context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace System.Globalization { // List of calendar data // Note the we cache overrides. // Note that localized names (resource names) aren't available from here. // // NOTE: Calendars depend on the locale name that creates it. Only a few // properties are available without locales using CalendarData.GetCalendar(CalendarData) // internal partial class CalendarData { // Max calendars internal const int MAX_CALENDARS = 23; // Identity internal string sNativeName = null!; // Calendar Name for the locale // Formats internal string[] saShortDates = null!; // Short Data format, default first internal string[] saYearMonths = null!; // Year/Month Data format, default first internal string[] saLongDates = null!; // Long Data format, default first internal string sMonthDay = null!; // Month/Day format // Calendar Parts Names internal string[] saEraNames = null!; // Names of Eras internal string[] saAbbrevEraNames = null!; // Abbreviated Era Names internal string[] saAbbrevEnglishEraNames = null!; // Abbreviated Era Names in English internal string[] saDayNames = null!; // Day Names, null to use locale data, starts on Sunday internal string[] saAbbrevDayNames = null!; // Abbrev Day Names, null to use locale data, starts on Sunday internal string[] saSuperShortDayNames = null!; // Super short Day of week names internal string[] saMonthNames = null!; // Month Names (13) internal string[] saAbbrevMonthNames = null!; // Abbrev Month Names (13) internal string[] saMonthGenitiveNames = null!; // Genitive Month Names (13) internal string[] saAbbrevMonthGenitiveNames = null!; // Genitive Abbrev Month Names (13) internal string[] saLeapYearMonthNames = null!; // Multiple strings for the month names in a leap year. // Integers at end to make marshaller happier internal int iTwoDigitYearMax = 2029; // Max 2 digit year (for Y2K bug data entry) internal int iCurrentEra = 0; // current era # (usually 1) // Use overrides? internal bool bUseUserOverrides; // True if we want user overrides. // Static invariant for the invariant locale internal static readonly CalendarData Invariant = CreateInvariant(); // Private constructor private CalendarData() { } // Invariant factory private static CalendarData CreateInvariant() { // Set our default/gregorian US calendar data // Calendar IDs are 1-based, arrays are 0 based. CalendarData invariant = new CalendarData(); // Set default data for calendar // Note that we don't load resources since this IS NOT supposed to change (by definition) invariant.sNativeName = "Gregorian Calendar"; // Calendar Name // Year invariant.iTwoDigitYearMax = 2029; // Max 2 digit year (for Y2K bug data entry) invariant.iCurrentEra = 1; // Current era # // Formats invariant.saShortDates = new string[] { "MM/dd/yyyy", "yyyy-MM-dd" }; // short date format invariant.saLongDates = new string[] { "dddd, dd MMMM yyyy" }; // long date format invariant.saYearMonths = new string[] { "yyyy MMMM" }; // year month format invariant.sMonthDay = "MMMM dd"; // Month day pattern // Calendar Parts Names invariant.saEraNames = new string[] { "A.D." }; // Era names invariant.saAbbrevEraNames = new string[] { "AD" }; // Abbreviated Era names invariant.saAbbrevEnglishEraNames = new string[] { "AD" }; // Abbreviated era names in English invariant.saDayNames = new string[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; // day names invariant.saAbbrevDayNames = new string[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; // abbreviated day names invariant.saSuperShortDayNames = new string[] { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; // The super short day names invariant.saMonthNames = new string[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", string.Empty }; // month names invariant.saAbbrevMonthNames = new string[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", string.Empty }; // abbreviated month names invariant.saMonthGenitiveNames = invariant.saMonthNames; // Genitive month names (same as month names for invariant) invariant.saAbbrevMonthGenitiveNames = invariant.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant) invariant.saLeapYearMonthNames = invariant.saMonthNames; // leap year month names are unused in Gregorian English (invariant) invariant.bUseUserOverrides = false; return invariant; } // // Get a bunch of data for a calendar // internal CalendarData(string localeName, CalendarId calendarId, bool bUseUserOverrides) { this.bUseUserOverrides = bUseUserOverrides; Debug.Assert(!GlobalizationMode.Invariant); if (!LoadCalendarDataFromSystem(localeName, calendarId)) { // LoadCalendarDataFromSystem sometimes can fail on Linux if the installed ICU package is missing some resources. // The ICU package can miss some resources in some cases like if someone compile and build the ICU package manually or ICU has a regression. // Something failed, try invariant for missing parts // This is really not good, but we don't want the callers to crash. this.sNativeName ??= string.Empty; // Calendar Name for the locale. // Formats this.saShortDates ??= Invariant.saShortDates; // Short Data format, default first this.saYearMonths ??= Invariant.saYearMonths; // Year/Month Data format, default first this.saLongDates ??= Invariant.saLongDates; // Long Data format, default first this.sMonthDay ??= Invariant.sMonthDay; // Month/Day format // Calendar Parts Names this.saEraNames ??= Invariant.saEraNames; // Names of Eras this.saAbbrevEraNames ??= Invariant.saAbbrevEraNames; // Abbreviated Era Names this.saAbbrevEnglishEraNames ??= Invariant.saAbbrevEnglishEraNames; // Abbreviated Era Names in English this.saDayNames ??= Invariant.saDayNames; // Day Names, null to use locale data, starts on Sunday this.saAbbrevDayNames ??= Invariant.saAbbrevDayNames; // Abbrev Day Names, null to use locale data, starts on Sunday this.saSuperShortDayNames ??= Invariant.saSuperShortDayNames; // Super short Day of week names this.saMonthNames ??= Invariant.saMonthNames; // Month Names (13) this.saAbbrevMonthNames ??= Invariant.saAbbrevMonthNames; // Abbrev Month Names (13) // Genitive and Leap names can follow the fallback below } if (calendarId == CalendarId.TAIWAN) { if (SystemSupportsTaiwaneseCalendar()) { // We got the month/day names from the OS (same as gregorian), but the native name is wrong this.sNativeName = "\x4e2d\x83ef\x6c11\x570b\x66c6"; } else { this.sNativeName = string.Empty; } } // Check for null genitive names (in case unmanaged side skips it for non-gregorian calendars, etc) if (this.saMonthGenitiveNames == null || this.saMonthGenitiveNames.Length == 0 || string.IsNullOrEmpty(this.saMonthGenitiveNames[0])) this.saMonthGenitiveNames = this.saMonthNames; // Genitive month names (same as month names for invariant) if (this.saAbbrevMonthGenitiveNames == null || this.saAbbrevMonthGenitiveNames.Length == 0 || string.IsNullOrEmpty(this.saAbbrevMonthGenitiveNames[0])) this.saAbbrevMonthGenitiveNames = this.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant) if (this.saLeapYearMonthNames == null || this.saLeapYearMonthNames.Length == 0 || string.IsNullOrEmpty(this.saLeapYearMonthNames[0])) this.saLeapYearMonthNames = this.saMonthNames; InitializeEraNames(localeName, calendarId); InitializeAbbreviatedEraNames(localeName, calendarId); // Abbreviated English Era Names are only used for the Japanese calendar. if (calendarId == CalendarId.JAPAN) { this.saAbbrevEnglishEraNames = JapaneseCalendar.EnglishEraNames(); } else { // For all others just use the an empty string (doesn't matter we'll never ask for it for other calendars) this.saAbbrevEnglishEraNames = new string[] { "" }; } // Japanese is the only thing with > 1 era. Its current era # is how many ever // eras are in the array. (And the others all have 1 string in the array) this.iCurrentEra = this.saEraNames.Length; } private void InitializeEraNames(string localeName, CalendarId calendarId) { // Note that the saEraNames only include "A.D." We don't have localized names for other calendars available from windows switch (calendarId) { // For Localized Gregorian we really expect the data from the OS. case CalendarId.GREGORIAN: // Fallback for CoreCLR < Win7 or culture.dll missing if (this.saEraNames == null || this.saEraNames.Length == 0 || string.IsNullOrEmpty(this.saEraNames[0])) { this.saEraNames = new string[] { "A.D." }; } break; // The rest of the calendars have constant data, so we'll just use that case CalendarId.GREGORIAN_US: case CalendarId.JULIAN: this.saEraNames = new string[] { "A.D." }; break; case CalendarId.HEBREW: this.saEraNames = new string[] { "C.E." }; break; case CalendarId.HIJRI: case CalendarId.UMALQURA: if (localeName == "dv-MV") { // Special case for Divehi this.saEraNames = new string[] { "\x0780\x07a8\x0796\x07b0\x0783\x07a9" }; } else { this.saEraNames = new string[] { "\x0628\x0639\x062F \x0627\x0644\x0647\x062C\x0631\x0629" }; } break; case CalendarId.GREGORIAN_ARABIC: case CalendarId.GREGORIAN_XLIT_ENGLISH: case CalendarId.GREGORIAN_XLIT_FRENCH: // These are all the same: this.saEraNames = new string[] { "\x0645" }; break; case CalendarId.GREGORIAN_ME_FRENCH: this.saEraNames = new string[] { "ap. J.-C." }; break; case CalendarId.TAIWAN: if (SystemSupportsTaiwaneseCalendar()) { this.saEraNames = new string[] { "\x4e2d\x83ef\x6c11\x570b" }; } else { this.saEraNames = new string[] { string.Empty }; } break; case CalendarId.KOREA: this.saEraNames = new string[] { "\xb2e8\xae30" }; break; case CalendarId.THAI: this.saEraNames = new string[] { "\x0e1e\x002e\x0e28\x002e" }; break; case CalendarId.JAPAN: case CalendarId.JAPANESELUNISOLAR: this.saEraNames = JapaneseCalendar.EraNames(); break; case CalendarId.PERSIAN: if (this.saEraNames == null || this.saEraNames.Length == 0 || string.IsNullOrEmpty(this.saEraNames[0])) { this.saEraNames = new string[] { "\x0647\x002e\x0634" }; } break; default: // Most calendars are just "A.D." this.saEraNames = Invariant.saEraNames; break; } } private void InitializeAbbreviatedEraNames(string localeName, CalendarId calendarId) { // Note that the saAbbrevEraNames only include "AD" We don't have localized names for other calendars available from windows switch (calendarId) { // For Localized Gregorian we really expect the data from the OS. case CalendarId.GREGORIAN: // Fallback for CoreCLR < Win7 or culture.dll missing if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || string.IsNullOrEmpty(this.saAbbrevEraNames[0])) { this.saAbbrevEraNames = new string[] { "AD" }; } break; // The rest of the calendars have constant data, so we'll just use that case CalendarId.GREGORIAN_US: case CalendarId.JULIAN: this.saAbbrevEraNames = new string[] { "AD" }; break; case CalendarId.JAPAN: case CalendarId.JAPANESELUNISOLAR: this.saAbbrevEraNames = JapaneseCalendar.AbbrevEraNames(); break; case CalendarId.HIJRI: case CalendarId.UMALQURA: if (localeName == "dv-MV") { // Special case for Divehi this.saAbbrevEraNames = new string[] { "\x0780\x002e" }; } else { this.saAbbrevEraNames = new string[] { "\x0647\x0640" }; } break; case CalendarId.TAIWAN: // Get era name and abbreviate it this.saAbbrevEraNames = new string[1]; if (this.saEraNames[0].Length == 4) { this.saAbbrevEraNames[0] = this.saEraNames[0].Substring(2, 2); } else { this.saAbbrevEraNames[0] = this.saEraNames[0]; } break; case CalendarId.PERSIAN: if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || string.IsNullOrEmpty(this.saAbbrevEraNames[0])) { this.saAbbrevEraNames = this.saEraNames; } break; default: // Most calendars just use the full name this.saAbbrevEraNames = this.saEraNames; break; } } internal static CalendarData GetCalendarData(CalendarId calendarId) { // // Get a calendar. // Unfortunately we depend on the locale in the OS, so we need a locale // no matter what. So just get the appropriate calendar from the // appropriate locale here // // Get a culture name // TODO: Note that this doesn't handle the new calendars (lunisolar, etc) string culture = CalendarIdToCultureName(calendarId); // Return our calendar return CultureInfo.GetCultureInfo(culture)._cultureData.GetCalendar(calendarId); } private static string CalendarIdToCultureName(CalendarId calendarId) { switch (calendarId) { case CalendarId.GREGORIAN_US: return "fa-IR"; // "fa-IR" Iran case CalendarId.JAPAN: return "ja-JP"; // "ja-JP" Japan case CalendarId.TAIWAN: return "zh-TW"; // zh-TW Taiwan case CalendarId.KOREA: return "ko-KR"; // "ko-KR" Korea case CalendarId.HIJRI: case CalendarId.GREGORIAN_ARABIC: case CalendarId.UMALQURA: return "ar-SA"; // "ar-SA" Saudi Arabia case CalendarId.THAI: return "th-TH"; // "th-TH" Thailand case CalendarId.HEBREW: return "he-IL"; // "he-IL" Israel case CalendarId.GREGORIAN_ME_FRENCH: return "ar-DZ"; // "ar-DZ" Algeria case CalendarId.GREGORIAN_XLIT_ENGLISH: case CalendarId.GREGORIAN_XLIT_FRENCH: return "ar-IQ"; // "ar-IQ"; Iraq default: // Default to gregorian en-US break; } return "en-US"; } } }
// Copyright 2019 Esri // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ArcGIS.Desktop.Framework; using ArcGIS.Desktop.Framework.Contracts; using ArcGIS.Desktop.Mapping; using ArcGIS.Desktop.Core.Geoprocessing; using ArcGIS.Desktop.Core; using ArcGIS.Core.CIM; using ArcGIS.Desktop.Framework.Threading.Tasks; using System.Collections.Specialized; using ArcGIS.Desktop.Framework.Dialogs; using System.Threading; namespace WorkingWithRasterLayers { static class RasterLayersVM { /// <summary> /// Create an image service layer and add it to the first 2D map. /// </summary> /// <returns>Task that contains a layer.</returns> public static async Task AddRasterLayerToMapAsync() { try { // Get the first 2D map from the project that is called Map. Map _map = await GetMapFromProject(Project.Current, "Map"); if (_map == null) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("AddRasterLayerToMap: Failed to get map."); return; } // Create a url pointing to the source. In this case it is a url to an image service // which will result in an image service layer being created. string dataSoureUrl = @"https://landsat2.arcgis.com/arcgis/services/Landsat/MS/ImageServer"; // Note: A url can also point to // 1.) An image on disk or an in a file geodatabase. e.g. string dataSoureUrl = @"C:\temp\a.tif"; This results in a raster layer. // 2.) A mosaic dataset in a file gdb e.g. string dataSoureUrl = @"c:\temp\mygdb.gdb\MyMosaicDataset"; This results in a mosaic layer. // 3.) A raster or mosaic dataset in an enterprise geodatabase. // Create an ImageServiceLayer object to hold the new layer. ImageServiceLayer imageServiceLayer = null; // The layer has to be created on the Main CIM Thread (MCT). await QueuedTask.Run(() => { // Create a layer based on the url. In this case the layer we are creating is an image service layer. imageServiceLayer = (ImageServiceLayer)LayerFactory.Instance.CreateLayer(new Uri(dataSoureUrl), _map); if (imageServiceLayer == null) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Failed to create layer for url:" + dataSoureUrl); return; } }); } catch (Exception exc) { // Catch any exception found and display a message box. ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Exception caught while trying to add layer: " + exc.Message); return; } } /// <summary> /// Set the resampling type on the first selected image service layer in the first open 2D map. /// </summary> /// <param name="resamplingType">The resampling type to set on the layer.</param> /// <returns></returns> public static async Task SetResamplingTypeAsync(RasterResamplingType resamplingType) { try { // Get the first 2D map from the project that is called Map. Map _map = await GetMapFromProject(Project.Current, "Map"); if (_map == null) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("SetResamplingType: Failed to get map."); return; } // Get the most recently selected layer. Layer firstSelectedLayer = MapView.Active.GetSelectedLayers().First(); // Check if the first selected layer is an image service layer. if (firstSelectedLayer is ImageServiceLayer) { // Set the colorizer on the most recently selected layer. // The colorizer has to be get/set on the Main CIM Thread (MCT). await QueuedTask.Run(() => { // Get the colorizer from the selected layer. CIMRasterColorizer newColorizer = ((BasicRasterLayer)firstSelectedLayer).GetColorizer(); // Set the resampling type on the colorizer. newColorizer.ResamplingType = resamplingType; // Update the image service with the new colorizer ((BasicRasterLayer)firstSelectedLayer).SetColorizer(newColorizer); }); } } catch (Exception exc) { // Catch any exception found and display a message box. ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Exception caught while trying to set resampling type: " + exc.Message); return; } } /// <summary> /// Set the processing template on the first selected image service layer in the first open 2D map. /// </summary> /// <param name="templateName">The name of the processing template to set on the layer.</param> /// <returns></returns> public static async Task SetProcessingTemplateAsync(string templateName) { try { // Get the first 2D map from the project that is called Map. Map _map = await GetMapFromProject(Project.Current, "Map"); if (_map == null) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("SetResamplingType: Failed to get map."); return; } // Get the most recently selected layer. Layer firstSelectedLayer = MapView.Active.GetSelectedLayers().First(); // Check if the first selected layer is an image service layer. if (firstSelectedLayer is ImageServiceLayer) { // Set the colorizer on the most recently selected layer. // The colorizer has to be set on the Main CIM Thread (MCT). ImageServiceLayer isLayer = (ImageServiceLayer)firstSelectedLayer; await QueuedTask.Run(() => { // Create a new Rendering rule CIMRenderingRule setRenderingrule = new CIMRenderingRule() { // Set the name of the rendering rule. Name = templateName }; // Update the image service with the new mosaic rule. isLayer.SetRenderingRule(setRenderingrule); }); } } catch (Exception exc) { // Catch any exception found and display a message box. ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Exception caught while trying to set processing template: " + exc.Message); return; } } /// <summary> /// Set the stretch type on the first selected image service layer in the first open 2D map. /// </summary> /// <param name="stretschType">The stretch type to set on the layer.</param> /// <param name="statsType">The stretch statistics type to set on the layer. This lets you pick between Dataset, Area of View (to enable DRA) or Custom statistics.</param> /// <returns></returns> public static async Task SetStretchTypeAsync(RasterStretchType stretschType, RasterStretchStatsType statsType = RasterStretchStatsType.Dataset) { try { // Get the first 2D map from the project that is called Map. Map _map = await GetMapFromProject(Project.Current, "Map"); if (_map == null) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("SetStretchType: Failed to get map."); return; } // Get the most recently selected layer. Layer firstSelectedLayer = MapView.Active.GetSelectedLayers().First(); // Check if the first selected layer is an image service layer. if (firstSelectedLayer is ImageServiceLayer) { // Set the colorizer on the most recently selected layer. // The colorizer has to be set on the Main CIM Thread (MCT). await QueuedTask.Run(() => { // Get the colorizer from the selected layer. CIMRasterColorizer newColorizer = ((BasicRasterLayer)firstSelectedLayer).GetColorizer(); // Set the stretch type and stretch statistics type on the colorizer. // Theese parameters only apply to the Stretch and RGB colorizers. if (newColorizer is CIMRasterRGBColorizer) { ((CIMRasterRGBColorizer)newColorizer).StretchType = stretschType; ((CIMRasterRGBColorizer)newColorizer).StretchStatsType = statsType; } else if (newColorizer is CIMRasterStretchColorizer) { ((CIMRasterStretchColorizer)newColorizer).StretchType = stretschType; ((CIMRasterStretchColorizer)newColorizer).StatsType = statsType; } else MessageBox.Show("Selected layer must be visualized using the RGB or Stretch colorizer"); // Update the image service with the new colorizer ((BasicRasterLayer)firstSelectedLayer).SetColorizer(newColorizer); }); } } catch (Exception exc) { // Catch any exception found and display a message box. ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Exception caught while trying to set stretch type: " + exc.Message); return; } } /// <summary> /// Set the compression type and compression quality (if applicable) on the first selected image service layer in the first open 2D map. /// </summary> /// <param name="type">The compression type to set on the layer.</param> /// <param name="quality">The compression quality to set on the layer.</param> /// <returns></returns> public static async Task SetCompressionAsync(string type, int quality = 80) { try { // Get the first 2D map from the project that is called Map. Map _map = await GetMapFromProject(Project.Current, "Map"); if (_map == null) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("SetCompression: Failed to get map."); return; } // Get the most recently selected layer. Layer firstSelectedLayer = MapView.Active.GetSelectedLayers().First(); // Check if the first selected layer is an image service layer. if (firstSelectedLayer is ImageServiceLayer) { // Set the compression type and quality on the most recently selected layer. // The compression has to be set on the Main CIM Thread (MCT). await QueuedTask.Run(() => { ((ImageServiceLayer)firstSelectedLayer).SetCompression(type, quality); }); } } catch (Exception exc) { // Catch any exception found and display a message box. ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Exception caught while trying to set compression: " + exc.Message); return; } } /// <summary> /// Gets the map from a project that matches a map name. /// </summary> /// <param name="project">The project in which the map resides.</param> /// <param name="mapName">The map name to identify the map.</param> /// <returns>A Task representing the map.</returns> private static Task<Map> GetMapFromProject(Project project, string mapName) { // Return null if either of the two parameters are invalid. if (project == null || string.IsNullOrEmpty(mapName)) return null; // Find the first project item with name matches with mapName MapProjectItem mapProjItem = project.GetItems<MapProjectItem>().FirstOrDefault(item => item.Name.Equals(mapName, StringComparison.CurrentCultureIgnoreCase)); if (mapProjItem != null) return QueuedTask.Run<Map>(() => { return mapProjItem.GetMap(); }, Progressor.None); else return null; } } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.SPOT.Platform.Test; namespace Microsoft.SPOT.Platform.Tests { public class ArithmeticTests1 : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } //Arithmetic Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Arithmetic //arith001,arith003,arith005,arith007,arith023,arith024,arith028,arith029,arith030,arith031,arith032,arith033,arith034,arith035,arith036,arith037,arith038,arith039,arith040,arith041,arith042,arith043,arith044,arith045,arith046,arith047,arith048,arith049,arith050,arith051,arith052,arith053,arith054,arith055,arith056,arith057,arith058,arith059,arith060,arith061,arith062,arith064,arith065 //opt001a,opt001b,opt002a,opt002b,opt003a,opt003b,opt004a,opt004b,mult0001,mult0002,mult0003,mult0004,mult0008,mult0009,mult0010,mult0011,mult0015,mult0016,mult0017,mult0018,mult0022,mult0023,mult0024,mult0025,mult0050,mult0051,mult0052,mult0053,mult0057,mult0058,mult0059,mult0060,mult0064,mult0065,mult0066,mult0067,mult0071,mult0072,mult0073,mult0074,div0001,div0002,div0008,div0009,div0015,div0016,div0022,div0023,div0050,div0051,div0057,div0058,div0064,div0065,div0071,div0072,rem0001,rem0002,rem0008,rem0009,rem0015,rem0016,rem0022,rem0023,rem0050,rem0051,rem0057,rem0058,rem0064,rem0065,rem0071,rem0072,add0001,add0002,add0003,add0007,add0008,add0009,add0013,add0014,add0015,add0037,add0038,add0039,add0043,add0044,add0045,add0049,add0050,add0051,sub0001,sub0002,sub0003,sub0007,sub0008,sub0009,sub0013,sub0014,sub0015,sub0037,sub0038,sub0039,sub0043,sub0044,sub0045,sub0049,sub0050,sub0051 //Test Case Calls [TestMethod] public MFTestResults Arith_arith001_Test() { Log.Comment("Section 7.4 "); Log.Comment("This code tests basic literal integral arthimetic additive expressions."); if (Arith_TestClass_arith001.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith003_Test() { Log.Comment("Section 7.4 "); Log.Comment("This code tests basic literal integral arthimetic multiplicative expressions."); if (Arith_TestClass_arith003.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith005_Test() { Log.Comment("Section 7.4 "); Log.Comment("This code tests basic integral arthimetic additive expressions using variables."); if (Arith_TestClass_arith005.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith007_Test() { Log.Comment("Section 7.4 "); Log.Comment("This code tests basic integral arthimetic multiplicative expressions with variables."); if (Arith_TestClass_arith007.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith023_Test() { Log.Comment("Section 7.4 "); Log.Comment("This code tests enum additive expressions."); if (Arith_TestClass_arith023.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith024_Test() { Log.Comment("Section 7.4 "); Log.Comment("This code tests enum additive expressions."); if (Arith_TestClass_arith024.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith028_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith028.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith029_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith029.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith030_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith030.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith031_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith031.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith032_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith032.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith033_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith033.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith034_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith034.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith035_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith035.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith036_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith036.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith037_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith037.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith038_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith038.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith039_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith039.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith040_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith040.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith041_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith041.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith042_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith042.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith043_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith043.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith044_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith044.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith045_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith045.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith046_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith046.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith047_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith047.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith048_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith048.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith049_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith049.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith050_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith050.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith051_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith051.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith052_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith052.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith053_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith053.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith054_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith054.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith055_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith055.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith056_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith056.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith057_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith057.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith058_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith058.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith059_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith059.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith060_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith060.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith061_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith061.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith062_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith062.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith064_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith064.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } [TestMethod] public MFTestResults Arith_arith065_Test() { Log.Comment("Section 7.7"); if (Arith_TestClass_arith065.testMethod()) { return MFTestResults.Pass; } return MFTestResults.Fail; } //Compiled Test Cases public class Arith_TestClass_arith001 { public static int Main_old() { int intRet = 0; //Scenario 1: type int if (5 != (3 + 2)) { intRet = 1; Log.Comment("Failure at Scenario 1"); } //Scenario 2: type int if (4 != (9 - 5)) { Log.Comment("Failure at Scenario 2"); intRet = 1; } //Scenario 7: type long if (1047L != (999L + 48L)) { Log.Comment("Failure at Scenario 7"); intRet = 1; } //Scenario 8: type long if (441L != (786L - 345L)) { Log.Comment("Failure at Scenario 8"); intRet = 1; } return intRet; } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith003 { public static int Main_old() { int intRet = 0; //Scenario 1: type int if (12 != (4 * 3)) { Log.Comment("Failure at Scenario 1"); intRet = 1; } //Scenario 2: type int if (4 != (8 / 2)) { Log.Comment("Failure at Scenario 2"); intRet = 1; } //Scenario 3; type int if (14 != (64 % 25)) { Log.Comment("Failure at Scenario 3"); intRet = 1; } //Scenario 10: type long if (361362L != (458L * 789L)) { Log.Comment("Failure at Scenario 10"); intRet = 1; } //Scenario 11: type long if (36L != (32004L / 889L)) { Log.Comment("Failure at Scenario 11"); intRet = 1; } //Scenario 12: type long if (29L != (985013L % 56L)) { Log.Comment("Failure at Scenario 12"); intRet = 1; } return intRet; } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith005 { public static int Main_old() { int intRet = 0; int i1 = 0; int i2 = 0; int i3 = 0; byte b1 = 0; byte b2 = 0; byte b3 = 0; short s1 = 0; short s2 = 0; short s3 = 0; long l1 = 0L; long l2 = 0L; long l3 = 0L; //Scenario 1: type int i1 = 7; i2 = 2; i3 = 5; if (i1 != (i2 + i3)) { Log.Comment("Failure at Scenario 1"); intRet = 1; } //Scenario 2: type int i1 = 16; i2 = 19; i3 = 3; if (i1 != (i2 - i3)) { Log.Comment("Failure at Scenario 2"); intRet = 1; } //Scenario 3: type byte b1 = 88; b2 = 86; b3 = 2; if (b1 != (b2 + b3)) { Log.Comment("Failure at Scenario 3"); intRet = 1; } //Scenario 4: type byte b1 = 62; b2 = 101; b3 = 39; if (b1 != (b2 - b3)) { Log.Comment("Failure at Scenario 4"); intRet = 1; } //Scenario 5: type short s1 = 45; s2 = 23; s3 = 22; if (s1 != (s2 + s3)) { Log.Comment("Failure at Scenario 5"); intRet = 1; } //Scenario 6: type short s1 = 87; s2 = 101; s3 = 14; if (s1 != (s2 - s3)) { Log.Comment("Failure at Scenario 6"); intRet = 1; } //Scenario 7: type long l1 = 5422L; l2 = 4567L; l3 = 855L; if (l1 != (l2 + l3)) { Log.Comment("Failure at Scenario 7"); intRet = 1; } //Scenario 8: type long l1 = 55423L; l2 = 192343L; l3 = 136920L; if (l1 != (l2 - l3)) { Log.Comment("Failure at Scenario 8"); intRet = 1; } return intRet; } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith007 { public static int Main_old() { int intRet = 0; int i1 = 0; int i2 = 0; int i3 = 0; byte b1 = 0; byte b2 = 0; byte b3 = 0; short s1 = 0; short s2 = 0; short s3 = 0; long l1 = 0L; long l2 = 0L; long l3 = 0L; //Scenario 1: type int i1 = 42; i2 = 7; i3 = 6; if (i1 != (i2 * i3)) { Log.Comment("Failure at Scenario 1"); intRet = 1; } //Scenario 2: type int i1 = 11; i2 = 154; i3 = 14; if (i1 != (i2 / i3)) { Log.Comment("Failure at Scenario 2"); intRet = 1; } //Scenario 3; type int i1 = 2; i2 = 95; i3 = 31; if (i1 != (i2 % i3)) { Log.Comment("Failure at Scenario 3"); intRet = 1; } //Scenario 4: type byte b1 = 94; b2 = 2; b3 = 47; if (b1 != (b2 * b3)) { Log.Comment("Failure at Scenario 4"); intRet = 1; } //Scenario 5: type byte b1 = 16; b2 = 96; b3 = 6; if (b1 != (b2 / b3)) { Log.Comment("Failure at Scenario 5"); intRet = 1; } //Scenario 6: type byte b1 = 48; b2 = 220; b3 = 86; if (b1 != (b2 % b3)) { Log.Comment("Failure at Scenario 6"); intRet = 1; } //Scenario 7: type short s1 = 8890; s2 = 254; s3 = 35; if (s1 != (s2 * s3)) { Log.Comment("Failure at Scenario 7"); intRet = 1; } //Scenario 8: type short s1 = 896; s2 = 23296; s3 = 26; if (s1 != (s2 / s3)) { Log.Comment("Failure at Scenario 8"); intRet = 1; } //Scenario 9: type short s1 = 72; s2 = 432; s3 = 90; if (s1 != (s2 % s3)) { Log.Comment("Failure at Scenario 9"); intRet = 1; } //Scenario 10: type long l1 = 3724L; l2 = 38L; l3 = 98L; if (l1 != (l2 * l3)) { Log.Comment("Failure at Scenario 10"); intRet = 1; } //Scenario 11: type long l1 = 821L; l2 = 5747L; l3 = 7L; if (l1 != (l2 / l3)) { Log.Comment("Failure at Scenario 11"); intRet = 1; } //Scenario 12: type long l1 = 89L; l2 = 22989L; l3 = 458L; if (l1 != (l2 % l3)) { Log.Comment("Failure at Scenario 12"); intRet = 1; } return intRet; } public static bool testMethod() { return (Main_old() == 0); } } enum Arith_TestClass_arith023_Enum { a = 1, b = 2 } public class Arith_TestClass_arith023 { public static int Main_old() { int MyInt = Arith_TestClass_arith023_Enum.a - Arith_TestClass_arith023_Enum.b; //E-E if (MyInt == -1) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } enum Arith_TestClass_arith024_Enum { a = 1, b = 2 } public class Arith_TestClass_arith024 { public static int Main_old() { Arith_TestClass_arith024_Enum MyEnum = Arith_TestClass_arith024_Enum.a + 3; //E+U if ((int)MyEnum == 4) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith028 { public static int Main_old() { int i1 = 2; if ((0 * i1) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith029 { public static int Main_old() { int i1 = 2; if ((i1 * 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith030 { public static int Main_old() { byte b1 = 2; if ((b1 * 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith031 { public static int Main_old() { sbyte sb1 = 2; if ((sb1 * 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith032 { public static int Main_old() { short s1 = 2; if ((s1 * 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith033 { public static int Main_old() { ushort us1 = 2; if ((us1 * 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith034 { public static int Main_old() { uint ui1 = 2; if ((ui1 * 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith035 { public static int Main_old() { long l1 = 2; if ((l1 * 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith036 { public static int Main_old() { ulong ul1 = 2; if ((ul1 * 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith037 { public static int Main_old() { char c1 = (char)2; if ((c1 * 0) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith038 { public static int Main_old() { int i1 = 2; if ((0 / i1) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith039 { public static int Main_old() { sbyte sb1 = 2; if ((0 / sb1) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith040 { public static int Main_old() { byte b1 = 2; if ((0 / b1) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith041 { public static int Main_old() { short s1 = 2; if ((0 / s1) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith042 { public static int Main_old() { ushort us1 = 2; if ((0 / us1) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith043 { public static int Main_old() { uint ui1 = 2; if ((0 / ui1) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith044 { public static int Main_old() { long l1 = 2; if ((0 / l1) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith045 { public static int Main_old() { ulong ul1 = 2; if ((0 / ul1) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith046 { public static int Main_old() { char c1 = (char)2; if ((0 / c1) == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith047 { public static int Main_old() { int i1 = (int)(0x80000000 / -1); if (i1 == int.MinValue) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith048 { public static int Main_old() { int i1 = (int)(0x80000000 % -1); if (i1 == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith049 { public static int Main_old() { string s1 = "foo" + "bar"; if (s1 == "foobar") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith050 { public static int Main_old() { string s1 = null + "foo"; if (s1 == "foo") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith051 { public static int Main_old() { string s1 = "foo" + null; if (s1 == "foo") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith052 { public static int Main_old() { string s1 = "" + "foo"; if (s1 == "foo") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith053 { public static int Main_old() { string s1 = "foo" + ""; if (s1 == "foo") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith054 { public static int Main_old() { string s1 = ("foo" + "bar"); if (s1 == "foobar") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith055 { public static int Main_old() { string s1 = ("f" + ("oo" + "bar")); if (s1 == "foobar") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith056 { public static int Main_old() { string s1 = (("f" + "oo") + "ba" + "r"); if (s1 == "foobar") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith057 { public static int Main_old() { string s1 = "foo"; string s2 = "bar"; return 0; string str = s1 + s2 + "!"; } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith058 { public static int Main_old() { int intI = -1 / int.MaxValue; if (intI == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith059 { public static int Main_old() { int intI = 1 / int.MaxValue; if (intI == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith060 { public static int Main_old() { int intI = -1 / int.MinValue; if (intI == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith061 { public static int Main_old() { int intI = 1 / int.MinValue; if (intI == 0) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith062 { public static int Main_old() { int intI = int.MaxValue / -1; if (intI == -2147483647) { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith064 { public static implicit operator string(Arith_TestClass_arith064 MC) { return "foo"; } public static int Main_old() { Arith_TestClass_arith064 MC = new Arith_TestClass_arith064(); string TestString1 = "bar"; if ((MC + TestString1) == "foobar") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } public class Arith_TestClass_arith065 { public static implicit operator string(Arith_TestClass_arith065 MC) { return "bar"; } public static int Main_old() { Arith_TestClass_arith065 MC = new Arith_TestClass_arith065(); string TestString1 = "foo"; if ((TestString1 + MC) == "foobar") { return 0; } else { return 1; } } public static bool testMethod() { return (Main_old() == 0); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using SR = System.Reflection; using System.Runtime.CompilerServices; using SquabPie.Mono.Cecil.Cil; using NUnit.Framework; namespace SquabPie.Mono.Cecil.Tests { [TestFixture] public class ImportReflectionTests : BaseTestFixture { [Test] public void ImportString () { var get_string = Compile<Func<string>> ((_, body) => { var il = body.GetILProcessor (); il.Emit (OpCodes.Ldstr, "yo dawg!"); il.Emit (OpCodes.Ret); }); Assert.AreEqual ("yo dawg!", get_string ()); } [Test] public void ImportInt () { var add = Compile<Func<int, int, int>> ((_, body) => { var il = body.GetILProcessor (); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ldarg_1); il.Emit (OpCodes.Add); il.Emit (OpCodes.Ret); }); Assert.AreEqual (42, add (40, 2)); } [Test] public void ImportStringByRef () { var get_string = Compile<Func<string, string>> ((module, body) => { var type = module.Types [1]; var method_by_ref = new MethodDefinition { Name = "ModifyString", IsPrivate = true, IsStatic = true, }; type.Methods.Add (method_by_ref); method_by_ref.MethodReturnType.ReturnType = module.ImportReference (typeof (void)); method_by_ref.Parameters.Add (new ParameterDefinition (module.ImportReference (typeof (string)))); method_by_ref.Parameters.Add (new ParameterDefinition (module.ImportReference (typeof (string).MakeByRefType ()))); var m_il = method_by_ref.Body.GetILProcessor (); m_il.Emit (OpCodes.Ldarg_1); m_il.Emit (OpCodes.Ldarg_0); m_il.Emit (OpCodes.Stind_Ref); m_il.Emit (OpCodes.Ret); var v_0 = new VariableDefinition (module.ImportReference (typeof (string))); body.Variables.Add (v_0); var il = body.GetILProcessor (); il.Emit (OpCodes.Ldnull); il.Emit (OpCodes.Stloc, v_0); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ldloca, v_0); il.Emit (OpCodes.Call, method_by_ref); il.Emit (OpCodes.Ldloc_0); il.Emit (OpCodes.Ret); }); Assert.AreEqual ("foo", get_string ("foo")); } [Test] public void ImportStringArray () { var identity = Compile<Func<string [,], string [,]>> ((module, body) => { var il = body.GetILProcessor (); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ret); }); var array = new string [2, 2]; Assert.AreEqual (array, identity (array)); } [Test] public void ImportFieldStringEmpty () { var get_empty = Compile<Func<string>> ((module, body) => { var il = body.GetILProcessor (); il.Emit (OpCodes.Ldsfld, module.ImportReference (typeof (string).GetField ("Empty"))); il.Emit (OpCodes.Ret); }); Assert.AreEqual ("", get_empty ()); } [Test] public void ImportStringConcat () { var concat = Compile<Func<string, string, string>> ((module, body) => { var il = body.GetILProcessor (); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ldarg_1); il.Emit (OpCodes.Call, module.ImportReference (typeof (string).GetMethod ("Concat", new [] { typeof (string), typeof (string) }))); il.Emit (OpCodes.Ret); }); Assert.AreEqual ("FooBar", concat ("Foo", "Bar")); } [Test] public void GeneratedAssemblyCulture () { var id = Compile<Func<int, int>> ((module, body) => { var il = body.GetILProcessor (); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ret); }); Assert.AreEqual ("", id.Method.DeclaringType.Assembly.GetName ().CultureInfo.Name); } public class Generic<T> { public T Field; public T Method (T t) { return t; } public TS GenericMethod<TS> (T t, TS s) { return s; } public Generic<TS> ComplexGenericMethod<TS> (T t, TS s) { return new Generic<TS> { Field = s }; } } [Test] public void ImportGenericField () { var get_field = Compile<Func<Generic<string>, string>> ((module, body) => { var il = body.GetILProcessor (); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ldfld, module.ImportReference (typeof (Generic<string>).GetField ("Field"))); il.Emit (OpCodes.Ret); }); var generic = new Generic<string> { Field = "foo", }; Assert.AreEqual ("foo", get_field (generic)); } [Test] public void ImportGenericMethod () { var generic_identity = Compile<Func<Generic<int>, int, int>> ((module, body) => { var il = body.GetILProcessor (); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ldarg_1); il.Emit (OpCodes.Callvirt, module.ImportReference (typeof (Generic<int>).GetMethod ("Method"))); il.Emit (OpCodes.Ret); }); Assert.AreEqual (42, generic_identity (new Generic<int> (), 42)); } [Test] public void ImportGenericMethodSpec () { var gen_spec_id = Compile<Func<Generic<string>, int, int>> ((module, body) => { var il = body.GetILProcessor (); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ldnull); il.Emit (OpCodes.Ldarg_1); il.Emit (OpCodes.Callvirt, module.ImportReference (typeof (Generic<string>).GetMethod ("GenericMethod").MakeGenericMethod (typeof (int)))); il.Emit (OpCodes.Ret); }); Assert.AreEqual (42, gen_spec_id (new Generic<string> (), 42)); } [Test] public void ImportComplexGenericMethodSpec () { var gen_spec_id = Compile<Func<Generic<string>, int, int>> ((module, body) => { var il = body.GetILProcessor (); il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Ldnull); il.Emit (OpCodes.Ldarg_1); il.Emit (OpCodes.Callvirt, module.ImportReference (typeof (Generic<string>).GetMethod ("ComplexGenericMethod").MakeGenericMethod (typeof (int)))); il.Emit (OpCodes.Ldfld, module.ImportReference (typeof (Generic<int>).GetField ("Field"))); il.Emit (OpCodes.Ret); }); Assert.AreEqual (42, gen_spec_id (new Generic<string> (), 42)); } public class Foo<TFoo> { public List<TFoo> list; } [Test] public void ImportGenericTypeDefOrOpen () { var module = typeof (Foo<>).ToDefinition ().Module; var foo_def = module.ImportReference (typeof (Foo<>)); var foo_open = module.ImportReference (typeof (Foo<>), foo_def); Assert.AreEqual ("SquabPie.Mono.Cecil.Tests.ImportReflectionTests/Foo`1", foo_def.FullName); Assert.AreEqual ("SquabPie.Mono.Cecil.Tests.ImportReflectionTests/Foo`1<TFoo>", foo_open.FullName); } [Test] public void ImportGenericTypeFromContext () { var list_foo = typeof (Foo<>).GetField ("list").FieldType; var generic_list_foo_open = typeof (Generic<>).MakeGenericType (list_foo); var foo_def = typeof (Foo<>).ToDefinition (); var module = foo_def.Module; var generic_foo = module.ImportReference (generic_list_foo_open, foo_def); Assert.AreEqual ("SquabPie.Mono.Cecil.Tests.ImportReflectionTests/Generic`1<System.Collections.Generic.List`1<TFoo>>", generic_foo.FullName); } [Test] public void ImportGenericTypeDefFromContext () { var foo_open = typeof (Foo<>).MakeGenericType (typeof (Foo<>).GetGenericArguments () [0]); var generic_foo_open = typeof (Generic<>).MakeGenericType (foo_open); var foo_def = typeof (Foo<>).ToDefinition (); var module = foo_def.Module; var generic_foo = module.ImportReference (generic_foo_open, foo_def); Assert.AreEqual ("SquabPie.Mono.Cecil.Tests.ImportReflectionTests/Generic`1<SquabPie.Mono.Cecil.Tests.ImportReflectionTests/Foo`1<TFoo>>", generic_foo.FullName); } [Test] public void ImportArrayTypeDefFromContext () { var foo_open = typeof (Foo<>).MakeGenericType (typeof (Foo<>).GetGenericArguments () [0]); var foo_open_array = foo_open.MakeArrayType (); var foo_def = typeof (Foo<>).ToDefinition (); var module = foo_def.Module; var array_foo = module.ImportReference (foo_open_array, foo_def); Assert.AreEqual ("SquabPie.Mono.Cecil.Tests.ImportReflectionTests/Foo`1<TFoo>[]", array_foo.FullName); } [Test] public void ImportGenericFieldFromContext () { var list_foo = typeof (Foo<>).GetField ("list").FieldType; var generic_list_foo_open = typeof (Generic<>).MakeGenericType (list_foo); var generic_list_foo_open_field = generic_list_foo_open.GetField ("Field"); var foo_def = typeof (Foo<>).ToDefinition (); var module = foo_def.Module; var generic_field = module.ImportReference (generic_list_foo_open_field, foo_def); Assert.AreEqual ("T SquabPie.Mono.Cecil.Tests.ImportReflectionTests/Generic`1<System.Collections.Generic.List`1<TFoo>>::Field", generic_field.FullName); } [Test] public void ImportGenericMethodFromContext () { var list_foo = typeof (Foo<>).GetField ("list").FieldType; var generic_list_foo_open = typeof (Generic<>).MakeGenericType (list_foo); var generic_list_foo_open_method = generic_list_foo_open.GetMethod ("Method"); var foo_def = typeof (Foo<>).ToDefinition (); var module = foo_def.Module; var generic_method = module.ImportReference (generic_list_foo_open_method, foo_def); Assert.AreEqual ("T SquabPie.Mono.Cecil.Tests.ImportReflectionTests/Generic`1<System.Collections.Generic.List`1<TFoo>>::Method(T)", generic_method.FullName); } [Test] public void ImportMethodOnOpenGenericType () { var module = typeof (Generic<>).ToDefinition ().Module; var method = module.ImportReference (typeof (Generic<>).GetMethod ("Method")); Assert.AreEqual ("T SquabPie.Mono.Cecil.Tests.ImportReflectionTests/Generic`1<T>::Method(T)", method.FullName); } [Test] public void ImportGenericMethodOnOpenGenericType () { var module = typeof (Generic<>).ToDefinition ().Module; var generic_method = module.ImportReference (typeof (Generic<>).GetMethod ("GenericMethod")); Assert.AreEqual ("TS SquabPie.Mono.Cecil.Tests.ImportReflectionTests/Generic`1<T>::GenericMethod(T,TS)", generic_method.FullName); generic_method = module.ImportReference (typeof (Generic<>).GetMethod ("GenericMethod"), generic_method); Assert.AreEqual ("TS SquabPie.Mono.Cecil.Tests.ImportReflectionTests/Generic`1<T>::GenericMethod<TS>(T,TS)", generic_method.FullName); } delegate void Emitter (ModuleDefinition module, MethodBody body); [MethodImpl (MethodImplOptions.NoInlining)] static TDelegate Compile<TDelegate> (Emitter emitter) where TDelegate : class { var name = GetTestCaseName (); var module = CreateTestModule<TDelegate> (name, emitter); var assembly = LoadTestModule (module); return CreateRunDelegate<TDelegate> (GetTestCase (name, assembly)); } static TDelegate CreateRunDelegate<TDelegate> (Type type) where TDelegate : class { return (TDelegate) (object) Delegate.CreateDelegate (typeof (TDelegate), type.GetMethod ("Run")); } static Type GetTestCase (string name, SR.Assembly assembly) { return assembly.GetType (name); } static SR.Assembly LoadTestModule (ModuleDefinition module) { using (var stream = new MemoryStream ()) { module.Write (stream); File.WriteAllBytes (Path.Combine (Path.Combine (Path.GetTempPath (), "cecil"), module.Name + ".dll"), stream.ToArray ()); return SR.Assembly.Load (stream.ToArray ()); } } static ModuleDefinition CreateTestModule<TDelegate> (string name, Emitter emitter) { var module = CreateModule (name); var type = new TypeDefinition ( "", name, TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Abstract, module.ImportReference (typeof (object))); module.Types.Add (type); var method = CreateMethod (type, typeof (TDelegate).GetMethod ("Invoke")); emitter (module, method.Body); return module; } static MethodDefinition CreateMethod (TypeDefinition type, SR.MethodInfo pattern) { var module = type.Module; var method = new MethodDefinition { Name = "Run", IsPublic = true, IsStatic = true, }; type.Methods.Add (method); method.MethodReturnType.ReturnType = module.ImportReference (pattern.ReturnType); foreach (var parameter_pattern in pattern.GetParameters ()) method.Parameters.Add (new ParameterDefinition (module.ImportReference (parameter_pattern.ParameterType))); return method; } static ModuleDefinition CreateModule (string name) { return ModuleDefinition.CreateModule (name, ModuleKind.Dll); } [MethodImpl (MethodImplOptions.NoInlining)] static string GetTestCaseName () { var stack_trace = new StackTrace (); var stack_frame = stack_trace.GetFrame (2); return "ImportReflection_" + stack_frame.GetMethod ().Name; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** Purpose: Create a Memorystream over an UnmanagedMemoryStream ** ===========================================================*/ using System; using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Threading; using System.Threading.Tasks; namespace System.IO { // Needed for backwards compatibility with V1.x usages of the // ResourceManager, where a MemoryStream is now returned as an // UnmanagedMemoryStream from ResourceReader. internal sealed class UnmanagedMemoryStreamWrapper : MemoryStream { private UnmanagedMemoryStream _unmanagedStream; internal UnmanagedMemoryStreamWrapper(UnmanagedMemoryStream stream) { _unmanagedStream = stream; } public override bool CanRead { get { return _unmanagedStream.CanRead; } } public override bool CanSeek { get { return _unmanagedStream.CanSeek; } } public override bool CanWrite { get { return _unmanagedStream.CanWrite; } } protected override void Dispose(bool disposing) { try { if (disposing) _unmanagedStream.Dispose(); } finally { base.Dispose(disposing); } } public override void Flush() { _unmanagedStream.Flush(); } public override byte[] GetBuffer() { throw new UnauthorizedAccessException(SR.UnauthorizedAccess_MemStreamBuffer); } public override bool TryGetBuffer(out ArraySegment<byte> buffer) { buffer = default(ArraySegment<byte>); return false; } public override int Capacity { get { return (int)_unmanagedStream.Capacity; } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. set { throw new IOException(SR.IO_FixedCapacity); } } public override long Length { get { return _unmanagedStream.Length; } } public override long Position { get { return _unmanagedStream.Position; } set { _unmanagedStream.Position = value; } } public override int Read(byte[] buffer, int offset, int count) { return _unmanagedStream.Read(buffer, offset, count); } public override int Read(Span<byte> destination) { return _unmanagedStream.Read(destination); } public override int ReadByte() { return _unmanagedStream.ReadByte(); } public override long Seek(long offset, SeekOrigin loc) { return _unmanagedStream.Seek(offset, loc); } public unsafe override byte[] ToArray() { byte[] buffer = new byte[_unmanagedStream.Length]; _unmanagedStream.Read(buffer, 0, (int)_unmanagedStream.Length); return buffer; } public override void Write(byte[] buffer, int offset, int count) { _unmanagedStream.Write(buffer, offset, count); } public override void Write(ReadOnlySpan<byte> source) { _unmanagedStream.Write(source); } public override void WriteByte(byte value) { _unmanagedStream.WriteByte(value); } // Writes this MemoryStream to another stream. public unsafe override void WriteTo(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream); Contract.EndContractBlock(); byte[] buffer = ToArray(); stream.Write(buffer, 0, buffer.Length); } public override void SetLength(Int64 value) { // This was probably meant to call _unmanagedStream.SetLength(value), but it was forgotten in V.4.0. // Now this results in a call to the base which touches the underlying array which is never actually used. // We cannot fix it due to compat now, but we should fix this at the next SxS release oportunity. base.SetLength(value); } public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) { // The parameter checks must be in sync with the base version: if (destination == null) throw new ArgumentNullException(nameof(destination)); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); if (!CanRead && !CanWrite) throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); if (!destination.CanRead && !destination.CanWrite) throw new ObjectDisposedException(nameof(destination), SR.ObjectDisposed_StreamClosed); if (!CanRead) throw new NotSupportedException(SR.NotSupported_UnreadableStream); if (!destination.CanWrite) throw new NotSupportedException(SR.NotSupported_UnwritableStream); Contract.EndContractBlock(); return _unmanagedStream.CopyToAsync(destination, bufferSize, cancellationToken); } public override Task FlushAsync(CancellationToken cancellationToken) { return _unmanagedStream.FlushAsync(cancellationToken); } public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { return _unmanagedStream.ReadAsync(buffer, offset, count, cancellationToken); } public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken)) { return _unmanagedStream.ReadAsync(destination, cancellationToken); } public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { return _unmanagedStream.WriteAsync(buffer, offset, count, cancellationToken); } public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken)) { return _unmanagedStream.WriteAsync(source, cancellationToken); } } // class UnmanagedMemoryStreamWrapper } // namespace
//Copyright 2010 Microsoft Corporation // //Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an //"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and limitations under the License. namespace System.Data.Services.Http { #region Namespaces. using System; using System.Globalization; using System.IO; using System.Text; using System.Threading; using System.Windows.Browser; using System.Diagnostics; #endregion Namespaces. internal sealed class XHRHttpWebRequest : System.Data.Services.Http.HttpWebRequest { #region Private fields. private bool aborted; private HttpWebRequestAsyncResult asyncRequestResult; private HttpWebRequestAsyncResult asyncResponseResult; private NonClosingMemoryStream contentStream; private System.Data.Services.Http.XHRWebHeaderCollection headers; private bool invoked; private string method; private System.Data.Services.Http.HttpWebResponse response; private ScriptXmlHttpRequest underlyingRequest; private Uri uri; #endregion Private fields. internal XHRHttpWebRequest(Uri uri) { Debug.Assert(uri != null, "uri != null"); this.uri = uri; } public override string Accept { get { return this.headers[System.Data.Services.Http.HttpRequestHeader.Accept]; } set { this.headers.SetSpecialHeader("accept", value); } } public override long ContentLength { set { this.headers[System.Data.Services.Http.HttpRequestHeader.ContentLength] = value.ToString(CultureInfo.InvariantCulture); } } public override bool AllowReadStreamBuffering { get { return true; } set { } } public override string ContentType { get { return this.headers[System.Data.Services.Http.HttpRequestHeader.ContentType]; } set { this.headers.SetSpecialHeader("content-type", value); } } public override System.Data.Services.Http.WebHeaderCollection Headers { get { if (this.headers == null) { this.headers = new System.Data.Services.Http.XHRWebHeaderCollection(System.Data.Services.Http.WebHeaderCollectionType.HttpWebRequest); } return this.headers; } } public override string Method { get { return this.method; } set { this.method = value; } } public override Uri RequestUri { get { return this.uri; } } public static bool IsAvailable() { try { ScriptXmlHttpRequest request = new ScriptXmlHttpRequest(); return (null != request); } catch (WebException) { return false; } } public override void Abort() { this.aborted = true; if (this.underlyingRequest != null) { this.underlyingRequest.Abort(); this.underlyingRequest.Dispose(); this.underlyingRequest = null; } if (this.response != null) { ((XHRHttpWebResponse)this.response).InternalRequest = null; this.response = null; } this.Close(); } public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state) { if (this.aborted) { throw CreateAbortException(); } if (this.contentStream == null) { this.contentStream = new NonClosingMemoryStream(); } else { this.contentStream.Seek(0L, SeekOrigin.Begin); } HttpWebRequestAsyncResult asyncResult = new HttpWebRequestAsyncResult(callback, state); this.asyncRequestResult = asyncResult; this.asyncRequestResult.CompletedSynchronously = true; if (asyncResult != null) { asyncResult.SetCompleted(); asyncResult.Callback(asyncResult); } return asyncResult; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Caller will dispose the returned value")] public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state) { HttpWebRequestAsyncResult asyncResult = new HttpWebRequestAsyncResult(callback, state); try { asyncResult.InsideBegin = true; this.asyncResponseResult = asyncResult; this.InvokeRequest(); } finally { asyncResult.InsideBegin = false; } return asyncResult; } public override Stream EndGetRequestStream(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } if (this.asyncRequestResult != asyncResult) { throw new InvalidOperationException( System.Data.Services.Client.Strings.HttpWeb_Internal("HttpWebRequest.EndGetRequestStream")); } if (this.asyncRequestResult.EndCalled) { throw new InvalidOperationException( System.Data.Services.Client.Strings.HttpWeb_Internal("HttpWebRequest.EndGetRequestStream.2")); } if (this.aborted) { throw CreateAbortException(); } this.asyncRequestResult.EndCalled = true; this.asyncRequestResult.Dispose(); this.asyncRequestResult = null; return this.contentStream; } public override System.Data.Services.Http.WebResponse EndGetResponse(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } if (this.asyncResponseResult != asyncResult) { throw new InvalidOperationException( System.Data.Services.Client.Strings.HttpWeb_Internal("HttpWebRequest.EndGetResponse")); } if (this.asyncResponseResult.EndCalled) { throw new InvalidOperationException( System.Data.Services.Client.Strings.HttpWeb_Internal("HttpWebRequest.EndGetResponse.2")); } if (this.aborted) { throw CreateAbortException(); } this.asyncResponseResult.EndCalled = true; this.CreateResponse(); this.asyncResponseResult.Dispose(); this.asyncResponseResult = null; return this.response; } public override System.Net.WebHeaderCollection CreateEmptyWebHeaderCollection() { return System.Net.WebRequest.Create(this.RequestUri).Headers; } internal void Close() { this.Dispose(true); } internal Stream ReadResponse(IDisposable connection) { Debug.Assert(connection != null, "connection != null"); if ((this.response.ContentType == null) || this.response.ContentType.Contains("json") || this.response.ContentType.Contains("xml") || this.response.ContentType.Contains("text") || this.response.ContentType.Contains("multipart")) { string buffer = this.underlyingRequest.ReadResponseAsString(); return (!string.IsNullOrEmpty(buffer) ? new DisposingMemoryStream(connection, Encoding.UTF8.GetBytes(buffer)) : null); } throw WebException.CreateInternal("HttpWebRequest.ReadResponse"); } protected override void Dispose(bool disposing) { if (disposing) { if (this.contentStream != null) { this.contentStream.InternalDispose(); this.contentStream = null; } } } private static System.Data.Services.Http.WebException CreateAbortException() { return new System.Data.Services.Http.WebException(System.Data.Services.Client.Strings.HttpWebRequest_Aborted); } private void CreateResponse() { int statusCode; this.underlyingRequest.GetResponseStatus(out statusCode); if (statusCode != -1) { string responseHeaders = this.underlyingRequest.GetResponseHeaders(); this.response = new System.Data.Services.Http.XHRHttpWebResponse(this, statusCode, responseHeaders); } } private void ReadyStateChanged() { if (this.underlyingRequest.IsCompleted && (this.asyncResponseResult != null)) { try { if (this.asyncResponseResult.InsideBegin) { this.asyncResponseResult.CompletedSynchronously = true; } this.asyncResponseResult.SetCompleted(); this.asyncResponseResult.Callback(this.asyncResponseResult); } finally { this.underlyingRequest.Dispose(); } } } private void InvokeRequest() { if (this.aborted) { throw CreateAbortException(); } if (this.invoked) { throw new InvalidOperationException( System.Data.Services.Client.Strings.HttpWeb_Internal("HttpWebRequest.InvokeRequest")); } this.invoked = true; this.underlyingRequest = new ScriptXmlHttpRequest(); this.underlyingRequest.Open(this.uri.AbsoluteUri, this.Method, (Action)this.ReadyStateChanged); if ((this.headers != null) && (this.headers.Count != 0)) { foreach (string header in this.headers.AllKeys) { string value = this.headers[header]; this.underlyingRequest.SetRequestHeader(header, value); } } string content = null; if (this.contentStream != null) { byte[] buf = this.contentStream.GetBuffer(); if (buf != null) { int bufferSize = checked((int)this.contentStream.Position); content = Encoding.UTF8.GetString(buf, 0, bufferSize); this.underlyingRequest.SetRequestHeader("content-length", bufferSize.ToString(CultureInfo.InvariantCulture)); } } this.underlyingRequest.Send(content); } private sealed class HttpWebRequestAsyncResult : IAsyncResult, IDisposable { private AsyncCallback callback; private bool completed; private bool completedSynchronously; private bool endCalled; private object state; private ManualResetEvent waitHandle; public HttpWebRequestAsyncResult(AsyncCallback callback, object state) { this.callback = callback; this.state = state; } public object AsyncState { get { return this.state; } } public WaitHandle AsyncWaitHandle { get { if (this.waitHandle == null) { this.waitHandle = new ManualResetEvent(false); } return this.waitHandle; } } public AsyncCallback Callback { get { return this.callback; } } public bool CompletedSynchronously { get { return this.completedSynchronously; } internal set { this.completedSynchronously = value; } } public bool EndCalled { get { return this.endCalled; } set { this.endCalled = value; } } public bool IsCompleted { get { return this.completed; } } public bool InsideBegin { get; set; } public void Dispose() { if (this.waitHandle != null) { ((IDisposable)this.waitHandle).Dispose(); } } public void SetCompleted() { this.completed = true; if (this.waitHandle != null) { this.waitHandle.Set(); } } } private sealed class DisposingMemoryStream : MemoryStream { private readonly IDisposable disposable; internal DisposingMemoryStream(IDisposable disposable, byte[] buffer) : base(buffer) { Debug.Assert(disposable != null, "disposable != null"); this.disposable = disposable; } protected override void Dispose(bool disposing) { this.disposable.Dispose(); base.Dispose(disposing); } } private sealed class NonClosingMemoryStream : MemoryStream { public override void Close() { } internal void InternalDispose() { base.Dispose(); } protected override void Dispose(bool disposing) { } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using System; using System.Collections.Immutable; using System.Linq; using Xunit; using Roslyn.Test.PdbUtilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class HoistedThisTests : ExpressionCompilerTestBase { [WorkItem(1067379)] [Fact] public void InstanceIterator_NoCapturing() { var source = @" class C { System.Collections.IEnumerable F() { yield break; } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""C C.<F>d__0.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<F>d__0.MoveNext", "C", expectedIL); } [WorkItem(1067379)] [Fact] public void InstanceAsync_NoCapturing() { var source = @" using System; using System.Threading.Tasks; class C { async Task F() { await Console.Out.WriteLineAsync('a'); } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.<F>d__0 V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C C.<F>d__0.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<F>d__0.MoveNext", "C", expectedIL); } [WorkItem(1067379)] [Fact] public void InstanceLambda_NoCapturing() { var source = @" class C { void M() { System.Action a = () => 1.Equals(2); a(); } } "; // This test documents the fact that, as in dev12, "this" // is unavailable while stepping through the lambda. It // would be preferable if it were. VerifyNoThis(source, "C.<>c.<M>b__0_0"); } [Fact] public void InstanceLambda_NoCapturingExceptThis() { var source = @" class C { void M() { System.Action a = () => this.ToString(); a(); } } "; var expectedIL = @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"; VerifyHasThis(source, "C.<M>b__0_0", "C", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceIterator_CapturedThis() { var source = @" class C { System.Collections.IEnumerable F() { yield return this; } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""C C.<F>d__0.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<F>d__0.MoveNext", "C", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceAsync_CapturedThis() { var source = @" using System; using System.Threading.Tasks; class C { async Task F() { await Console.Out.WriteLineAsync(this.ToString()); } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.<F>d__0 V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C C.<F>d__0.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<F>d__0.MoveNext", "C", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceLambda_CapturedThis_DisplayClass() { var source = @" class C { int x; void M(int y) { System.Action a = () => x.Equals(y); a(); } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C C.<>c__DisplayClass1_0.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<>c__DisplayClass1_0.<M>b__0", "C", expectedIL, thisCanBeElided: false); } [WorkItem(1067379)] [Fact] public void InstanceLambda_CapturedThis_NoDisplayClass() { var source = @" class C { int x; void M(int y) { System.Action a = () => x.Equals(1); a(); } } "; var expectedIL = @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"; VerifyHasThis(source, "C.<M>b__1_0", "C", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceIterator_Generic() { var source = @" class C<T> { System.Collections.IEnumerable F<U>() { yield return this; } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""C<T> C<T>.<F>d__0<U>.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<F>d__0.MoveNext", "C<T>", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceAsync_Generic() { var source = @" using System; using System.Threading.Tasks; class C<T> { async Task F<U>() { await Console.Out.WriteLineAsync(this.ToString()); } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C<T>.<F>d__0<U> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C<T> C<T>.<F>d__0<U>.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<F>d__0.MoveNext", "C<T>", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceLambda_Generic() { var source = @" class C<T> { int x; void M<U>(int y) { System.Action a = () => x.Equals(y); a(); } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C<T> C<T>.<>c__DisplayClass1_0<U>.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<>c__DisplayClass1_0.<M>b__0", "C<T>", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceIterator_ExplicitInterfaceImplementation() { var source = @" interface I { System.Collections.IEnumerable F(); } class C : I { System.Collections.IEnumerable I.F() { yield return this; } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""C C.<I-F>d__0.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<I-F>d__0.MoveNext", "C", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceAsync_ExplicitInterfaceImplementation() { var source = @" using System; using System.Threading.Tasks; interface I { Task F(); } class C : I { async Task I.F() { await Console.Out.WriteLineAsync(this.ToString()); } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.<I-F>d__0 V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C C.<I-F>d__0.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<I-F>d__0.MoveNext", "C", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceLambda_ExplicitInterfaceImplementation() { var source = @" interface I { void M(int y); } class C : I { int x; void I.M(int y) { System.Action a = () => x.Equals(y); a(); } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C C.<>c__DisplayClass1_0.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<>c__DisplayClass1_0.<I.M>b__0", "C", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceIterator_ExplicitGenericInterfaceImplementation() { var source = @" interface I<T> { System.Collections.IEnumerable F(); } class C : I<int> { System.Collections.IEnumerable I<int>.F() { yield return this; } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""C C.<I<System-Int32>-F>d__0.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<I<System-Int32>-F>d__0.MoveNext", "C", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceAsync_ExplicitGenericInterfaceImplementation() { var source = @" using System; using System.Threading.Tasks; interface I<T> { Task F(); } class C : I<int> { async Task I<int>.F() { await Console.Out.WriteLineAsync(this.ToString()); } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.<I<System-Int32>-F>d__0 V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C C.<I<System-Int32>-F>d__0.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<I<System-Int32>-F>d__0.MoveNext", "C", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceLambda_ExplicitGenericInterfaceImplementation() { var source = @" interface I<T> { void M(int y); } class C : I<int> { int x; void I<int>.M(int y) { System.Action a = () => x.Equals(y); a(); } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C C.<>c__DisplayClass1_0.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<>c__DisplayClass1_0.<I<System.Int32>.M>b__0", "C", expectedIL, thisCanBeElided: false); } [WorkItem(1066489)] [Fact] public void InstanceIterator_ExplicitInterfaceImplementation_OldName() { var ilSource = @" .class interface public abstract auto ansi I`1<T> { .method public hidebysig newslot abstract virtual instance class [mscorlib]System.Collections.IEnumerable F() cil managed { } // end of method I`1::F } // end of class I`1 .class public auto ansi beforefieldinit C extends [mscorlib]System.Object implements class I`1<int32> { .class auto ansi sealed nested private beforefieldinit '<I<System.Int32>'.'F>d__0' extends [mscorlib]System.Object implements class [mscorlib]System.Collections.Generic.IEnumerable`1<object>, [mscorlib]System.Collections.IEnumerable, class [mscorlib]System.Collections.Generic.IEnumerator`1<object>, [mscorlib]System.Collections.IEnumerator, [mscorlib]System.IDisposable { .field private object '<>2__current' .field private int32 '<>1__state' .field private int32 '<>l__initialThreadId' .field public class C '<>4__this' .method private hidebysig newslot virtual final instance class [mscorlib]System.Collections.Generic.IEnumerator`1<object> 'System.Collections.Generic.IEnumerable<System.Object>.GetEnumerator'() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance class [mscorlib]System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance bool MoveNext() cil managed { ldnull throw } .method private hidebysig newslot specialname virtual final instance object 'System.Collections.Generic.IEnumerator<System.Object>.get_Current'() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance void System.Collections.IEnumerator.Reset() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance void System.IDisposable.Dispose() cil managed { ldnull throw } .method private hidebysig newslot specialname virtual final instance object System.Collections.IEnumerator.get_Current() cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor(int32 '<>1__state') cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance object 'System.Collections.Generic.IEnumerator<System.Object>.Current'() { .get instance object C/'<I<System.Int32>'.'F>d__0'::'System.Collections.Generic.IEnumerator<System.Object>.get_Current'() } .property instance object System.Collections.IEnumerator.Current() { .get instance object C/'<I<System.Int32>'.'F>d__0'::System.Collections.IEnumerator.get_Current() } } // end of class '<I<System.Int32>'.'F>d__0' .method private hidebysig newslot virtual final instance class [mscorlib]System.Collections.IEnumerable 'I<System.Int32>.F'() cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class C "; ImmutableArray<byte> ilBytes; ImmutableArray<byte> ilPdbBytes; EmitILToArray(ilSource, appendDefaultHeader: true, includePdb: true, assemblyBytes: out ilBytes, pdbBytes: out ilPdbBytes); var runtime = CreateRuntimeInstance( assemblyName: GetUniqueName(), references: ImmutableArray.Create(MscorlibRef), exeBytes: ilBytes.ToArray(), symReader: SymReaderFactory.CreateReader(ilPdbBytes)); var context = CreateMethodContext(runtime, "C.<I<System.Int32>.F>d__0.MoveNext"); VerifyHasThis(context, "C", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C C.<I<System.Int32>.F>d__0.<>4__this"" IL_0006: ret }"); } [Fact] public void StaticIterator() { var source = @" class C { static System.Collections.IEnumerable F() { yield break; } } "; VerifyNoThis(source, "C.<F>d__0.MoveNext"); } [Fact] public void StaticAsync() { var source = @" using System; using System.Threading.Tasks; class C<T> { static async Task F<U>() { await Console.Out.WriteLineAsync('a'); } } "; VerifyNoThis(source, "C.<F>d__0.MoveNext"); } [Fact] public void StaticLambda() { var source = @" using System; class C<T> { static void F<U>(int x) { Action a = () => x.ToString(); a(); } } "; VerifyNoThis(source, "C.<>c__DisplayClass0_0.<F>b__0"); } [Fact] public void ExtensionIterator() { var source = @" static class C { static System.Collections.IEnumerable F(this int x) { yield return x; } } "; VerifyNoThis(source, "C.<F>d__0.MoveNext"); } [Fact] public void ExtensionAsync() { var source = @" using System; using System.Threading.Tasks; static class C { static async Task F(this int x) { await Console.Out.WriteLineAsync(x.ToString()); } } "; VerifyNoThis(source, "C.<F>d__0.MoveNext"); } [Fact] public void ExtensionLambda() { var source = @" using System; static class C { static void F(this int x) { Action a = () => x.ToString(); a(); } } "; VerifyNoThis(source, "C.<>c__DisplayClass0_0.<F>b__0"); } [WorkItem(1072296)] [Fact] public void OldStyleNonCapturingLambda() { var ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .method public hidebysig instance void M() cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method private hidebysig static int32 '<M>b__0'() cil managed { ldnull throw } } // end of class C "; ImmutableArray<byte> ilBytes; ImmutableArray<byte> ilPdbBytes; EmitILToArray(ilSource, appendDefaultHeader: true, includePdb: true, assemblyBytes: out ilBytes, pdbBytes: out ilPdbBytes); var runtime = CreateRuntimeInstance( assemblyName: GetUniqueName(), references: ImmutableArray.Create(MscorlibRef), exeBytes: ilBytes.ToArray(), symReader: SymReaderFactory.CreateReader(ilPdbBytes.ToArray())); var context = CreateMethodContext(runtime, "C.<M>b__0"); VerifyNoThis(context); } [WorkItem(1067379)] [Fact] public void LambdaLocations_Instance() { var source = @" using System; class C { int _toBeCaptured; C() { int l = ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 4))() + x))(1); } ~C() { int l = ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 6))() + x))(1); } int P { get { return ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 7))() + x))(1); } set { value = ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 8))() + x))(1); } } int this[int p] { get { return ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 9))() + x))(1); } set { value = ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 10))() + x))(1); } } event Action E { add { int l = ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 11))() + x))(1); } remove { int l = ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 12))() + x))(1); } } } "; var expectedILTemplate = @" {{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C C.{0}.<>4__this"" IL_0006: ret }}"; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); var runtime = CreateRuntimeInstance(comp); var dummyComp = CreateCompilationWithMscorlib("", new[] { comp.EmitToImageReference() }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var typeC = dummyComp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var displayClassTypes = typeC.GetMembers().OfType<NamedTypeSymbol>(); Assert.True(displayClassTypes.Any()); foreach (var displayClassType in displayClassTypes) { var displayClassName = displayClassType.Name; Assert.Equal(GeneratedNameKind.LambdaDisplayClass, GeneratedNames.GetKind(displayClassName)); foreach (var displayClassMethod in displayClassType.GetMembers().OfType<MethodSymbol>().Where(m => GeneratedNames.GetKind(m.Name) == GeneratedNameKind.LambdaMethod)) { var lambdaMethodName = string.Format("C.{0}.{1}", displayClassName, displayClassMethod.Name); var context = CreateMethodContext(runtime, lambdaMethodName); var expectedIL = string.Format(expectedILTemplate, displayClassName); VerifyHasThis(context, "C", expectedIL); } } } [Fact] public void LambdaLocations_Static() { var source = @" using System; class C { static int f = ((Func<int, int>)(x => ((Func<int>)(() => x + 2))() + x))(1); static C() { int l = ((Func<int, int>)(x => ((Func<int>)(() => x + 4))() + x))(1); } static int P { get { return ((Func<int, int>)(x => ((Func<int>)(() => x + 7))() + x))(1); } set { value = ((Func<int, int>)(x => ((Func<int>)(() => x + 8))() + x))(1); } } static event Action E { add { int l = ((Func<int, int>)(x => ((Func<int>)(() => x + 11))() + x))(1); } remove { int l = ((Func<int, int>)(x => ((Func<int>)(() => x + 12))() + x))(1); } } } "; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); var runtime = CreateRuntimeInstance(comp); var dummyComp = CreateCompilationWithMscorlib("", new[] { comp.EmitToImageReference() }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var typeC = dummyComp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var displayClassTypes = typeC.GetMembers().OfType<NamedTypeSymbol>(); Assert.True(displayClassTypes.Any()); foreach (var displayClassType in displayClassTypes) { var displayClassName = displayClassType.Name; Assert.Equal(GeneratedNameKind.LambdaDisplayClass, GeneratedNames.GetKind(displayClassName)); foreach (var displayClassMethod in displayClassType.GetMembers().OfType<MethodSymbol>().Where(m => GeneratedNames.GetKind(m.Name) == GeneratedNameKind.LambdaMethod)) { var lambdaMethodName = string.Format("C.{0}.{1}", displayClassName, displayClassMethod.Name); var context = CreateMethodContext(runtime, lambdaMethodName); VerifyNoThis(context); } } } private void VerifyHasThis(string source, string methodName, string expectedType, string expectedIL, bool thisCanBeElided = true) { var sourceCompilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); var runtime = CreateRuntimeInstance(sourceCompilation); var context = CreateMethodContext(runtime, methodName); VerifyHasThis(context, expectedType, expectedIL); // Now recompile and test CompileExpression with optimized code. sourceCompilation = sourceCompilation.WithOptions(sourceCompilation.Options.WithOptimizationLevel(OptimizationLevel.Release)); runtime = CreateRuntimeInstance(sourceCompilation); context = CreateMethodContext(runtime, methodName); // In C#, "this" may be optimized away. if (thisCanBeElided) { VerifyNoThis(context); } else { VerifyHasThis(context, expectedType, expectedIL: null); } // Verify that binding a trivial expression succeeds. string error; var testData = new CompilationTestData(); context.CompileExpression("42", out error, testData); Assert.Null(error); Assert.Equal(1, testData.Methods.Count); } private static void VerifyHasThis(EvaluationContext context, string expectedType, string expectedIL) { var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var testData = new CompilationTestData(); var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.NotNull(assembly); Assert.NotEqual(assembly.Count, 0); var localAndMethod = locals.Single(l => l.LocalName == "this"); if (expectedIL != null) { VerifyMethodData(testData.Methods.Single(m => m.Key.Contains(localAndMethod.MethodName)).Value, expectedType, expectedIL); } locals.Free(); string error; testData = new CompilationTestData(); context.CompileExpression("this", out error, testData); Assert.Null(error); if (expectedIL != null) { VerifyMethodData(testData.Methods.Single(m => m.Key.Contains("<>m0")).Value, expectedType, expectedIL); } } private static void VerifyMethodData(CompilationTestData.MethodData methodData, string expectedType, string expectedIL) { methodData.VerifyIL(expectedIL); var method = (MethodSymbol)methodData.Method; VerifyTypeParameters(method); Assert.Equal(expectedType, method.ReturnType.ToTestDisplayString()); } private void VerifyNoThis(string source, string methodName) { var comp = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); var runtime = CreateRuntimeInstance(comp); var context = CreateMethodContext(runtime, methodName); VerifyNoThis(context); } private static void VerifyNoThis(EvaluationContext context) { string error; var testData = new CompilationTestData(); context.CompileExpression("this", out error, testData); Assert.Contains(error, new[] { "error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer", "error CS0027: Keyword 'this' is not available in the current context", }); testData = new CompilationTestData(); context.CompileExpression("base.ToString()", out error, testData); Assert.Contains(error, new[] { "error CS1511: Keyword 'base' is not available in a static method", "error CS1512: Keyword 'base' is not available in the current context", }); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; testData = new CompilationTestData(); var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.NotNull(assembly); AssertEx.None(locals, l => l.LocalName.Contains("this")); locals.Free(); } [WorkItem(1024137)] [Fact] public void InstanceMembersInIterator() { var source = @"class C { object x; System.Collections.IEnumerable F() { yield return this.x; } }"; var compilation0 = CreateCompilationWithMscorlib( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); var runtime = CreateRuntimeInstance(compilation0); var context = CreateMethodContext(runtime, "C.<F>d__1.MoveNext"); string error; var testData = new CompilationTestData(); context.CompileExpression("this.x", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""C C.<F>d__1.<>4__this"" IL_0006: ldfld ""object C.x"" IL_000b: ret }"); } [WorkItem(1024137)] [Fact] public void InstanceMembersInAsync() { var source = @" using System; using System.Threading.Tasks; class C { object x; async Task F() { await Console.Out.WriteLineAsync(this.ToString()); } }"; var compilation0 = CreateCompilationWithMscorlib45( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); var runtime = CreateRuntimeInstance(compilation0); var context = CreateMethodContext(runtime, "C.<F>d__1.MoveNext"); string error; var testData = new CompilationTestData(); context.CompileExpression("this.x", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.<F>d__1 V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C C.<F>d__1.<>4__this"" IL_0006: ldfld ""object C.x"" IL_000b: ret }"); } [WorkItem(1024137)] [Fact] public void InstanceMembersInLambda() { var source = @"class C { object x; void F() { System.Action a = () => this.x.ToString(); a(); } }"; var compilation0 = CreateCompilationWithMscorlib( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); var runtime = CreateRuntimeInstance(compilation0); var context = CreateMethodContext(runtime, "C.<F>b__1_0"); string error; var testData = new CompilationTestData(); context.CompileExpression("this.x", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""object C.x"" IL_0006: ret }"); } [Fact] public void BaseMembersInIterator() { var source = @" class Base { protected int x; } class Derived : Base { new protected object x; System.Collections.IEnumerable M() { yield return base.x; } }"; var compilation0 = CreateCompilationWithMscorlib( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); var runtime = CreateRuntimeInstance(compilation0); var context = CreateMethodContext(runtime, "Derived.<M>d__1.MoveNext"); string error; var testData = new CompilationTestData(); context.CompileExpression("base.x", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""Derived Derived.<M>d__1.<>4__this"" IL_0006: ldfld ""int Base.x"" IL_000b: ret }"); } [Fact] public void BaseMembersInAsync() { var source = @" using System; using System.Threading.Tasks; class Base { protected int x; } class Derived : Base { new protected object x; async Task M() { await Console.Out.WriteLineAsync(this.ToString()); } }"; var compilation0 = CreateCompilationWithMscorlib45( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); var runtime = CreateRuntimeInstance(compilation0); var context = CreateMethodContext(runtime, "Derived.<M>d__1.MoveNext"); string error; var testData = new CompilationTestData(); context.CompileExpression("base.x", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, Derived.<M>d__1 V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""Derived Derived.<M>d__1.<>4__this"" IL_0006: ldfld ""int Base.x"" IL_000b: ret }"); } [Fact] public void BaseMembersInLambda() { var source = @" class Base { protected int x; } class Derived : Base { new protected object x; void F() { System.Action a = () => this.x.ToString(); a(); } }"; var compilation0 = CreateCompilationWithMscorlib( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); var runtime = CreateRuntimeInstance(compilation0); var context = CreateMethodContext(runtime, "Derived.<F>b__1_0"); string error; var testData = new CompilationTestData(); context.CompileExpression("this.x", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""object Derived.x"" IL_0006: ret }"); } [Fact] public void IteratorOverloading_Parameters1() { var source = @" public class C { public System.Collections.IEnumerable M() { yield return this; } public System.Collections.IEnumerable M(int x) { return null; } }"; CheckIteratorOverloading(source, m => m.ParameterCount == 0); } [Fact] public void IteratorOverloading_Parameters2() // Same as above, but declarations reversed. { var source = @" public class C { public System.Collections.IEnumerable M(int x) { return null; } public System.Collections.IEnumerable M() { yield return this; } }"; // NB: We pick the wrong overload, but it doesn't matter because // the methods have the same characteristics. // Also, we don't require this behavior, we're just documenting it. CheckIteratorOverloading(source, m => m.ParameterCount == 1); } [Fact] public void IteratorOverloading_Staticness() { var source = @" public class C { public static System.Collections.IEnumerable M(int x) { return null; } // NB: We declare the interesting overload last so we know we're not // just picking the first one by mistake. public System.Collections.IEnumerable M() { yield return this; } }"; CheckIteratorOverloading(source, m => !m.IsStatic); } [Fact] public void IteratorOverloading_Abstractness() { var source = @" public abstract class C { public abstract System.Collections.IEnumerable M(int x); // NB: We declare the interesting overload last so we know we're not // just picking the first one by mistake. public System.Collections.IEnumerable M() { yield return this; } }"; CheckIteratorOverloading(source, m => !m.IsAbstract); } [Fact] public void IteratorOverloading_Arity1() { var source = @" public class C { public System.Collections.IEnumerable M<T>(int x) { return null; } // NB: We declare the interesting overload last so we know we're not // just picking the first one by mistake. public System.Collections.IEnumerable M() { yield return this; } }"; CheckIteratorOverloading(source, m => m.Arity == 0); } [Fact] public void IteratorOverloading_Arity2() { var source = @" public class C { public System.Collections.IEnumerable M(int x) { return null; } // NB: We declare the interesting overload last so we know we're not // just picking the first one by mistake. public System.Collections.IEnumerable M<T>() { yield return this; } }"; CheckIteratorOverloading(source, m => m.Arity == 1); } [Fact] public void IteratorOverloading_Constraints1() { var source = @" public class C { public System.Collections.IEnumerable M<T>(int x) where T : struct { return null; } // NB: We declare the interesting overload last so we know we're not // just picking the first one by mistake. public System.Collections.IEnumerable M<T>() where T : class { yield return this; } }"; CheckIteratorOverloading(source, m => m.TypeParameters.Single().HasReferenceTypeConstraint); } [Fact] public void IteratorOverloading_Constraints2() { var source = @" using System.Collections.Generic; public class C { public System.Collections.IEnumerable M<T, U>(int x) where T : class where U : IEnumerable<T> { return null; } // NB: We declare the interesting overload last so we know we're not // just picking the first one by mistake. public System.Collections.IEnumerable M<T, U>() where U : class where T : IEnumerable<U> { yield return this; } }"; // NOTE: This isn't the feature we're switching on, but it is a convenient // differentiator. CheckIteratorOverloading(source, m => m.ParameterCount == 0); } private static void CheckIteratorOverloading(string source, Func<MethodSymbol, bool> isDesiredOverload) { var comp1 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); var ref1 = comp1.EmitToImageReference(); var comp2 = CreateCompilationWithMscorlib("", new[] { ref1 }, options: TestOptions.DebugDll); var originalType = comp2.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var iteratorMethod = originalType.GetMembers("M").OfType<MethodSymbol>().Single(isDesiredOverload); var stateMachineType = originalType.GetMembers().OfType<NamedTypeSymbol>().Single(t => GeneratedNames.GetKind(t.Name) == GeneratedNameKind.StateMachineType); var moveNextMethod = stateMachineType.GetMember<MethodSymbol>("MoveNext"); var guessedIterator = CompilationContext.GetSubstitutedSourceMethod(moveNextMethod, sourceMethodMustBeInstance: true); Assert.Equal(iteratorMethod, guessedIterator.OriginalDefinition); } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using Aurora.Framework; using Aurora.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using Nini.Config; using Aurora.Simulation.Base; using OpenMetaverse; using OpenMetaverse.Imaging; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Services.Handlers.Map { public class MapService : IService, IMapService { private uint m_port = 8005; private IHttpServer m_server; private IRegistryCore m_registry; private bool m_enabled = false; private bool m_cacheEnabled = true; private float m_cacheExpires = 24; private IAssetService m_assetService; private IGridService m_gridService; public void Initialize (IConfigSource config, IRegistryCore registry) { m_registry = registry; IConfig mapConfig = config.Configs["MapService"]; if (mapConfig != null) { m_enabled = mapConfig.GetBoolean ("Enabled", m_enabled); m_port = mapConfig.GetUInt ("Port", m_port); m_cacheEnabled = mapConfig.GetBoolean ("CacheEnabled", m_cacheEnabled); m_cacheExpires = mapConfig.GetFloat ("CacheExpires", m_cacheExpires); } if(!m_enabled) return; if (m_cacheEnabled) CreateCacheDirectories (); m_server = registry.RequestModuleInterface<ISimulationBase>().GetHttpServer(m_port); m_server.AddHTTPHandler("/MapService/", MapRequest); m_server.AddHTTPHandler(new GenericStreamHandler("GET", "/MapAPI/", MapAPIRequest)); registry.RegisterModuleInterface<IMapService>(this); } private void CreateCacheDirectories () { if (!Directory.Exists ("assetcache")) Directory.CreateDirectory ("assetcache"); if(!Directory.Exists("assetcache/mapzoomlevels")) Directory.CreateDirectory ("assetcache/mapzoomlevels"); } public void Start (IConfigSource config, IRegistryCore registry) { m_assetService = m_registry.RequestModuleInterface<IAssetService>(); m_gridService = m_registry.RequestModuleInterface<IGridService>(); } public void FinishedStartup () { } public string MapServiceURL { get { return m_server.ServerURI + "/MapService/"; } } public string MapServiceAPIURL { get { return m_server.ServerURI + "/MapAPI/"; } } public byte[] MapAPIRequest(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { byte[] response = MainServer.BlankResponse; string var = httpRequest.Query["var"].ToString(); if (path == "/MapAPI/get-region-coords-by-name") { string resp = "var {0} = {\"x\":{1},\"y\":{2}};"; string sim_name = httpRequest.Query["sim_name"].ToString(); var region = m_registry.RequestModuleInterface<IGridService>().GetRegionByName(null, sim_name); if (region == null) resp = "var " + var + " = {error: true};"; else resp = "var " + var + " = {\"x\":" + region.RegionLocX + ",\"y\":" + region.RegionLocY + "};"; response = System.Text.Encoding.UTF8.GetBytes(resp); httpResponse.ContentType = "text/javascript"; } else if (path == "/MapAPI/get-region-name-by-coords") { string resp = "var {0} = \"{1}\";"; int grid_x = int.Parse(httpRequest.Query["grid_x"].ToString()); int grid_y = int.Parse(httpRequest.Query["grid_y"].ToString()); var region = m_registry.RequestModuleInterface<IGridService>().GetRegionByPosition(null, grid_x * Constants.RegionSize, grid_y * Constants.RegionSize); if (region == null) { List<GridRegion> regions = m_gridService.GetRegionRange(null, (grid_x * Constants.RegionSize) - (m_gridService.GetMaxRegionSize()), (grid_x * Constants.RegionSize), (grid_y * Constants.RegionSize) - (m_gridService.GetMaxRegionSize()), (grid_y * Constants.RegionSize)); bool found = false; foreach (var r in regions) { if (r.PointIsInRegion(grid_x * Constants.RegionSize, grid_y * Constants.RegionSize)) { resp = string.Format(resp, var, r.RegionName); found = true; break; } } if (!found) resp = "var " + var + " = {error: true};"; } else resp = string.Format(resp, var, region.RegionName); response = System.Text.Encoding.UTF8.GetBytes(resp); httpResponse.ContentType = "text/javascript"; } return response; } public Hashtable MapRequest (Hashtable request) { Hashtable reply = new Hashtable (); string uri = request["uri"].ToString (); //Remove the /MapService/ uri = uri.Remove (0, 12); if (!uri.StartsWith("map")) { if (uri == "") { string resp = "<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">" + "<Name>map.secondlife.com</Name>" + "<Prefix/>" + "<Marker/>" + "<MaxKeys>1000</MaxKeys>" + "<IsTruncated>true</IsTruncated>"; List<GridRegion> regions = m_gridService.GetRegionRange(null, (1000 * Constants.RegionSize) - (8 * Constants.RegionSize), (1000 * Constants.RegionSize) + (8 * Constants.RegionSize), (1000 * Constants.RegionSize) - (8 * Constants.RegionSize), (1000 * Constants.RegionSize) + (8 * Constants.RegionSize)); foreach (var region in regions) { resp += "<Contents><Key>map-1-" + region.RegionLocX/256 + "-" + region.RegionLocY/256 + "-objects.jpg</Key>" + "<LastModified>2012-07-09T21:26:32.000Z</LastModified></Contents>"; } resp += "</ListBucketResult>"; reply["str_response_string"] = resp; reply["int_response_code"] = 200; reply["content_type"] = "application/xml"; return reply; } return null; } string[] splitUri = uri.Split ('-'); byte[] jpeg = FindCachedImage(uri); if (jpeg.Length != 0) { reply["str_response_string"] = Convert.ToBase64String (jpeg); reply["int_response_code"] = 200; reply["content_type"] = "image/jpeg"; return reply; } try { int mapLayer = int.Parse(uri.Substring(4, 1)); int mapView = (int)Math.Pow(2, (mapLayer - 1)); int regionX = int.Parse(splitUri[2]); int regionY = int.Parse(splitUri[3]); int maxRegionSize = m_gridService.GetMaxRegionSize(); if (maxRegionSize == 0) maxRegionSize = 8192; List<GridRegion> regions = m_gridService.GetRegionRange(null, (regionX * Constants.RegionSize) - maxRegionSize, (regionX * Constants.RegionSize) + maxRegionSize, (regionY * Constants.RegionSize) - maxRegionSize, (regionY * Constants.RegionSize) + maxRegionSize); List<Image> bitImages = new List<Image>(); List<GridRegion> badRegions = new List<GridRegion>(); IJ2KDecoder decoder = m_registry.RequestModuleInterface<IJ2KDecoder>(); foreach (GridRegion r in regions) { AssetBase texAsset = m_assetService.Get(r.TerrainMapImage.ToString()); if (texAsset != null) { Image image = decoder.DecodeToImage(texAsset.Data); if (image != null) bitImages.Add(image); else badRegions.Add(r); } else badRegions.Add(r); } foreach (GridRegion r in badRegions) regions.Remove(r); const int SizeOfImage = 256; using (Bitmap mapTexture = new Bitmap(SizeOfImage, SizeOfImage)) { using (Graphics g = Graphics.FromImage(mapTexture)) { SolidBrush sea = new SolidBrush(Color.FromArgb(29, 71, 95)); g.FillRectangle(sea, 0, 0, SizeOfImage, SizeOfImage); for (int i = 0; i < regions.Count; i++) { //Find the offsets first float x = (regions[i].RegionLocX - (regionX * (float)Constants.RegionSize)) / Constants.RegionSize; float y = (regions[i].RegionLocY - (regionY * (float)Constants.RegionSize)) / Constants.RegionSize; y += (regions[i].RegionSizeX - Constants.RegionSize) / Constants.RegionSize; float xx = (float)(x * (SizeOfImage / mapView)); float yy = SizeOfImage - (y * (SizeOfImage / mapView) + (SizeOfImage / (mapView))); g.DrawImage(bitImages[i], xx, yy, (int)(SizeOfImage / (float)mapView * ((float)regions[i].RegionSizeX / Constants.RegionSize)), (int)(SizeOfImage / (float)mapView * (regions[i].RegionSizeY / (float)Constants.RegionSize))); // y origin is top } } foreach (var bmp in bitImages) { bmp.Dispose(); } EncoderParameters myEncoderParameters = new EncoderParameters(); myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L); using (MemoryStream imgstream = new MemoryStream()) { // Save bitmap to stream mapTexture.Save(imgstream, GetEncoderInfo("image/jpeg"), myEncoderParameters); // Write the stream to a byte array for output jpeg = imgstream.ToArray(); } SaveCachedImage(uri, jpeg); } } catch { } if (jpeg.Length == 0 && splitUri.Length > 1 && splitUri[1].Length > 1) { using (MemoryStream imgstream = new MemoryStream()) { GridRegion region = m_registry.RequestModuleInterface<IGridService>().GetRegionByName(null, splitUri[1].Remove (4)); if (region == null) return null; // non-async because we know we have the asset immediately. AssetBase mapasset = m_assetService.Get(region.TerrainMapImage.ToString()); if (mapasset != null) { Image image; ManagedImage mImage; if (!OpenJPEG.DecodeToImage(mapasset.Data, out mImage, out image) || image == null) return null; // Decode image to System.Drawing.Image EncoderParameters myEncoderParameters = new EncoderParameters(); myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L); // Save bitmap to stream image.Save(imgstream, GetEncoderInfo("image/jpeg"), myEncoderParameters); // Write the stream to a byte array for output jpeg = imgstream.ToArray(); SaveCachedImage(uri, jpeg); mapasset.Dispose(); image.Dispose(); } } } reply["str_response_string"] = Convert.ToBase64String (jpeg); reply["int_response_code"] = 200; reply["content_type"] = "image/jpeg"; return reply; } // From msdn private static ImageCodecInfo GetEncoderInfo (String mimeType) { ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders (); #if (!ISWIN) foreach (ImageCodecInfo t in encoders) { if (t.MimeType == mimeType) return t; } return null; #else return encoders.FirstOrDefault(t => t.MimeType == mimeType); #endif } private byte[] FindCachedImage (string name) { if (!m_cacheEnabled) return new byte[0]; string fullPath = Path.Combine ("assetcache", Path.Combine ("mapzoomlevels", name)); if (File.Exists (fullPath)) { //Make sure the time is ok if(DateTime.Now < File.GetLastWriteTime (fullPath).AddHours(m_cacheExpires)) return File.ReadAllBytes (fullPath); } return new byte[0]; } private void SaveCachedImage (string name, byte[] data) { if (!m_cacheEnabled) return; string fullPath = Path.Combine ("assetcache", Path.Combine ("mapzoomlevels", name)); File.WriteAllBytes (fullPath, data); } } }
#region License /* Copyright (c) 2003-2015 Llewellyn Pritchard * All rights reserved. * This source code is subject to terms and conditions of the BSD License. * See license.txt. */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Text.RegularExpressions; using System.ComponentModel; using System.IO; using System.Windows.Forms; using System.Xml.Schema; using System.Xml.Serialization; namespace IronScheme.Editor.Utils { #region Test code #if TESTGA [ArgOptions(MessageBox = false, AllowShortcut = true, CaseSensitive = false, Prefix = "-", Seperator = " ", ShortcutLength = 1)] class MyArgs : xacc.Utils.GetArgs { // argtype argname default value [ArgItem("Specifies the level of stuff", Shortname = "lev")] public int level = 5; [ArgItem("The best server in the world")] public string server = "xacc.sf.net"; public bool debug; [ArgItem( @"This is long description for usernames, because it takes multiple arguments and could confuse a user.")] public string[] usernames; public DayOfWeek day; } class Test { // compile with: // -d:TEST -doc:GetArgs.xml -nowarn:0649,1591 GetArgs.cs // run with: // -lev : 10 -d -usernames: {leppie, is , the, 1337357} -DAY : Monday [STAThread] static void Main() { MyArgs a = new MyArgs(); Console.WriteLine("level: {0}", a.level); Console.WriteLine("server: {0}", a.server); Console.WriteLine("debug: {0}", a.debug); Console.WriteLine("day: {0}", a.day); if (a.usernames != null) { Console.WriteLine("usernames:"); Console.WriteLine("{"); foreach (string name in a.usernames) { Console.WriteLine(" {0}, ", name); } Console.WriteLine("}"); } } } #endif #endregion /// <summary> /// Provides customization of argument parsing. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class ArgOptionsAttribute : Attribute { string prefix = "-"; string seperator = ":"; bool casesensistive = true; bool allowshortcut = false; bool msgbox = false; int shortcutlength = 1; bool pauseonerror = false; bool ignoreunknown = true; /// <summary> /// The prefix to use for the argument name eg '-' /// </summary> public string Prefix { get { return prefix; } set { prefix = value; } } /// <summary> /// The seperator to use for the argument eg ':' /// </summary> public string Seperator { get { return seperator; } set { seperator = value; } } /// <summary> /// Specifies whether argument names are case sensitive. /// </summary> /// <remarks>Case sensitive by default</remarks> public bool CaseSensitive { get { return casesensistive; } set { casesensistive = value; } } /// <summary> /// Specifies whether unknown arguments are ignored. /// </summary> /// <remarks>true by default</remarks> public bool IgnoreUnknownArguments { get { return ignoreunknown; } set { ignoreunknown = value; } } /// <summary> /// Specifies whether the user must press enter before an error condition exits. /// </summary> /// <remarks>False by default</remarks> public bool PauseOnError { get { return pauseonerror; } set { pauseonerror = value; } } /// <summary> /// Whether shortcut argument names will be allowed. /// </summary> /// <remarks> /// The shortname will be the 1st letter of the argument name. If another argument starts /// with the same letter, the second shortname will not be used. See ArgItemAttribute for /// customization. /// </remarks> public bool AllowShortcut { get { return allowshortcut; } set { allowshortcut = value; } } /// <summary> /// Specifies the length of shortcut names, eg 1 or 3. /// </summary> public int ShortcutLength { get { return shortcutlength; } set { shortcutlength = value; } } /// <summary> /// Specifies whether a MessageBox will be shown rather than printing to the console. /// </summary> public bool MessageBox { get { return msgbox; } set { msgbox = value; } } } /// <summary> /// The default input argument /// </summary> [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)] public sealed class DefaultArgAttribute : ArgItemAttribute { bool allowname = false; /// <summary> /// Specifies to accept name too. /// </summary> public bool AllowName { get { return allowname; } set { allowname = value; } } } /// <summary> /// Allows customization of specific argument items. /// </summary> [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)] public class ArgItemAttribute : Attribute { string shortname = null; string description = null; string name = null; /// <summary> /// Creates an instance of ArgItemAttribute. /// </summary> public ArgItemAttribute() { } /// <summary> /// Creates an instance of ArgItemAttribute with the description of the argument. /// </summary> /// <param name="description">the description of the argument</param> public ArgItemAttribute(string description) { this.description = description; } /// <summary> /// The description of the argument. /// </summary> public string Description { get { return description; } set { description = value; } } /// <summary> /// The name, if different, of the argument (if used). /// </summary> public string Name { get { return name; } set { name = value; } } /// <summary> /// The short form of the argument (if used). /// </summary> public string Shortname { get { return shortname; } set { shortname = value; } } } /// <summary> /// An ultra simplistic class for managing command line arguments parsing. /// </summary> /// <remarks> /// <p>Just inherit from this class making all args that need to be parsed /// public fields. Once you instantiate the inherited class the commandline /// arguements will be parsed and will be applied to the field in a /// type-safe fashion.</p> /// <list type="bullet"> /// <item>Pass -? or -help for help regarding usage from the commandline.</item> /// <item>Argument values cannot contain spaces unless it is single or double quoted.</item> /// <item>Argument values must be convertable via a TypeConvertor.</item> /// <item>The class will print exceptions and/or any errors to to Console.Error.</item> /// <item>If an exception is generated, the application will exit and print usage.</item> /// <item>Only the first occurance of an argument will be accepted, additional /// duplicate arguments will be ignored.</item> /// </list> /// </remarks> /// <example> /// <code> /// [ArgOptions(MessageBox=false,AllowShortcut = true, CaseSensitive=false, Prefix="-", Seperator=":")] /// class MyArgs : xacc.Utils.GetArgs /// { /// // argtype argname default value /// [ArgItem("Specifies the level of stuff", Shortname="lev")] /// public int level = 5; /// /// [ArgItem("The best server in the world")] /// public string server = "xacc.sf.net"; /// /// public bool debug; /// /// [ArgItem( /// @"This is long description /// for usersames, because it takes /// multiple arguments and could /// confuse a user.")] /// public string[] usernames; /// /// public DayOfWeek day; /// } /// /// class Test /// { /// // compile with: /// // -d:TEST -doc:GetArgs.xml -nowarn:0649,1591 GetArgs.cs /// // run with: /// // -level: 10 -debug -usernames: {leppie, is , the, 1337357} /// [STAThread] /// static void Main(string[] args) /// { /// MyArgs a = new MyArgs(); /// Console.WriteLine("level: {0}", a.level); /// Console.WriteLine("server: {0}", a.server); /// Console.WriteLine("debug: {0}", a.debug); /// Console.WriteLine("day: {0}", a.day); /// /// if (a.usernames != null) /// { /// Console.WriteLine("usernames:"); /// Console.WriteLine("{"); /// foreach (string name in a.usernames) /// { /// Console.WriteLine(" {0}, ", name); /// } /// Console.WriteLine("}"); /// } /// } /// } /// </code> /// </example> [ArgOptions] public abstract class GetArgs { static readonly Dictionary<Type, string> aliasmap = new Dictionary<Type, string>(); static GetArgs() { aliasmap.Add(typeof(int), "int"); aliasmap.Add(typeof(string), "string"); aliasmap.Add(typeof(bool), "bool"); aliasmap.Add(typeof(uint), "uint"); aliasmap.Add(typeof(byte), "byte"); aliasmap.Add(typeof(char), "char"); aliasmap.Add(typeof(short), "short"); aliasmap.Add(typeof(ushort), "ushort"); aliasmap.Add(typeof(long), "long"); aliasmap.Add(typeof(ulong), "ulong"); aliasmap.Add(typeof(decimal), "decimal"); aliasmap.Add(typeof(sbyte), "sbyte"); } static string GetShortTypeName(Type t) { if (aliasmap.ContainsKey(t)) { return aliasmap[t]; } return t.Name; } static XmlSchema GetSchema(Type t) { if (t.IsPublic) { XmlReflectionImporter xri = new XmlReflectionImporter(); XmlTypeMapping xtm = xri.ImportTypeMapping(t); XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter xse = new XmlSchemaExporter(schemas); xse.ExportTypeMapping(xtm); foreach (XmlSchema xs in schemas) { return xs; } } return null; } void GetSchema(TextWriter w) { XmlSchema xs = GetSchema(GetType()); if (xs != null) { xs.Write(w); } } class ArgInfo { readonly FieldInfo fi; readonly GetArgs container; bool handled = false; object _value; internal readonly object defaultvalue; readonly ArgItemAttribute options; public ArgInfo(FieldInfo fi, GetArgs container, object defaultvalue) { this.defaultvalue = defaultvalue; this.fi = fi; this.container = container; object[] att = fi.GetCustomAttributes(typeof(ArgItemAttribute), false); if (att.Length == 0) { options = new ArgItemAttribute(); } else { options = att[0] as ArgItemAttribute; } } public ArgItemAttribute Options { get { return options; } } public string Name { get { return options.Name ?? fi.Name; } } public Type Type { get { return fi.FieldType; } } public object Value { get { if (_value != null) { return _value; } return defaultvalue; } set { if (!handled && (_value == null || !_value.Equals(value))) { fi.SetValue(container, value); _value = value; //handled = true; } } } } string MakeArg(string name, string shortname) { if (!allowshortcut || shortname == null) { return name; } return string.Format("({0}|{1})", shortname, name); } void PrintHelp(Dictionary<string, ArgInfo> map) { TextWriter writer = null; if (msgbox) { writer = new StringWriter(); } else { writer = Console.Out; } Assembly ass = Assembly.GetEntryAssembly(); AssemblyName assname = ass.GetName(); AssemblyCopyrightAttribute acopy = null; object[] atts = ass.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); if (atts.Length > 0) { acopy = atts[0] as AssemblyCopyrightAttribute; } string progname = string.Format("{0} {1}.{2} {3}", assname.Name, assname.Version.Major, assname.Version.Minor, acopy == null ? string.Empty : acopy.Copyright); if (!msgbox) { writer.WriteLine(progname); } writer.WriteLine("Usage: {0}", assname.Name); writer.WriteLine("{0}? or {0}help prints usage", prefix); List<string> keys = new List<string>(map.Keys); bool acceptsdefault = false; foreach (KeyValuePair<string, ArgInfo> de in map) { ArgInfo arginfo = de.Value; string name = de.Key; string shortname = arginfo.Options.Shortname; if (shortname == name) { continue; } if (name == MAGIC) { acceptsdefault = true; continue; } writer.WriteLine(); Type t = arginfo.Type; if (t.IsArray) { writer.WriteLine("{2}{0,-15}{3} {{ <{1}> , ... }}", MakeArg(name, shortname), GetShortTypeName(t.GetElementType()), prefix, seperator); } else { if (t == typeof(bool)) { writer.WriteLine("{2}{0,-15} {3,-20} default: {1}", MakeArg(name, shortname), (bool)arginfo.defaultvalue ? "on" : "off", prefix, "(toggles)"); } else { writer.WriteLine("{3}{0,-15}{4} {1,-20} {2}", MakeArg(name, shortname), "<" + GetShortTypeName(t) + ">", arginfo.Value != null ? "default: " + arginfo.Value : string.Empty, prefix, seperator); } } if (arginfo.Options.Description != null) { string[] lines = arginfo.Options.Description.Split('\n'); foreach (string line in lines) { writer.WriteLine(" {0}", line.TrimEnd('\r')); } } } writer.WriteLine(); if (acceptsdefault) { writer.WriteLine("Non-named arguments are used as input."); } writer.WriteLine("Note: Argument names are case-{0}sensitive.", casesensitive ? string.Empty : "in"); if (msgbox) { MessageBox.Show(writer.ToString(), progname); } } //note: these are static just to improve performance a bit static bool casesensitive, allowshortcut, msgbox, pauserr, ignoreunknown; static string seperator, prefix; static int shortlen; static Regex re, arrre; const string MAGIC = "kksjhd&^D3"; /// <summary> /// Creates an instance of GetArgs /// </summary> protected GetArgs() { const BindingFlags flags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance; Type argclass = GetType(); if (re == null) { ArgOptionsAttribute aoa = argclass.GetCustomAttributes(typeof(ArgOptionsAttribute), true)[0] as ArgOptionsAttribute; casesensitive = aoa.CaseSensitive; allowshortcut = aoa.AllowShortcut; seperator = aoa.Seperator; prefix = aoa.Prefix; msgbox = aoa.MessageBox; shortlen = aoa.ShortcutLength; pauserr = aoa.PauseOnError; ignoreunknown = aoa.IgnoreUnknownArguments; re = new Regex(string.Format(@" (({0} # switch (?<name>[_A-Za-z][_\w]*) # name (any legal C# name) ({1} # sep + optional space (((""(?<value>((\\"")|[^""])*)"")| # match a double quoted value (escape "" with \) ('(?<value>((\\')|[^'])*)'))| # match a single quoted value (escape ' with \) (\{{(?<arrayval>[^\}}]*)\}})| # list value (escaped for string.Format) (?<value>\S+)) # any single value )?)| # sep option + list (((""(?<value>((\\"")|[^""])*)"")| # match a double quoted value (escape "" with \) ('(?<value>((\\')|[^'])*)'))| # match a single quoted value (escape ' with \) (\{{(?<arrayval>[^\}}]*)\}})| # list value (escaped for string.Format) (?<value>\S+)))* # any single value", Regex.Escape(prefix), seperator.Trim() == string.Empty ? @"\s+" : @"\s*" + Regex.Escape(seperator) + @"\s*" ), RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace); arrre = new Regex(@"\s*(?<value>((\\,)|[^,])+)(\s*,\s*(?<value>((\\,)|[^,])+))*\s*", // escape , with \ RegexOptions.Compiled | RegexOptions.ExplicitCapture); } Dictionary<string, ArgInfo> argz = new Dictionary<string, ArgInfo>(); string allargs = Environment.CommandLine; allargs = allargs.Replace(string.Format(@"""{0}""", Application.ExecutablePath), "").Trim(); if (prefix == string.Empty) { throw new ArgumentException("prefix cannot be empty string"); } foreach (FieldInfo fi in argclass.GetFields(flags)) { object defval = fi.GetValue(this); string n = fi.Name; if (!casesensitive) { n = n.ToLower(); } fi.SetValue(this, defval); ArgInfo ai = new ArgInfo(fi, this, defval); if (ai.Options is DefaultArgAttribute) { argz.Add(MAGIC, ai); } //be very careful with the next line! if (!(ai.Options is DefaultArgAttribute) || ((DefaultArgAttribute)ai.Options).AllowName) { argz.Add(n, ai); if (allowshortcut) { string sn = ai.Options.Shortname; if (sn == null) { int nlen = n.Length - 1; if (nlen > 0 && shortlen < n.Length) { sn = n.Substring(0, nlen < shortlen ? nlen : shortlen); if (!argz.ContainsKey(sn)) { argz.Add(sn, ai); ai.Options.Shortname = sn; } } } else { if (!argz.ContainsKey(sn)) { argz.Add(sn, ai); } } } } } if (allargs.StartsWith(prefix + "?") || allargs.StartsWith(prefix + "help")) { PrintHelp(argz); Environment.Exit(0); } Group g = null; bool haserror = false; foreach (Match m in re.Matches(allargs)) { string argname = null; try { if (m.Value == string.Empty) { continue; } object val = null; if ((g = m.Groups["name"]).Success) { argname = g.Value; if (!casesensitive) { argname = argname.ToLower(); } } else { argname = MAGIC; } ArgInfo arginfo = argz[argname]; if (arginfo == null) { if (ignoreunknown) { Console.Error.WriteLine("Warning: Ignoring argument unknown '{0}'", argname); } else { Console.Error.WriteLine("Error: Argument '{0}' not known", argname); haserror = true; } continue; } Type t = arginfo.Type; if (t == null) { continue; } if (t.IsArray && argname != MAGIC) { if ((g = m.Groups["arrayval"]).Success) { Type elet = t.GetElementType(); TypeConverter tc = TypeDescriptor.GetConverter(elet); Match arrm = arrre.Match(g.Value); if (arrm.Success) { Group gg = arrm.Groups["value"]; Array arr = Array.CreateInstance(elet, gg.Captures.Count); for (int i = 0; i < arr.Length; i++) { arr.SetValue(tc.ConvertFromString(gg.Captures[i].Value.Trim()), i); } val = arr; } } } else { if ((g = m.Groups["value"]).Success) { string v = g.Value; if (t == typeof(bool) && (v == "on" || v == "off")) { val = v == "on"; } else { if (t.IsArray) { ArrayList vals = new ArrayList(); if (arginfo.Value != null) { vals.AddRange(arginfo.Value as ICollection); } TypeConverter tc = TypeDescriptor.GetConverter(t.GetElementType()); vals.Add(tc.ConvertFromString(v)); val = vals.ToArray(typeof(string)) as string[]; } else { TypeConverter tc = TypeDescriptor.GetConverter(t); val = tc.ConvertFromString(v); } } } else { val = t == typeof(bool); } } arginfo.Value = val; } catch (Exception ex) { Console.Error.WriteLine("Error: Argument '{0}' could not be read ({1})", argname, ex.Message, ex.GetBaseException().GetType().Name); haserror = true; } } if (haserror) { PrintHelp(argz); if (pauserr && !msgbox) { Console.WriteLine("Press any key to exit"); Console.Read(); } Environment.Exit(1); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace KaoriStudio.Core.Collections { /// <summary> /// A generic wrapper for a System.Collections.IDictionary /// </summary> /// <typeparam name="K">The key type</typeparam> /// <typeparam name="V">The value type</typeparam> public struct GenericDictionary<K, V> : IDictionary<K, V> { /// <summary> /// The underlying dictionary /// </summary> public IDictionary Dictionary { get; set; } /// <summary> /// Creates a new GenericDictionary /// </summary> /// <param name="Dictionary">The underlying dictionary</param> public GenericDictionary(IDictionary Dictionary) { this.Dictionary = Dictionary; } /// <summary> /// The key based indexor /// </summary> /// <param name="key">The key</param> /// <returns>The value</returns> public V this[K key] { get { return (V)Dictionary[key]; } set { Dictionary[key] = value; } } /// <summary> /// The number of pairs in this dictionary /// </summary> public int Count { get { return Dictionary.Count; } } /// <summary> /// Whether this dictionary is read-only /// </summary> public bool IsReadOnly { get { return Dictionary.IsReadOnly; } } /// <summary> /// The collection of keys in this dictionary /// </summary> public GenericCollection<K> Keys { get { return new GenericCollection<K>(Dictionary.Keys); } } ICollection<K> IDictionary<K, V>.Keys { get { return Keys; } } /// <summary> /// The collection of values in this dictionary /// </summary> public GenericCollection<V> Values { get { return new GenericCollection<V>(Dictionary.Values); } } ICollection<V> IDictionary<K, V>.Values { get { return Values; } } /// <summary> /// Adds a pair to this dictionary /// </summary> /// <param name="item">The pair</param> public void Add(KeyValuePair<K, V> item) { Dictionary.Add(item.Key, item.Value); } /// <summary> /// Adds an entry to this dictionary /// </summary> /// <param name="key">The key</param> /// <param name="value">The value</param> public void Add(K key, V value) { Dictionary.Add(key, value); } /// <summary> /// Clears this dictionary /// </summary> public void Clear() { Dictionary.Clear(); } bool ICollection<KeyValuePair<K, V>>.Contains(KeyValuePair<K, V> item) { throw new NotImplementedException(); } /// <summary> /// Checks for the presence of a key in this dictionary /// </summary> /// <param name="key">The key</param> /// <returns>Whether the key was found</returns> public bool ContainsKey(K key) { return Dictionary.Contains(key); } /// <summary> /// Copies the contents of this dictionary to an array /// </summary> /// <param name="array">The array</param> /// <param name="arrayIndex">The starting index</param> public void CopyTo(KeyValuePair<K, V>[] array, int arrayIndex) { if (array == null) throw new ArgumentNullException("array"); if (arrayIndex < 0) throw new ArgumentOutOfRangeException("arrayIndex", arrayIndex, "Cannot be less than zero"); var count = Count; if ((count + arrayIndex) >= array.Length) throw new ArgumentException(); var enumerator = GetEnumerator(); for(int i=arrayIndex;enumerator.MoveNext();i++) { array[i] = enumerator.Current; } } /// <summary> /// Gets the enumerator for this dictionary /// </summary> /// <returns>The enumerator</returns> public GenericDictionaryEnumerator<K, V> GetEnumerator() { return new GenericDictionaryEnumerator<K, V>(Dictionary.GetEnumerator()); } IEnumerator<KeyValuePair<K, V>> IEnumerable<KeyValuePair<K, V>>.GetEnumerator() { return GetEnumerator(); } bool ICollection<KeyValuePair<K, V>>.Remove(KeyValuePair<K, V> item) { throw new NotImplementedException(); } /// <summary> /// Attempts to remove a pair with a given key /// </summary> /// <param name="key">The key</param> /// <returns>Whether the pair was found and removed</returns> public bool Remove(K key) { if (Dictionary.Contains(key)) { Dictionary.Remove(key); return true; } else return false; } /// <summary> /// Tries to retrieve a value from this dictionary /// </summary> /// <param name="key">The key</param> /// <param name="value">The value output</param> /// <returns>Whether the value was successfully retrieved</returns> public bool TryGetValue(K key, out V value) { if (Dictionary.Contains(key)) { value = (V)Dictionary[key]; return true; } else { value = default(V); return false; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
// 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 OLEDB.Test.ModuleCore; using XmlCoreTest.Common; namespace System.Xml.Tests { public enum EINTEGRITY { //DataReader BEFORE_READ, AFTER_READ_FALSE, AFTER_RESETSTATE, //DataWriter BEFORE_WRITE, AFTER_WRITE_FALSE, AFTER_CLEAR, AFTER_FLUSH, // Both DataWriter and DataReader AFTER_CLOSE, CLOSE_IN_THE_MIDDLE, }; //////////////////////////////////////////////////////////////// // TestCase TCXMLIntegrity // //////////////////////////////////////////////////////////////// [InheritRequired()] public partial class TCXMLIntegrityBase : CDataReaderTestCase { private EINTEGRITY _eEIntegrity; public EINTEGRITY IntegrityVer { get { return _eEIntegrity; } set { _eEIntegrity = value; } } private static string s_ATTR = "Attr1"; private static string s_NS = "Foo"; private static string s_NAME = "PLAY0"; public virtual void ReloadSource() { // load the reader string strFile = GetTestFileName(EREADER_TYPE.GENERIC); DataReader.Internal = XmlReader.Create(FilePathUtil.getStream(strFile)); // position the reader at the expected place InitReaderPointer(); } public int InitReaderPointer() { int iRetVal = TEST_PASS; CError.WriteLine("InitReaderPointer:{0}", GetDescription()); if (GetDescription() == "BeforeRead") { IntegrityVer = EINTEGRITY.BEFORE_READ; CError.Compare(DataReader.ReadState, ReadState.Initial, "ReadState=Initial"); CError.Compare(DataReader.EOF, false, "EOF==false"); } else if (GetDescription() == "AfterReadIsFalse") { IntegrityVer = EINTEGRITY.AFTER_READ_FALSE; while (DataReader.Read()) ; CError.Compare(DataReader.ReadState, ReadState.EndOfFile, "ReadState=EOF"); CError.Compare(DataReader.EOF, true, "EOF==true"); } else if (GetDescription() == "AfterClose") { IntegrityVer = EINTEGRITY.AFTER_CLOSE; while (DataReader.Read()) ; DataReader.Close(); CError.Compare(DataReader.ReadState, ReadState.Closed, "ReadState=Closed"); CError.Compare(DataReader.EOF, false, "EOF==true"); } else if (GetDescription() == "AfterCloseInTheMiddle") { IntegrityVer = EINTEGRITY.CLOSE_IN_THE_MIDDLE; for (int i = 0; i < 1; i++) { if (false == DataReader.Read()) iRetVal = TEST_FAIL; CError.Compare(DataReader.ReadState, ReadState.Interactive, "ReadState=Interactive"); } DataReader.Close(); CError.Compare(DataReader.ReadState, ReadState.Closed, "ReadState=Closed"); CError.Compare(DataReader.EOF, false, "EOF==true"); CError.WriteLine("EOF = " + DataReader.EOF); } else if (GetDescription() == "AfterResetState") { IntegrityVer = EINTEGRITY.AFTER_RESETSTATE; // position the reader somewhere in the middle of the file DataReader.PositionOnElement("elem1"); DataReader.ResetState(); CError.Compare(DataReader.ReadState, ReadState.Initial, "ReadState=Initial"); } CError.WriteLine("ReadState = " + (DataReader.ReadState).ToString()); return iRetVal; } [Variation("NodeType")] public int GetXmlReaderNodeType() { ReloadSource(); CError.Compare(DataReader.NodeType, XmlNodeType.None, CurVariation.Desc); CError.Compare(DataReader.NodeType, XmlNodeType.None, CurVariation.Desc); return TEST_PASS; } [Variation("Name")] public int GetXmlReaderName() { CError.Compare(DataReader.Name, String.Empty, CurVariation.Desc); CError.Compare(DataReader.Name, String.Empty, CurVariation.Desc); return TEST_PASS; } [Variation("LocalName")] public int GetXmlReaderLocalName() { CError.Compare(DataReader.LocalName, String.Empty, CurVariation.Desc); CError.Compare(DataReader.LocalName, String.Empty, CurVariation.Desc); return TEST_PASS; } [Variation("NamespaceURI")] public int Namespace() { CError.Compare(DataReader.NamespaceURI, String.Empty, CurVariation.Desc); CError.Compare(DataReader.NamespaceURI, String.Empty, CurVariation.Desc); return TEST_PASS; } [Variation("Prefix")] public int Prefix() { CError.Compare(DataReader.Prefix, String.Empty, CurVariation.Desc); CError.Compare(DataReader.Prefix, String.Empty, CurVariation.Desc); return TEST_PASS; } [Variation("HasValue")] public int HasValue() { CError.Compare(DataReader.HasValue, false, CurVariation.Desc); CError.Compare(DataReader.HasValue, false, CurVariation.Desc); return TEST_PASS; } [Variation("Value")] public int GetXmlReaderValue() { CError.Compare(DataReader.Value, String.Empty, CurVariation.Desc); CError.Compare(DataReader.Value, String.Empty, CurVariation.Desc); return TEST_PASS; } [Variation("Depth")] public int GetDepth() { CError.Compare(DataReader.Depth, 0, CurVariation.Desc); CError.Compare(DataReader.Depth, 0, CurVariation.Desc); return TEST_PASS; } [Variation("BaseURI")] public virtual int GetBaseURI() { return TEST_SKIPPED; } [Variation("IsEmptyElement")] public int IsEmptyElement() { CError.Compare(DataReader.IsEmptyElement, false, CurVariation.Desc); CError.Compare(DataReader.IsEmptyElement, false, CurVariation.Desc); return TEST_PASS; } [Variation("IsDefault")] public int IsDefault() { CError.Compare(DataReader.IsDefault, false, CurVariation.Desc); CError.Compare(DataReader.IsDefault, false, CurVariation.Desc); return TEST_PASS; } [Variation("XmlSpace")] public int GetXmlSpace() { CError.Compare(DataReader.XmlSpace, XmlSpace.None, CurVariation.Desc); CError.Compare(DataReader.XmlSpace, XmlSpace.None, CurVariation.Desc); return TEST_PASS; } [Variation("XmlLang")] public int GetXmlLang() { CError.Compare(DataReader.XmlLang, String.Empty, CurVariation.Desc); CError.Compare(DataReader.XmlLang, String.Empty, CurVariation.Desc); return TEST_PASS; } [Variation("AttributeCount")] public int AttributeCount() { CError.Compare(DataReader.AttributeCount, 0, CurVariation.Desc); CError.Compare(DataReader.AttributeCount, 0, CurVariation.Desc); return TEST_PASS; } [Variation("HasAttributes")] public int HasAttribute() { CError.Compare(DataReader.HasAttributes, false, CurVariation.Desc); CError.Compare(DataReader.HasAttributes, false, CurVariation.Desc); return TEST_PASS; } [Variation("GetAttributes(name)")] public int GetAttributeName() { CError.Compare(DataReader.GetAttribute(s_ATTR), null, "Compare the GetAttribute"); return TEST_PASS; } [Variation("GetAttribute(String.Empty)")] public int GetAttributeEmptyName() { CError.Compare(DataReader.GetAttribute(String.Empty), null, "Compare the GetAttribute"); return TEST_PASS; } [Variation("GetAttribute(name,ns)")] public int GetAttributeNameNamespace() { CError.Compare(DataReader.GetAttribute(s_ATTR, s_NS), null, "Compare the GetAttribute"); return TEST_PASS; } [Variation("GetAttribute(String.Empty, String.Empty)")] public int GetAttributeEmptyNameNamespace() { CError.Compare(DataReader.GetAttribute(String.Empty, String.Empty), null, "Compare the GetAttribute"); return TEST_PASS; } [Variation("GetAttribute(i)")] public int GetAttributeOrdinal() { try { DataReader.GetAttribute(0); } catch (ArgumentOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("this[i]")] public int HelperThisOrdinal() { ReloadSource(); try { string str = DataReader[0]; } catch (ArgumentOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("this[name]")] public int HelperThisName() { ReloadSource(); CError.Compare(DataReader[s_ATTR], null, "Compare the GetAttribute"); return TEST_PASS; } [Variation("this[name,namespace]")] public int HelperThisNameNamespace() { ReloadSource(); string str = DataReader[s_ATTR, s_NS]; CError.Compare(DataReader[s_ATTR, s_NS], null, "Compare the GetAttribute"); return TEST_PASS; } [Variation("MoveToAttribute(name)")] public int MoveToAttributeName() { ReloadSource(); CError.Compare(DataReader.MoveToAttribute(s_ATTR), false, CurVariation.Desc); CError.Compare(DataReader.MoveToAttribute(s_ATTR), false, CurVariation.Desc); return TEST_PASS; } [Variation("MoveToAttributeNameNamespace(name,ns)")] public int MoveToAttributeNameNamespace() { ReloadSource(); CError.Compare(DataReader.MoveToAttribute(s_ATTR, s_NS), false, CurVariation.Desc); CError.Compare(DataReader.MoveToAttribute(s_ATTR, s_NS), false, CurVariation.Desc); return TEST_PASS; } [Variation("MoveToAttribute(i)")] public int MoveToAttributeOrdinal() { ReloadSource(); try { DataReader.MoveToAttribute(0); } catch (ArgumentOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("MoveToFirstAttribute()")] public int MoveToFirstAttribute() { ReloadSource(); CError.Compare(DataReader.MoveToFirstAttribute(), false, CurVariation.Desc); CError.Compare(DataReader.MoveToFirstAttribute(), false, CurVariation.Desc); return TEST_PASS; } [Variation("MoveToNextAttribute()")] public int MoveToNextAttribute() { ReloadSource(); CError.Compare(DataReader.MoveToNextAttribute(), false, CurVariation.Desc); CError.Compare(DataReader.MoveToNextAttribute(), false, CurVariation.Desc); return TEST_PASS; } [Variation("MoveToElement()")] public int MoveToElement() { ReloadSource(); CError.Compare(DataReader.MoveToElement(), false, CurVariation.Desc); CError.Compare(DataReader.MoveToElement(), false, CurVariation.Desc); return TEST_PASS; } [Variation("Read")] public int ReadTestAfterClose() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interesting for test return TEST_SKIPPED; } else { CError.Compare(DataReader.Read(), false, CurVariation.Desc); CError.Compare(DataReader.Read(), false, CurVariation.Desc); } return TEST_PASS; } [Variation("GetEOF")] public int GetEOF() { ReloadSource(); if ((IntegrityVer == EINTEGRITY.AFTER_READ_FALSE)) { CError.Compare(DataReader.EOF, true, CurVariation.Desc); CError.Compare(DataReader.EOF, true, CurVariation.Desc); } else { CError.Compare(DataReader.EOF, false, CurVariation.Desc); CError.Compare(DataReader.EOF, false, CurVariation.Desc); } return TEST_PASS; } [Variation("GetReadState")] public int GetReadState() { ReloadSource(); ReadState iState = ReadState.Initial; // EndOfFile State if ((IntegrityVer == EINTEGRITY.AFTER_READ_FALSE)) { iState = ReadState.EndOfFile; } // Closed State if ((IntegrityVer == EINTEGRITY.AFTER_CLOSE) || (IntegrityVer == EINTEGRITY.CLOSE_IN_THE_MIDDLE)) { iState = ReadState.Closed; } CError.Compare(DataReader.ReadState, iState, CurVariation.Desc); CError.Compare(DataReader.ReadState, iState, CurVariation.Desc); return TEST_PASS; } [Variation("Skip")] public int XMLSkip() { ReloadSource(); DataReader.Skip(); DataReader.Skip(); return TEST_PASS; } [Variation("NameTable")] public int TestNameTable() { ReloadSource(); CError.Compare(DataReader.NameTable != null, "nt"); return TEST_PASS; } [Variation("ReadInnerXml")] public int ReadInnerXmlTestAfterClose() { ReloadSource(); XmlNodeType nt = DataReader.NodeType; string name = DataReader.Name; string value = DataReader.Value; CError.Compare(DataReader.ReadInnerXml(), String.Empty, CurVariation.Desc); CError.Compare(DataReader.VerifyNode(nt, name, value), "vn"); return TEST_PASS; } [Variation("ReadOuterXml")] public int TestReadOuterXml() { ReloadSource(); XmlNodeType nt = DataReader.NodeType; string name = DataReader.Name; string value = DataReader.Value; CError.Compare(DataReader.ReadOuterXml(), String.Empty, CurVariation.Desc); CError.Compare(DataReader.VerifyNode(nt, name, value), "vn"); return TEST_PASS; } [Variation("MoveToContent")] public int TestMoveToContent() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { CError.WriteLine("NodeType " + DataReader.NodeType); CError.Compare(DataReader.MoveToContent(), XmlNodeType.None, CurVariation.Desc); } return TEST_PASS; } [Variation("IsStartElement")] public int TestIsStartElement() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { CError.Compare(DataReader.IsStartElement(), false, CurVariation.Desc); } return TEST_PASS; } [Variation("IsStartElement(name)")] public int TestIsStartElementName() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { CError.Compare(DataReader.IsStartElement(s_NAME), false, CurVariation.Desc); } return TEST_PASS; } [Variation("IsStartElement(String.Empty)")] public int TestIsStartElementName2() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { CError.Compare(DataReader.IsStartElement(String.Empty), false, CurVariation.Desc); } return TEST_PASS; } [Variation("IsStartElement(name, ns)")] public int TestIsStartElementNameNs() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { CError.Compare(DataReader.IsStartElement(s_NAME, s_NS), false, CurVariation.Desc); } return TEST_PASS; } [Variation("IsStartElement(String.Empty,String.Empty)")] public int TestIsStartElementNameNs2() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { CError.Compare(DataReader.IsStartElement(String.Empty, String.Empty), false, CurVariation.Desc); } return TEST_PASS; } [Variation("ReadStartElement")] public int TestReadStartElement() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { try { DataReader.ReadStartElement(); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } } [Variation("ReadStartElement(name)")] public int TestReadStartElementName() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { try { DataReader.ReadStartElement(s_NAME); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } } [Variation("ReadStartElement(String.Empty)")] public int TestReadStartElementName2() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { try { DataReader.ReadStartElement(String.Empty); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } } [Variation("ReadStartElement(name, ns)")] public int TestReadStartElementNameNs() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { try { DataReader.ReadStartElement(s_NAME, s_NS); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } } [Variation("ReadStartElement(String.Empty,String.Empty)")] public int TestReadStartElementNameNs2() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { try { DataReader.ReadStartElement(String.Empty, String.Empty); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } } [Variation("ReadEndElement")] public int TestReadEndElement() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { try { DataReader.ReadEndElement(); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } } [Variation("LookupNamespace")] public int LookupNamespace() { ReloadSource(); string[] astr = { "a", "Foo", /*String.Empty,*/ "Foo1", "Foo_S" }; // for String.Empty XmlTextReader returns null, while xmlreader returns "" for (int i = 0; i < astr.Length; i++) { if (DataReader.LookupNamespace(astr[i]) != null) { CError.WriteLine("Not NULL " + i + " LookupNameSpace " + DataReader.LookupNamespace(astr[i]) + "," + DataReader.NodeType); } CError.Compare(DataReader.LookupNamespace(astr[i]), null, CurVariation.Desc); } return TEST_PASS; } [Variation("ResolveEntity")] public int ResolveEntity() { ReloadSource(); try { DataReader.ResolveEntity(); } catch (InvalidOperationException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("ReadAttributeValue")] public int ReadAttributeValue() { ReloadSource(); CError.Compare(DataReader.ReadAttributeValue(), false, CurVariation.Desc); CError.Compare(DataReader.ReadAttributeValue(), false, CurVariation.Desc); return TEST_PASS; } [Variation("Close")] public int CloseTest() { DataReader.Close(); DataReader.Close(); DataReader.Close(); return TEST_PASS; } } }
// Copyright (c) 2012, Miron Brezuleanu // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Globalization; using Shovel.Exceptions; using Shovel.Vm.Types; using Shovel.Compiler.Types; using System.IO; namespace Shovel.Vm { public class Vm { #region Private Storage Instruction[] bytecode = null; object[] cache = null; int programCounter = 0; VmEnvironment currentEnvironment = null; Stack stack = new Stack (); Dictionary<string, Callable> userPrimitives = null; int usedCells = 0; long executedTicks = 0; long executedTicksSinceLastNap = 0; List<SourceFile> sources; bool shouldTakeANap = false; Exception userDefinedPrimitiveError = null; ShovelException programmingError = null; int? cellsQuota = null; long? totalTicksQuota = null; long? untilNextNapTicksQuota = null; VmApi api = null; #endregion #region Public API internal ShovelException ProgrammingError { get { return programmingError; } } internal Exception UserDefinedPrimitiveError { get { return userDefinedPrimitiveError; } } internal int UsedCells { get { this.usedCells = CountCells (); return usedCells; } } internal long ExecutedTicks { get { return executedTicks; } } internal long ExecutedTicksSinceLastNap { get { return executedTicksSinceLastNap; } } internal static Vm RunVm ( Instruction[] bytecode, List<SourceFile> sources = null, IEnumerable<Callable> userPrimitives = null, byte[] state = null, Vm vm = null, int? cellsQuota = null, long? totalTicksQuota = null, long? untilNextNapTicksQuota = null) { if (vm == null) { vm = new Vm (); vm.bytecode = bytecode; vm.cache = new object[bytecode.Length]; vm.programCounter = 0; vm.currentEnvironment = null; vm.stack = new Stack (); vm.sources = sources; vm.userPrimitives = new Dictionary<string, Callable> (); } vm.cellsQuota = cellsQuota; vm.totalTicksQuota = totalTicksQuota; vm.untilNextNapTicksQuota = untilNextNapTicksQuota; if (state != null) { // Utils.TimeIt ("Deserialize VM state", () => { vm.DeserializeState (state); // } // ); } if (userPrimitives != null) { foreach (var udp in userPrimitives) { vm.userPrimitives [udp.UdpName] = udp; } } vm.executedTicksSinceLastNap = 0; vm.api = new VmApi ( raiseShovelError: vm.RaiseShovelError, ticksIncrementer: vm.IncrementTicks, cellsIncrementer: vm.IncrementCells, cellsIncrementHerald: vm.IncrementCellsHerald); do { } while (vm.StepVm()); return vm; } internal void WakeUp () { this.shouldTakeANap = false; } internal Value CheckStackTop () { if (this.stack.Count != 1) { Utils.Panic (); } return this.stack.Top (); } #endregion #region Assembly-internal API internal void SerializeState (Stream s) { CheckVmWithoutError (); var ser = new Serialization.VmStateSerializer (); var usedStack = this.stack.GetUsedStack (); int stackIndex = ser.Serialize (usedStack); int envIndex = ser.Serialize (this.currentEnvironment); Serialization.Utils.WriteBytes (s, BitConverter.GetBytes (Shovel.Api.Version)); Serialization.Utils.WriteBytes (s, BitConverter.GetBytes (stackIndex)); Serialization.Utils.WriteBytes (s, BitConverter.GetBytes (envIndex)); Serialization.Utils.WriteBytes (s, BitConverter.GetBytes (this.programCounter)); Serialization.Utils.WriteBytes (s, Encoding.UTF8.GetBytes (Utils.GetBytecodeMd5 (this.bytecode))); Serialization.Utils.WriteBytes (s, Encoding.UTF8.GetBytes (Utils.GetSourcesMd5 (this.bytecode))); Serialization.Utils.WriteBytes (s, BitConverter.GetBytes (this.executedTicks)); Serialization.Utils.WriteBytes (s, BitConverter.GetBytes (this.usedCells)); ser.WriteToStream (s); } #endregion #region Private Helper Functions void DeserializeState (byte[] serializedState) { using (var ms = new MemoryStream(serializedState)) { Serialization.Utils.DeserializeWithMd5CheckSum (ms, str => { var version = Serialization.Utils.ReadInt (str); if (version > Shovel.Api.Version) { throw new Exceptions.VersionNotSupportedException (); } var stackIndex = Serialization.Utils.ReadInt (str); var envIndex = Serialization.Utils.ReadInt (str); this.programCounter = Serialization.Utils.ReadInt (str); var bytes = new byte[32]; str.Read (bytes, 0, 32); var actualBytecodeMd5 = Encoding.UTF8.GetString (bytes); if (actualBytecodeMd5 != Utils.GetBytecodeMd5 (this.bytecode)) { throw new Exceptions.BytecodeDoesntMatchState (); } // Read and ignore the source MD5. str.Read (bytes, 0, 32); // Read the number of ticks executed so far. this.executedTicks = Serialization.Utils.ReadLong (ms); // Read the number of used cells. this.usedCells = Serialization.Utils.ReadInt (ms); var ser = new Serialization.VmStateSerializer (); ser.Deserialize (str, version, reader => { this.stack = new Stack ((Value[])reader (stackIndex)); this.currentEnvironment = (VmEnvironment)reader (envIndex); } ); return null; }); } } static string DumpShovelValue (VmApi api, Value obj) { if (obj.Kind == Value.Kinds.String) { return Prim0.ShovelStringRepresentation (api, obj).stringValue; } else if (obj.Kind == Value.Kinds.Array) { return Prim0.ShovelStringRepresentation (api, obj).stringValue; } else if (obj.Kind == Value.Kinds.Integer) { return Prim0.ShovelStringRepresentation (api, obj).stringValue; } else if (obj.Kind == Value.Kinds.Double) { return Prim0.ShovelStringRepresentation (api, obj).stringValue; } else if (obj.Kind == Value.Kinds.Hash) { return Prim0.ShovelStringRepresentation (api, obj).stringValue; } else if (obj.Kind == Value.Kinds.Callable) { return Prim0.ShovelStringRepresentation (api, obj).stringValue; } else if (obj.Kind == Value.Kinds.Bool) { return Prim0.ShovelStringRepresentation (api, obj).stringValue; } else if (obj.Kind == Value.Kinds.Null) { return Prim0.ShovelStringRepresentation (api, obj).stringValue; } else if (obj.Kind == Value.Kinds.ReturnAddress) { return String.Format ("Return to {0}", obj.ReturnAddressValue.ProgramCounter); } else if (obj.Kind == Value.Kinds.NamedBlock) { return String.Format ("Named block {0} to {0}", obj.NamedBlockValue.Name, obj.NamedBlockValue.BlockEnd); } else { throw new InvalidOperationException (); } } void TraceInstruction (Instruction instruction) { Console.WriteLine ("*****"); Console.WriteLine (instruction.ToString ()); StringBuilder sb = new StringBuilder (); this.PrintLineFor (sb, this.programCounter, instruction.StartPos, instruction.EndPos); Console.WriteLine (sb.ToString ()); Console.WriteLine ("Stack before:"); for (var i = 0; i < this.stack.Count; i++) { Console.WriteLine (DumpShovelValue (this.api, this.stack.Storage [i])); } } bool StepVm () { if (this.IsLive ()) { this.CheckVmWithoutError (); this.CheckQuotas (); try { var instruction = this.CurrentInstruction(); //TraceInstruction(instruction); Vm.handlers[instruction.NumericOpcode](this); this.executedTicks++; this.executedTicksSinceLastNap++; return true; } catch (ShovelException ex) { this.programmingError = ex; throw; } } else { return false; } } static Action<Vm>[] handlers = new Action<Vm>[] { Vm.HandleJump, // 0 Vm.HandleConst, // 1 Vm.HandlePrim0, // 2 Vm.HandlePrim, // 3 Vm.HandleCall, // 4 Vm.HandleCallj, // 5 Vm.HandleFjump, // 6 Vm.HandleLset, // 7 Vm.HandlePop, // 8 Vm.HandleLget, // 9 Vm.HandleFn, // 10 Vm.HandleNewFrame, // 11 Vm.HandleDropFrame, // 12 Vm.HandleArgs, // 13 Vm.HandleReturn, // 14 Vm.HandleBlock, // 15 Vm.HandlePopBlock, // 16 Vm.HandleBlockReturn, // 17 Vm.HandleContext, // 18 Vm.HandleTjump, // 19 Vm.HandleNop, // 20 Vm.HandleDiv, // 21 Vm.HandleMod, // 22 Vm.HandleNeq, // 23 Vm.HandleLt, // 24 Vm.HandleAdd, // 25 Vm.HandleGref, // 26 Vm.HandleEq, // 27 Vm.HandleApush, // 28 Vm.HandleGrefDot, // 29 Vm.HandleSub, // 30 Vm.HandleNeg, // 31 Vm.HandleMul, // 32 Vm.HandleShl, // 33 Vm.HandleShr, // 34 Vm.HandlePow, // 35 Vm.HandleFloor, // 36 Vm.HandleLte, // 37 Vm.HandleGt, // 38 Vm.HandleGte, // 39 Vm.HandleNot, // 40 Vm.HandleAnd, // 41 Vm.HandleIor, // 42 Vm.HandleXor, // 43 Vm.HandleKeys, // 44 Vm.HandleHasKey, // 45 Vm.HandleApop, // 46 Vm.HandleSetIndexed, // 47 Vm.HandleLen, // 48 Vm.HandleIsString, // 49 Vm.HandleIsHash, // 50 Vm.HandleIsBool, // 51 Vm.HandleIsArray, // 52 Vm.HandleIsNumber, // 53 Vm.HandleIsInteger, // 54 Vm.HandleIsCallable, // 55 Vm.HandleDelete, // 56 Vm.HandleIsStruct, // 57 Vm.HandleIsStructInstance, // 58 Vm.HandleSetDotIndexed, // 59 Vm.HandleApply, // 60 }; Instruction CurrentInstruction () { return this.bytecode [this.programCounter]; } internal object GetCurrentCache () { return this.cache [this.programCounter]; } internal void SetCurrentCache (object cache) { this.cache [this.programCounter] = cache; } static void HandleDiv (Vm vm) { var start = vm.stack.Count - 2; Prim0.Divide (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); vm.stack.Pop (); vm.programCounter++; } static void HandleMod (Vm vm) { var start = vm.stack.Count - 2; Prim0.Modulo (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); vm.stack.Pop (); vm.programCounter++; } static void HandleApop (Vm vm) { Prim0.ArrayPop (vm.api, ref vm.stack.Storage [vm.stack.Count - 1]); vm.programCounter++; } static void HandleLen (Vm vm) { Prim0.GetLength (vm.api, ref vm.stack.Storage [vm.stack.Count - 1]); vm.programCounter++; } static void HandleIsString (Vm vm) { Prim0.IsString (vm.api, ref vm.stack.Storage [vm.stack.Count - 1]); vm.programCounter++; } static void HandleIsStruct (Vm vm) { Prim0.IsStruct (vm.api, ref vm.stack.Storage [vm.stack.Count - 1]); vm.programCounter++; } static void HandleIsStructInstance (Vm vm) { var start = vm.stack.Count - 2; Prim0.IsStructInstance (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); vm.stack.Pop (); vm.programCounter++; } static void HandleIsHash (Vm vm) { Prim0.IsHash (vm.api, ref vm.stack.Storage [vm.stack.Count - 1]); vm.programCounter++; } static void HandleIsBool (Vm vm) { Prim0.IsBool (vm.api, ref vm.stack.Storage [vm.stack.Count - 1]); vm.programCounter++; } static void HandleIsArray (Vm vm) { Prim0.IsArray (vm.api, ref vm.stack.Storage [vm.stack.Count - 1]); vm.programCounter++; } static void HandleIsNumber (Vm vm) { Prim0.IsNumber (vm.api, ref vm.stack.Storage [vm.stack.Count - 1]); vm.programCounter++; } static void HandleIsInteger (Vm vm) { Prim0.IsInteger (vm.api, ref vm.stack.Storage [vm.stack.Count - 1]); vm.programCounter++; } static void HandleIsCallable (Vm vm) { Prim0.IsCallable (vm.api, ref vm.stack.Storage [vm.stack.Count - 1]); vm.programCounter++; } static void HandleDelete (Vm vm) { var start = vm.stack.Count - 2; Prim0.DeleteDictionary (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); vm.stack.Pop (); vm.programCounter++; } static void HandleLt (Vm vm) { var start = vm.stack.Count - 2; Prim0.LessThan (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); vm.stack.Pop (); vm.programCounter++; } static void HandleAdd (Vm vm) { var start = vm.stack.Count - 2; Prim0.Add (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); vm.stack.Pop (); vm.programCounter++; } static void HandleGref (Vm vm) { var start = vm.stack.Count - 2; var callGetter = !Prim0.ArrayOrHashGet (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); if (callGetter) { var obj = vm.stack.Storage[start]; if (obj.Kind == Value.Kinds.Hash) { vm.stack.Push(obj.hashValue.IndirectGet); } else if (obj.Kind == Value.Kinds.Array) { vm.stack.Push(obj.arrayValue.IndirectGet); } HandleCallImpl(vm, 2, true); } else { vm.stack.Pop(); vm.programCounter++; } } static void HandleEq (Vm vm) { var start = vm.stack.Count - 2; Prim0.AreEqual (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); vm.stack.Pop (); vm.programCounter++; } static void HandleNeq (Vm vm) { var start = vm.stack.Count - 2; Prim0.AreNotEqual (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); vm.stack.Pop (); vm.programCounter++; } static void HandleLte (Vm vm) { var start = vm.stack.Count - 2; Prim0.LessThanOrEqual (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); vm.stack.Pop (); vm.programCounter++; } static void HandleGt (Vm vm) { var start = vm.stack.Count - 2; Prim0.GreaterThan (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); vm.stack.Pop (); vm.programCounter++; } static void HandleGte (Vm vm) { var start = vm.stack.Count - 2; Prim0.GreaterThanOrEqual (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); vm.stack.Pop (); vm.programCounter++; } static void HandleApush (Vm vm) { var start = vm.stack.Count - 2; Prim0.ArrayPush (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); vm.stack.Pop (); vm.programCounter++; } static void HandleGrefDot (Vm vm) { var start = vm.stack.Count - 2; var callGetter = !Prim0.HashOrStructGetDot (vm, vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); if (callGetter) { var obj = vm.stack.Storage[start]; if (obj.Kind == Value.Kinds.Hash) { vm.stack.Push(obj.hashValue.IndirectGet); HandleCallImpl(vm, 2, true); } } else { vm.stack.Pop (); vm.programCounter++; } } static void HandleSetDotIndexed (Vm vm) { var start = vm.stack.Count - 3; var callSetter = !Prim0.HashOrStructDotSet(vm, vm.api, ref vm.stack.Storage[start], ref vm.stack.Storage[start + 1], ref vm.stack.Storage[start + 2]); if (!callSetter) { vm.stack.PopMany(2); vm.programCounter++; } else { vm.stack.Push(vm.stack.Storage[start].hashValue.IndirectSet); HandleCallImpl(vm, 3, true); } } static void HandleSub (Vm vm) { var start = vm.stack.Count - 2; Prim0.Subtract (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); vm.stack.Pop (); vm.programCounter++; } static void HandleAnd (Vm vm) { var start = vm.stack.Count - 2; Prim0.BitwiseAnd (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); vm.stack.Pop (); vm.programCounter++; } static void HandleIor (Vm vm) { var start = vm.stack.Count - 2; Prim0.BitwiseOr (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); vm.stack.Pop (); vm.programCounter++; } static void HandleXor (Vm vm) { var start = vm.stack.Count - 2; Prim0.BitwiseXor (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); vm.stack.Pop (); vm.programCounter++; } static void HandleSetIndexed (Vm vm) { var start = vm.stack.Count - 3; var callSetter = !Prim0.ArrayOrHashSet (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1], ref vm.stack.Storage [start + 2]); if (!callSetter) { vm.stack.PopMany(2); vm.programCounter++; } else { var obj = vm.stack.Storage[start]; if (obj.Kind == Value.Kinds.Hash) { vm.stack.Push(obj.hashValue.IndirectSet); } else if (obj.Kind == Value.Kinds.Array) { vm.stack.Push(obj.arrayValue.IndirectSet); } HandleCallImpl(vm, 3, true); } } static void HandleNeg (Vm vm) { Prim0.UnaryMinus (vm.api, ref vm.stack.Storage [vm.stack.Count - 1]); vm.programCounter++; } static void HandleNot (Vm vm) { Prim0.LogicalNot (vm.api, ref vm.stack.Storage [vm.stack.Count - 1]); vm.programCounter++; } static void HandleKeys (Vm vm) { Prim0.Keys (vm.api, ref vm.stack.Storage [vm.stack.Count - 1]); vm.programCounter++; } static void HandleMul (Vm vm) { var start = vm.stack.Count - 2; Prim0.Multiply (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); vm.stack.Pop (); vm.programCounter++; } static void HandleHasKey (Vm vm) { var start = vm.stack.Count - 2; Prim0.HasKey (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); vm.stack.Pop (); vm.programCounter++; } static void HandleShl (Vm vm) { var start = vm.stack.Count - 2; Prim0.ShiftLeft (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); vm.stack.Pop (); vm.programCounter++; } static void HandleShr (Vm vm) { var start = vm.stack.Count - 2; Prim0.ShiftRight (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); vm.stack.Pop (); vm.programCounter++; } static void HandlePow (Vm vm) { var start = vm.stack.Count - 2; Prim0.Pow (vm.api, ref vm.stack.Storage [start], ref vm.stack.Storage [start + 1]); vm.stack.Pop (); vm.programCounter++; } static void HandleFloor (Vm vm) { Prim0.Floor (vm.api, ref vm.stack.Storage [vm.stack.Count - 1]); vm.programCounter++; } static void HandleJump (Vm vm) { vm.programCounter = (int)vm.CurrentInstruction ().Arguments; } static void HandleConst (Vm vm) { vm.stack.Push ((Value)vm.CurrentInstruction ().Arguments); vm.programCounter++; vm.IncrementCells (1); } static Dictionary<string, Callable> prim0Hash = null; static Dictionary<string, Callable> Prim0Hash { get { if (Vm.prim0Hash == null) { Vm.prim0Hash = Prim0.GetPrim0Hash (); } return prim0Hash; } } static void HandlePrim0 (Vm vm) { var instruction = vm.CurrentInstruction (); if (vm.GetCurrentCache () == null) { var primName = (string)instruction.Arguments; if (!Vm.Prim0Hash.ContainsKey (primName)) { vm.RaiseShovelError (String.Format ( "Cannot take address of primitive '{0}' (implemented as instruction).", primName) ); } vm.SetCurrentCache (Value.Make (Vm.Prim0Hash [primName])); } vm.stack.Push ((Value)vm.GetCurrentCache ()); vm.IncrementTicks (1); vm.programCounter++; } static Callable GetUdpByName (Vm vm, string udpName) { if (vm.userPrimitives == null || !vm.userPrimitives.ContainsKey (udpName)) { vm.RaiseShovelError (String.Format ( "Unknown user primitive '{0}'.", udpName) ); } return vm.userPrimitives [udpName]; } static void HandlePrim (Vm vm) { var instruction = vm.CurrentInstruction (); if (vm.GetCurrentCache () == null) { var udpName = (string)instruction.Arguments; vm.SetCurrentCache (Value.Make (GetUdpByName (vm, udpName))); } vm.stack.Push ((Value)vm.GetCurrentCache ()); vm.IncrementTicks (1); vm.programCounter++; } static void HandleCall (Vm vm) { var instruction = vm.CurrentInstruction (); var numArgs = (int)instruction.Arguments; Vm.HandleCallImpl (vm, numArgs, true); } static void HandleApply(Vm vm) { var maybeArray = vm.stack.PopTop(); var maybeCallable = vm.stack.PopTop(); if (maybeArray.Kind != Value.Kinds.Array) { vm.RaiseShovelError(String.Format( "Object [{0}] is not an array.", Prim0.ShovelStringRepresentation(vm.api, maybeArray)) ); } var numArgs = maybeArray.arrayValue.Count; foreach (var value in maybeArray.arrayValue) { vm.stack.Push((Value)value); vm.IncrementCells(1); } vm.stack.Push(maybeCallable); Vm.HandleCallImpl(vm, numArgs, true, true); } static void HandleCallImpl (Vm vm, int numArgs, bool saveReturnAddress, bool inApply = false) { var maybeCallable = vm.stack.Top (); if (maybeCallable.Kind != Value.Kinds.Callable) { vm.RaiseShovelError (String.Format ( "Object [{0}] is not callable.", Prim0.ShovelStringRepresentation (vm.api, maybeCallable)) ); } var callable = maybeCallable.CallableValue; if (callable.ProgramCounter.HasValue) { vm.stack.Pop (); CallFunction (callable, vm, numArgs, saveReturnAddress, inApply); if (saveReturnAddress) { vm.IncrementCells (1); } } else { CallPrimitive (callable, vm, numArgs, saveReturnAddress, inApply); } } static void CallFunction (Callable callable, Vm vm, int numArgs, bool saveReturnAddress, bool inApply) { if (callable.Arity != null) { // FIXME: Find out why/when the arity can be null. if (callable.HasCollectParams) { if (callable.Arity.Value <= numArgs) { var extraArgs = numArgs - callable.Arity.Value; var values = new ArrayInstance(); for (int i = 0; i < extraArgs; i++) { values.Add(vm.stack.Storage[i + vm.stack.Count - extraArgs]); } vm.stack.PopMany(extraArgs); vm.stack.Push(Value.Make(values)); } else { ArityError(vm, callable.Arity.Value, numArgs, inApply); } } else if (callable.Arity.Value != numArgs) { ArityError(vm, callable.Arity.Value, numArgs, inApply); } } if (saveReturnAddress) { vm.stack.Push (Value.Make (new ReturnAddress () { ProgramCounter = vm.programCounter + 1, Environment = vm.currentEnvironment })); } vm.currentEnvironment = callable.Environment; vm.programCounter = callable.ProgramCounter.Value; } static void FinishPrimitiveCall ( Vm vm, int numArgs, bool saveReturnAddress, Value result) { vm.stack.PopMany (numArgs); if (saveReturnAddress) { vm.programCounter ++; } else { var maybeRa = vm.stack.PopTop (); if (maybeRa.Kind == Value.Kinds.ReturnAddress) { vm.ApplyReturnAddress (maybeRa.ReturnAddressValue); } else { Utils.Panic (); } } vm.stack.Push (result); vm.IncrementCells (1); } static void CallPrimitive (Callable callable, Vm vm, int numArgs, bool saveReturnAddress, bool inApply) { bool isRequiredPrimitive = false; if (callable.Prim0Name != null) { isRequiredPrimitive = true; if (callable.RequiredPrimitive == null) { callable.RequiredPrimitive = Vm.Prim0Hash [callable.Prim0Name].RequiredPrimitive; } } else if (callable.UserDefinedPrimitive == null) { callable.UserDefinedPrimitive = GetUdpByName (vm, callable.UdpName).UserDefinedPrimitive; } if (callable.Arity != null && callable.Arity.Value != numArgs) { ArityError (vm, callable.Arity.Value, numArgs, inApply); } Value[] array; int start; if (isRequiredPrimitive) { vm.stack.Pop (); // Remove the callable. vm.stack.GetTopRange (numArgs, out array, out start); FinishPrimitiveCall ( vm, numArgs, saveReturnAddress, callable.RequiredPrimitive (vm.api, array, start, numArgs)); } else { vm.stack.GetTopRange (numArgs + 1, out array, out start); var udpResult = new UdpResult (); Value[] args = new Value[numArgs]; Array.Copy (vm.stack.Storage, start, args, 0, numArgs); try { callable.UserDefinedPrimitive (vm.api, args, udpResult); } catch (Exception ex) { vm.userDefinedPrimitiveError = ex; vm.shouldTakeANap = true; } switch (udpResult.After) { case UdpResult.AfterCall.Continue: vm.stack.Pop (); FinishPrimitiveCall (vm, numArgs, saveReturnAddress, udpResult.Result); break; case UdpResult.AfterCall.Nap: vm.stack.Pop (); FinishPrimitiveCall (vm, numArgs, saveReturnAddress, udpResult.Result); vm.shouldTakeANap = true; break; case UdpResult.AfterCall.NapAndRetryOnWakeUp: vm.shouldTakeANap = true; break; } } } static void ArityError (Vm vm, int expectedArity, int actualArity, bool inApply) { var message = "Function of {0} arguments called with {1} arguments."; if (inApply) { message = "The first argument of 'apply', a function of {0} arguments, was called with {1} arguments."; } vm.RaiseShovelError (String.Format ( message, expectedArity, actualArity)); } static void HandleCallj (Vm vm) { var instruction = vm.CurrentInstruction (); var numArgs = (int)instruction.Arguments; Vm.HandleCallImpl (vm, numArgs, false); } void CheckBool () { if (this.stack.Top ().Kind != Value.Kinds.Bool) { RaiseShovelError ("Argument must be a boolean."); } } static void HandleFjump (Vm vm) { var args = (int)vm.CurrentInstruction ().Arguments; // vm.CheckBool (); if (!vm.stack.PopTop ().boolValue) { vm.programCounter = args; } else { vm.programCounter ++; } } static void HandleTjump (Vm vm) { var args = (int)vm.CurrentInstruction ().Arguments; // vm.CheckBool (); if (vm.stack.PopTop ().boolValue) { vm.programCounter = args; } else { vm.programCounter ++; } } static void HandleLset (Vm vm) { var instruction = vm.CurrentInstruction (); var args = (int[])instruction.Arguments; SetInEnvironment (vm.currentEnvironment, args [0], args [1], vm.stack.Top ()); vm.programCounter++; } static void SetInEnvironment ( VmEnvironment env, int frameNumber, int varIndex, Value value) { FindFrame (env, frameNumber).Values [varIndex] = value; } static VmEnvFrame FindFrame (VmEnvironment env, int frameNumber) { while (env != null && frameNumber > 0) { env = env.Next; frameNumber --; } if (env == null) { Utils.Panic (); } return env.Frame; } static void HandlePop (Vm vm) { vm.stack.Pop (); vm.programCounter++; } static void HandleLget (Vm vm) { var instruction = vm.CurrentInstruction (); var args = (int[])instruction.Arguments; vm.stack.Push (FindFrame (vm.currentEnvironment, args [0]).Values [args [1]]); vm.IncrementCells (1); vm.programCounter++; } static Value GetFromEnvironment (VmEnvironment env, int frameNumber, int varIndex) { return FindFrame (env, frameNumber).Values [varIndex]; } static void HandleFn (Vm vm) { var instruction = vm.CurrentInstruction (); var args = (int[])instruction.Arguments; var arity = args[1]; var hasCollectParameters = arity >= Callable.CollectParamsArityModifier; if (hasCollectParameters) { arity -= Callable.CollectParamsArityModifier; } var callable = new Callable () { ProgramCounter = args[0], Arity = arity, HasCollectParams = hasCollectParameters, Environment = vm.currentEnvironment }; vm.stack.Push (Value.Make (callable)); vm.IncrementCells (5); vm.programCounter++; } static void HandleNewFrame (Vm vm) { var instruction = vm.CurrentInstruction (); var args = (string[])instruction.Arguments; var frame = new VmEnvFrame () { VarNames = args, Values = new Value[args.Length], IntroducedAtProgramCounter = vm.programCounter }; var newEnv = new VmEnvironment () { Frame = frame, Next = vm.currentEnvironment }; vm.currentEnvironment = newEnv; vm.IncrementCells (args.Length * 3 + 5); vm.programCounter++; } static void HandleDropFrame (Vm vm) { vm.currentEnvironment = vm.currentEnvironment.Next; vm.programCounter++; } static void HandleArgs (Vm vm) { var instruction = vm.CurrentInstruction (); var argCount = (int)instruction.Arguments; if (argCount > 0) { Value? returnAddress = null; if (vm.stack.Top ().Kind == Value.Kinds.ReturnAddress) { returnAddress = vm.stack.PopTop (); } var values = vm.currentEnvironment.Frame.Values; Array.Copy ( vm.stack.Storage, vm.stack.Count - argCount, values, 0, argCount); vm.stack.PopMany (argCount); if (returnAddress.HasValue) { vm.stack.Push (returnAddress.Value); } } vm.programCounter++; } static void HandleArgs1 (Vm vm) { if (vm.stack.TopIsReturnAddress ()) { vm.currentEnvironment.Frame.Values [0] = vm.stack.UnderTopOne (); vm.stack.UnderPopOneAndCopyTop (); } else { vm.currentEnvironment.Frame.Values [0] = vm.stack.PopTop (); } vm.programCounter++; } static void HandleArgs2 (Vm vm) { if (vm.stack.TopIsReturnAddress ()) { vm.currentEnvironment.Frame.Values [0] = vm.stack.UnderTop (2); vm.currentEnvironment.Frame.Values [1] = vm.stack.UnderTop (1); vm.stack.UnderPopAndCopyTop (2); } else { vm.currentEnvironment.Frame.Values [1] = vm.stack.PopTop (); vm.currentEnvironment.Frame.Values [0] = vm.stack.PopTop (); } vm.programCounter++; } static void HandleArgs3 (Vm vm) { if (vm.stack.TopIsReturnAddress ()) { vm.currentEnvironment.Frame.Values [0] = vm.stack.UnderTop (3); vm.currentEnvironment.Frame.Values [1] = vm.stack.UnderTop (2); vm.currentEnvironment.Frame.Values [2] = vm.stack.UnderTop (1); vm.stack.UnderPopAndCopyTop (3); } else { vm.currentEnvironment.Frame.Values [2] = vm.stack.PopTop (); vm.currentEnvironment.Frame.Values [1] = vm.stack.PopTop (); vm.currentEnvironment.Frame.Values [0] = vm.stack.PopTop (); } vm.programCounter++; } static void HandleReturn (Vm vm) { // SLOW: maybe there's a faster way to manipulate the stack here? var result = vm.stack.PopTop (); var maybeRa = vm.stack.PopTop (); if (maybeRa.Kind == Value.Kinds.ReturnAddress) { vm.ApplyReturnAddress (maybeRa.ReturnAddressValue); } else { Utils.Panic (); } vm.stack.Push (result); } void ApplyReturnAddress (ReturnAddress returnAddress) { this.programCounter = returnAddress.ProgramCounter; this.currentEnvironment = returnAddress.Environment; } static void HandleBlock (Vm vm) { var instruction = vm.CurrentInstruction (); var blockEnd = (int)instruction.Arguments; var name = vm.stack.PopTop (); if (name.Kind != Value.Kinds.String) { vm.RaiseShovelError ("The name of a block must be a string."); } vm.stack.Push (Value.Make (new NamedBlock () { Name = name.stringValue, BlockEnd = blockEnd, Environment = vm.currentEnvironment } ) ); vm.IncrementCells (3); vm.programCounter++; } static void HandlePopBlock (Vm vm) { var returnValue = vm.stack.PopTop (); var namedBlock = vm.stack.PopTop (); if (namedBlock.Kind != Value.Kinds.NamedBlock) { vm.RaiseShovelError ("Invalid context for POP_BLOCK."); } vm.stack.Push (returnValue); vm.programCounter++; } static void HandleBlockReturn (Vm vm) { var returnValue = vm.stack.PopTop (); var name = vm.stack.PopTop (); if (name.Kind != Value.Kinds.String) { vm.RaiseShovelError ("The name of a block must be a string."); } var namedBlockIndex = vm.FindNamedBlock (name.stringValue); if (vm.stack.Count > namedBlockIndex + 1) { vm.stack.RemoveRange (namedBlockIndex + 1, vm.stack.Count - namedBlockIndex - 1); } var namedBlock = vm.stack.Top ().NamedBlockValue; vm.stack.Push (returnValue); vm.programCounter = namedBlock.BlockEnd; vm.currentEnvironment = namedBlock.Environment; } int FindNamedBlock (string blockName) { for (var i = this.stack.Count - 1; i >= 0; i--) { if (this.stack.Storage [i].Kind == Value.Kinds.NamedBlock && this.stack.Storage [i].NamedBlockValue.Name == blockName) { return i; } } this.RaiseShovelError ( String.Format ("Cannot find block '{0}'.", blockName)); return -1; } static void HandleContext (Vm vm) { var stackTraceSb = new StringBuilder (); vm.WriteStackTrace (stackTraceSb); var stackTrace = stackTraceSb.ToString (); var currentEnvironmentSb = new StringBuilder (); vm.WriteCurrentEnvironment (currentEnvironmentSb); var currentEnvironment = currentEnvironmentSb.ToString (); var result = new HashInstance (); result.Add (Value.Make ("stack"), Value.Make (stackTrace)); result.Add (Value.Make ("environment"), Value.Make (currentEnvironment)); vm.IncrementCells (6 + stackTrace.Length + currentEnvironment.Length); vm.stack.Push (Value.Make (result)); vm.programCounter ++; return; } static void HandleNop (Vm vm) { vm.programCounter++; } internal bool IsLive () { return !(this.programCounter == this.bytecode.Length || this.shouldTakeANap); } internal bool ExecutionComplete () { return this.programCounter == this.bytecode.Length; } int CountCellsSvList (List<Value> list, HashSet<object> visited) { var sum = list.Count; visited.Add (list); foreach (var el in list) { sum += CountCellsImpl (el, visited); } return sum; } int CountCellsHash (Dictionary<Value, Value> hash, HashSet<object> visited) { var sum = hash.Count * 2; visited.Add (hash); foreach (var kv in hash) { sum += CountCellsImpl (kv.Key, visited); sum += CountCellsImpl (kv.Value, visited); } return sum; } int CountCellsString (string s) { if (s == null) { return 0; } else { return s.Length; } } int CountCellsNullableInt (int? i) { if (i.HasValue) { return 1; } else { return 0; } } int CountCellsCallable (Callable callable, HashSet<object> visited) { var sum = 5; visited.Add (callable); sum += CountCellsString (callable.UdpName); sum += CountCellsString (callable.Prim0Name); sum += CountCellsImpl (callable.Environment, visited); return sum; } int CountCellsReturnAddress (ReturnAddress returnAddress, HashSet<object> visited) { var sum = 2; visited.Add (returnAddress); sum += CountCellsImpl (returnAddress.Environment, visited); return sum; } int CountCellsNamedBlock (NamedBlock namedBlock, HashSet<object> visited) { var sum = 3; visited.Add (namedBlock); sum += CountCellsString (namedBlock.Name); sum += CountCellsImpl (namedBlock.Environment, visited); return sum; } int CountCellsSvArray (Value[] values, HashSet<object> visited) { var sum = values.Length; visited.Add (values); foreach (var el in values) { sum += CountCellsImpl (el, visited); } return sum; } int CountCellsEnvironment (VmEnvironment env, HashSet<object> visited) { var sum = 3; visited.Add (env); sum += CountCellsImpl (env.Frame, visited); sum += CountCellsImpl (env.Next, visited); return sum; } int CountCellsEnvFrame (VmEnvFrame envFrame, HashSet<object> visited) { var sum = 3; visited.Add (envFrame); sum += CountCellsImpl (envFrame.VarNames, visited); sum += CountCellsImpl (envFrame.Values, visited); return sum; } int CountCellsStringArray (string[] strings, HashSet<object> visited) { var sum = strings.Length; visited.Add (strings); foreach (var str in strings) { sum += CountCellsString (str); } return sum; } int CountCellsImpl (object obj, HashSet<object> visited) { if (obj == null) { return 0; } else if (obj is Value) { var sv = (Value)obj; switch (sv.Kind) { case Value.Kinds.Null: return 1; case Value.Kinds.Integer: return 1; case Value.Kinds.String: return sv.stringValue.Length + 1; case Value.Kinds.Double: return 1; case Value.Kinds.Bool: return 1; case Value.Kinds.Array: return 1 + CountCellsSvList (sv.arrayValue, visited); case Value.Kinds.Hash: return 1 + CountCellsHash (sv.hashValue, visited); case Value.Kinds.Callable: return 1 + CountCellsCallable (sv.CallableValue, visited); case Value.Kinds.ReturnAddress: return 1 + CountCellsReturnAddress (sv.ReturnAddressValue, visited); case Value.Kinds.NamedBlock: return 1 + CountCellsNamedBlock (sv.NamedBlockValue, visited); case Value.Kinds.Struct: return 1 + CountCellsStringArray (sv.StructValue.Fields, visited); case Value.Kinds.StructInstance: return 1 + CountCellsSvArray (sv.structInstanceValue.Values, visited); default: Utils.Panic (); return 0; } } else if (visited.Contains (obj)) { return 0; } else if (obj is Value[]) { return CountCellsSvArray ((Value[])obj, visited); } else if (obj is List<Value>) { return CountCellsSvList ((List<Value>)obj, visited); } else if (obj is VmEnvironment) { return CountCellsEnvironment ((VmEnvironment)obj, visited); } else if (obj is VmEnvFrame) { return CountCellsEnvFrame ((VmEnvFrame)obj, visited); } else if (obj is string[]) { return CountCellsStringArray ((string[])obj, visited); } else { Utils.Panic (); return 0; } } int CountCells () { var visited = new HashSet<object> (); return CountCellsImpl (this.stack.GetUsedStack (), visited) + CountCellsImpl (this.currentEnvironment, visited); } void CheckQuotas () { if (this.cellsQuota.HasValue) { if (this.usedCells > this.cellsQuota.Value) { this.usedCells = this.CountCells (); if (this.usedCells > this.cellsQuota.Value) { throw new Shovel.Exceptions.ShovelCellQuotaExceededException (); } } } if (this.totalTicksQuota.HasValue) { if (this.executedTicks > this.totalTicksQuota.Value) { throw new Shovel.Exceptions.ShovelTicksQuotaExceededException (); } } if (this.untilNextNapTicksQuota.HasValue) { if (this.executedTicksSinceLastNap > this.untilNextNapTicksQuota) { this.shouldTakeANap = true; } } } void CheckVmWithoutError () { if (this.userDefinedPrimitiveError != null) { throw new ShovelException( "An exception has been thrown in a user-defined primitive.", this.userDefinedPrimitiveError ); } if (this.programmingError != null) { throw new ShovelException( "An exception has occurred in the Shovel program.", this.programmingError ); } } void RaiseShovelError (string message) { var sb = new StringBuilder (); sb.AppendLine (message); sb.AppendLine (); sb.AppendLine ("Current stack trace:"); this.WriteStackTrace (sb); sb.AppendLine (); sb.AppendLine ("Current environment:"); sb.AppendLine (); this.WriteCurrentEnvironment (sb); var fileName = this.FindFileName (this.programCounter); int? line = null, column = null; if (fileName != null && this.sources != null) { var source = SourceFile.FindSource (this.sources, fileName); if (source != null) { int? startPos, endPos; this.FindStartEndPos (out startPos, out endPos); if (startPos != null) { var pos = Position.CalculatePosition (source, startPos.Value); if (pos != null) { line = pos.Line; column = pos.Column; } } } } throw new ShovelException (){ ShovelMessage = sb.ToString(), FileName = fileName, Line = line, Column = column }; } string FindFileName (int programCounter) { for (var i = programCounter; i >= 0; i--) { var instruction = this.bytecode [i]; if (instruction.Opcode == Instruction.Opcodes.FileName) { return (string)instruction.Arguments; } } return null; } void FindStartEndPos (out int? startPos, out int? endPos) { startPos = null; endPos = null; for (var i = this.programCounter; i >= 0; i--) { var instruction = this.bytecode [i]; if (instruction.StartPos != null && instruction.EndPos != null) { startPos = instruction.StartPos; endPos = instruction.EndPos; return; } } } void WriteCurrentEnvironment (StringBuilder sb) { for (var env = this.currentEnvironment; env != null; env = env.Next) { if (env.Frame.IntroducedAtProgramCounter != null) { sb.AppendLine ("Frame starts at:"); var pc = env.Frame.IntroducedAtProgramCounter.Value; var instruction = this.bytecode [pc]; this.PrintLineFor (sb, pc, instruction.StartPos, instruction.StartPos); } sb.AppendLine ("Frame variables are:"); for (var i = 0; i < env.Frame.VarNames.Length; i++) { sb.AppendLine (String.Format ( "{0} = {1}", env.Frame.VarNames [i], Prim0.ShovelStringRepresentation (this.api, env.Frame.Values [i]).stringValue) ); } sb.AppendLine (); } } void PrintLineFor (StringBuilder sb, int pc, int? characterStartPos, int? characterEndPos) { var foundLocation = false; if (characterStartPos != null && characterEndPos != null) { if (this.sources != null) { var fileName = this.FindFileName (pc); var sourceFile = SourceFile.FindSource (this.sources, fileName); if (sourceFile != null) { var startPos = Position.CalculatePosition (sourceFile, characterStartPos.Value); var endPos = Position.CalculatePosition (sourceFile, characterEndPos.Value); var lines = Utils.ExtractRelevantSource (sourceFile.Content.Split ('\n'), startPos, endPos); foreach (var line in lines) { sb.AppendLine (line); } foundLocation = true; } } } if (!foundLocation) { sb.AppendLine (String.Format ( "... unknown source location, program counter {0} ...", pc) ); } } void WriteStackTrace (StringBuilder sb) { int? startPos, endPos; this.FindStartEndPos (out startPos, out endPos); this.PrintLineFor (sb, this.programCounter, startPos, endPos); for (var i = this.stack.Count - 1; i >= 0; i--) { if (this.stack.Storage [i].Kind == Value.Kinds.ReturnAddress) { var ra = this.stack.Storage [i].ReturnAddressValue; var pc = ra.ProgramCounter; var callSite = this.bytecode [pc - 1]; this.PrintLineFor (sb, pc, callSite.StartPos, callSite.EndPos); } } } void IncrementTicks (int ticks) { this.executedTicks += ticks; this.executedTicksSinceLastNap += ticks; } void IncrementCells (int cells) { this.usedCells += cells; } void IncrementCellsHerald (int cells) { if (this.cellsQuota != null && cells > this.cellsQuota.Value) { throw new ShovelCellQuotaExceededException (); } } #endregion } }
// Generated by SharpKit.QooxDoo.Generator using System; using System.Collections.Generic; using SharpKit.Html; using SharpKit.JavaScript; namespace qx.core { /// <summary> /// <para>A collection of assertions.</para> /// <para>These methods can be used to assert incoming parameters, return values, ... /// If an assertion fails an <see cref="AssertionError"/> is thrown.</para> /// <para>Assertions are used in unit tests as well.</para> /// </summary> [JsType(JsMode.Prototype, Name = "qx.core.Assert", OmitOptionalParameters = true, Export = false)] public partial class Assert { #region Methods public Assert() { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the condition evaluates to true.</para> /// </summary> /// <param name="condition">Condition to check for. Must evaluate to true.</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assert")] public static void Assertx(object condition, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the number of arguments is within the given range</para> /// </summary> /// <param name="args">The arguments variable of a function</param> /// <param name="minCount">Minimal number of arguments</param> /// <param name="maxCount">Maximum number of arguments</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertArgumentsCount")] public static void AssertArgumentsCount(JsArguments args, double minCount, double maxCount, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is an array.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertArray")] public static void AssertArray(object value, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that both array have identical array items.</para> /// </summary> /// <param name="expected">The expected array</param> /// <param name="found">The found array</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertArrayEquals")] public static void AssertArrayEquals(JsArray expected, JsArray found, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is a boolean.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertBoolean")] public static void AssertBoolean(object value, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value represents the given CSS color value. This method /// parses the color strings and compares the RGB values. It is able to /// parse values supported by <see cref="qx.util.ColorUtil.StringToRgb"/>.</para> /// </summary> /// <param name="expected">The expected color</param> /// <param name="value">The value to check</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertCssColor")] public static void AssertCssColor(string expected, string value, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is a DOM element.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertElement")] public static void AssertElement(object value, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that both values are equal. (Uses the equality operator /// ==.)</para> /// </summary> /// <param name="expected">Reference value</param> /// <param name="found">found value</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertEquals")] public static void AssertEquals(object expected, object found, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that an event is fired.</para> /// </summary> /// <param name="obj">The object on which the event should be fired.</param> /// <param name="eventx">The event which should be fired.</param> /// <param name="invokeFunc">The function which will be invoked and which fires the event.</param> /// <param name="listenerFunc">The function which will be invoked in the listener. The function receives one parameter which is the event.</param> /// <param name="msg">Message to be shows if the assertion fails.</param> [JsMethod(Name = "assertEventFired")] public static void AssertEventFired(object obj, string eventx, Action<object> invokeFunc, Action<object> listenerFunc = null, string msg = "") { throw new NotImplementedException(); } /// <summary> /// <para>Assert that an event is not fired.</para> /// </summary> /// <param name="obj">The object on which the event should be fired.</param> /// <param name="eventx">The event which should be fired.</param> /// <param name="invokeFunc">The function which will be invoked and which should not fire the event.</param> /// <param name="msg">Message to be shows if the assertion fails.</param> [JsMethod(Name = "assertEventNotFired")] public static void AssertEventNotFired(object obj, string eventx, Action<object> invokeFunc, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Asserts that the callback raises a matching exception.</para> /// </summary> /// <param name="callback">function to check</param> /// <param name="exception">Expected constructor of the exception. The assertion fails if the raised exception is not an instance of the parameter.</param> /// <param name="re">The assertion fails if the error message does not match this parameter</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertException")] public static void AssertException(Action<object> callback, JsError exception = null, object re = null, string msg = null) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is false (Identity check).</para> /// </summary> /// <param name="value">Condition to check for. Must be identical to false.</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertFalse")] public static void AssertFalse(bool value, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is a function.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertFunction")] public static void AssertFunction(object value, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that both values are identical. (Uses the identity operator /// ===.)</para> /// </summary> /// <param name="expected">Reference value</param> /// <param name="found">found value</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertIdentical")] public static void AssertIdentical(object expected, object found, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is an item in the given array.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="array">List of valid values</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertInArray")] public static void AssertInArray(object value, JsArray array, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is inside the given range.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="min">lower bound</param> /// <param name="max">upper bound</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertInRange")] public static void AssertInRange(object value, double min, double max, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is an instance of the given class.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="clazz">The value must be an instance of this class</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertInstance")] public static void AssertInstance(object value, Class clazz, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is an integer.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertInteger")] public static void AssertInteger(object value, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value implements the given interface.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="iface">The value must implement this interface</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertInterface")] public static void AssertInterface(object value, Class iface, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the first two arguments are equal, when serialized into /// JSON.</para> /// </summary> /// <param name="expected">The the expected value</param> /// <param name="found">The found value</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertJsonEquals")] public static void AssertJsonEquals(object expected, object found, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is a key in the given map.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="map">Map, where the keys represent the valid values</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertKeyInMap")] public static void AssertKeyInMap(object value, object map, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is a map either created using new Object /// or by using the object literal notation { ... }.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertMap")] public static void AssertMap(object value, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the given string matches the regular expression</para> /// </summary> /// <param name="str">String, which should match the regular expression</param> /// <param name="re">Regular expression to match</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertMatch")] public static void AssertMatch(string str, object re, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that both values are not equal. (Uses the not equality operator /// !=.)</para> /// </summary> /// <param name="expected">Reference value</param> /// <param name="found">found value</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertNotEquals")] public static void AssertNotEquals(object expected, object found, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that both values are not identical. (Uses the not identity operator /// !==.)</para> /// </summary> /// <param name="expected">Reference value</param> /// <param name="found">found value</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertNotIdentical")] public static void AssertNotIdentical(object expected, object found, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is not null.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertNotNull")] public static void AssertNotNull(object value, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is not undefined.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertNotUndefined")] public static void AssertNotUndefined(object value, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is null.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertNull")] public static void AssertNull(object value, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is a number.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertNumber")] public static void AssertNumber(object value, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is an object.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertObject")] public static void AssertObject(object value, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is an integer >= 0.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertPositiveInteger")] public static void AssertPositiveInteger(object value, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is a number >= 0.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertPositiveNumber")] public static void AssertPositiveNumber(object value, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is an instance of <see cref="qx.core.Object"/>.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertQxObject")] public static void AssertQxObject(object value, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is an instance of <see cref="qx.ui.core.Widget"/>.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertQxWidget")] public static void AssertQxWidget(object value, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is a regular expression.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertRegExp")] public static void AssertRegExp(object value, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is a string.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertString")] public static void AssertString(object value, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is true (Identity check).</para> /// </summary> /// <param name="value">Condition to check for. Must be identical to true.</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertTrue")] public static void AssertTrue(bool value, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value has the given type using the typeof /// operator. Because the type is not always what it is supposed to be it is /// better to use more explicit checks like <see cref="AssertString"/> or /// <see cref="AssertArray"/>.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="type">expected type of the value</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertType")] public static void AssertType(object value, string type, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Assert that the value is undefined.</para> /// </summary> /// <param name="value">Value to check</param> /// <param name="msg">Message to be shown if the assertion fails.</param> [JsMethod(Name = "assertUndefined")] public static void AssertUndefined(object value, string msg) { throw new NotImplementedException(); } /// <summary> /// <para>Raise an <see cref="AssertionError"/>.</para> /// </summary> /// <param name="msg">Message to be shown if the assertion fails.</param> /// <param name="compact">Show less verbose message. Default: false.</param> [JsMethod(Name = "fail")] public static void Fail(string msg, bool compact) { throw new NotImplementedException(); } #endregion Methods } }
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using System.Linq; using tk2dEditor.SpriteCollectionEditor; namespace tk2dEditor.SpriteCollectionEditor { public interface IEditorHost { void OnSpriteCollectionChanged(bool retainSelection); void OnSpriteCollectionSortChanged(); Texture2D GetTextureForSprite(int spriteId); SpriteCollectionProxy SpriteCollection { get; } int InspectorWidth { get; } SpriteView SpriteView { get; } void SelectSpritesFromList(int[] indices); void SelectSpritesInSpriteSheet(int spriteSheetId, int[] spriteIds); void Commit(); } public class SpriteCollectionEditorEntry { public enum Type { None, Sprite, SpriteSheet, Font, MaxValue } public string name; public int index; public Type type; public bool selected = false; // list management public int listIndex; // index into the currently active list public int selectionKey; // a timestamp of when the entry was selected, to decide the last selected one } } public class tk2dSpriteCollectionEditorPopup : EditorWindow, IEditorHost { tk2dSpriteCollection _spriteCollection; // internal tmp var SpriteView spriteView; SettingsView settingsView; FontView fontView; SpriteSheetView spriteSheetView; // sprite collection we're editing SpriteCollectionProxy spriteCollectionProxy = null; public SpriteCollectionProxy SpriteCollection { get { return spriteCollectionProxy; } } public SpriteView SpriteView { get { return spriteView; } } // This lists all entries List<SpriteCollectionEditorEntry> entries = new List<SpriteCollectionEditorEntry>(); // This lists all selected entries List<SpriteCollectionEditorEntry> selectedEntries = new List<SpriteCollectionEditorEntry>(); // Callback when a sprite collection is changed and the selection needs to be refreshed public void OnSpriteCollectionChanged(bool retainSelection) { var oldSelection = selectedEntries.ToArray(); PopulateEntries(); if (retainSelection) { searchFilter = ""; // name may have changed foreach (var selection in oldSelection) { foreach (var entry in entries) { if (entry.type == selection.type && entry.index == selection.index) { entry.selected = true; break; } } } UpdateSelection(); } } public void SelectSpritesFromList(int[] indices) { OnSpriteCollectionChanged(true); // clear filter selectedEntries = new List<SpriteCollectionEditorEntry>(); // Clear selection foreach (var entry in entries) entry.selected = false; // Create new selection foreach (var index in indices) { foreach (var entry in entries) { if (entry.type == SpriteCollectionEditorEntry.Type.Sprite && entry.index == index) { entry.selected = true; selectedEntries.Add(entry); break; } } } } public void SelectSpritesInSpriteSheet(int spriteSheetId, int[] spriteIds) { OnSpriteCollectionChanged(true); // clear filter selectedEntries = new List<SpriteCollectionEditorEntry>(); foreach (var entry in entries) { entry.selected = (entry.type == SpriteCollectionEditorEntry.Type.SpriteSheet && entry.index == spriteSheetId); if (entry.selected) { spriteSheetView.Select(spriteCollectionProxy.spriteSheets[spriteSheetId], spriteIds); } } UpdateSelection(); } void UpdateSelection() { // clear settings view if its selected settingsView.show = false; selectedEntries = (from entry in entries where entry.selected == true orderby entry.selectionKey select entry).ToList(); } void ClearSelection() { entries.ForEach((a) => a.selected = false); UpdateSelection(); } // Callback when a sprite collection needs resorting public static bool Contains(string s, string text) { return s.ToLower().IndexOf(text.ToLower()) != -1; } // Callback when a sort criteria is changed public void OnSpriteCollectionSortChanged() { if (searchFilter.Length > 0) { // re-sort list entries = (from entry in entries where Contains(entry.name, searchFilter) orderby entry.type, entry.name select entry).ToList(); } else { // re-sort list entries = (from entry in entries orderby entry.type, entry.name select entry).ToList(); } for (int i = 0; i < entries.Count; ++i) entries[i].listIndex = i; } public int InspectorWidth { get { return tk2dPreferences.inst.spriteCollectionInspectorWidth; } } // populate the entries struct for display in the listbox void PopulateEntries() { entries = new List<SpriteCollectionEditorEntry>(); selectedEntries = new List<SpriteCollectionEditorEntry>(); if (spriteCollectionProxy == null) return; for (int spriteIndex = 0; spriteIndex < spriteCollectionProxy.textureParams.Count; ++spriteIndex) { var sprite = spriteCollectionProxy.textureParams[spriteIndex]; var spriteSourceTexture = sprite.texture; if (spriteSourceTexture == null && sprite.name.Length == 0) continue; var newEntry = new SpriteCollectionEditorEntry(); newEntry.name = sprite.name; if (sprite.texture == null) { newEntry.name += " (missing)"; } newEntry.index = spriteIndex; newEntry.type = SpriteCollectionEditorEntry.Type.Sprite; entries.Add(newEntry); } for (int i = 0; i < spriteCollectionProxy.spriteSheets.Count; ++i) { var spriteSheet = spriteCollectionProxy.spriteSheets[i]; if (!spriteSheet.active) continue; var newEntry = new SpriteCollectionEditorEntry(); newEntry.name = spriteSheet.Name; newEntry.index = i; newEntry.type = SpriteCollectionEditorEntry.Type.SpriteSheet; entries.Add(newEntry); } for (int i = 0; i < spriteCollectionProxy.fonts.Count; ++i) { var font = spriteCollectionProxy.fonts[i]; if (!font.active) continue; var newEntry = new SpriteCollectionEditorEntry(); newEntry.name = font.Name; newEntry.index = i; newEntry.type = SpriteCollectionEditorEntry.Type.Font; entries.Add(newEntry); } OnSpriteCollectionSortChanged(); selectedEntries = new List<SpriteCollectionEditorEntry>(); } public void SetGenerator(tk2dSpriteCollection spriteCollection) { this._spriteCollection = spriteCollection; this.firstRun = true; spriteCollectionProxy = new SpriteCollectionProxy(spriteCollection); PopulateEntries(); } public void SetGeneratorAndSelectedSprite(tk2dSpriteCollection spriteCollection, int selectedSprite) { searchFilter = ""; SetGenerator(spriteCollection); foreach (var entry in entries) { if (entry.type == SpriteCollectionEditorEntry.Type.Sprite && entry.index == selectedSprite) { entry.selected = true; break; } } UpdateSelection(); } int cachedSpriteId = -1; Texture2D cachedSpriteTexture = null; // Returns a texture for a given sprite, if the sprite is a region sprite, a new texture is returned public Texture2D GetTextureForSprite(int spriteId) { var param = spriteCollectionProxy.textureParams[spriteId]; if (spriteId != cachedSpriteId) { ClearTextureCache(); cachedSpriteId = spriteId; } if (param.extractRegion) { if (cachedSpriteTexture == null) { var tex = param.texture; cachedSpriteTexture = new Texture2D(param.regionW, param.regionH); for (int y = 0; y < param.regionH; ++y) { for (int x = 0; x < param.regionW; ++x) { cachedSpriteTexture.SetPixel(x, y, tex.GetPixel(param.regionX + x, param.regionY + y)); } } cachedSpriteTexture.Apply(); } return cachedSpriteTexture; } else { return param.texture; } } void ClearTextureCache() { if (cachedSpriteId != -1) cachedSpriteId = -1; if (cachedSpriteTexture != null) { DestroyImmediate(cachedSpriteTexture); cachedSpriteTexture = null; } } void OnEnable() { if (_spriteCollection != null) { SetGenerator(_spriteCollection); } spriteView = new SpriteView(this); settingsView = new SettingsView(this); fontView = new FontView(this); spriteSheetView = new SpriteSheetView(this); } void OnDisable() { ClearTextureCache(); _spriteCollection = null; tk2dEditorUtility.CollectAndUnloadUnusedAssets(); } string searchFilter = ""; void DrawToolbar() { GUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true)); // LHS GUILayout.BeginHorizontal(GUILayout.Width(leftBarWidth - 6)); // Create Button GUIContent createButton = new GUIContent("Create"); Rect createButtonRect = GUILayoutUtility.GetRect(createButton, EditorStyles.toolbarDropDown, GUILayout.ExpandWidth(false)); if (GUI.Button(createButtonRect, createButton, EditorStyles.toolbarDropDown)) { GUIUtility.hotControl = 0; GUIContent[] menuItems = new GUIContent[] { new GUIContent("Sprite Sheet"), new GUIContent("Font") }; EditorUtility.DisplayCustomMenu(createButtonRect, menuItems, -1, delegate(object userData, string[] options, int selected) { switch (selected) { case 0: int addedSpriteSheetIndex = spriteCollectionProxy.FindOrCreateEmptySpriteSheetSlot(); searchFilter = ""; PopulateEntries(); foreach (var entry in entries) { if (entry.type == SpriteCollectionEditorEntry.Type.SpriteSheet && entry.index == addedSpriteSheetIndex) entry.selected = true; } UpdateSelection(); break; case 1: if (SpriteCollection.allowMultipleAtlases) { EditorUtility.DisplayDialog("Create Font", "Adding fonts to sprite collections isn't allowed when multi atlas spanning is enabled. " + "Please disable it and try again.", "Ok"); } else { int addedFontIndex = spriteCollectionProxy.FindOrCreateEmptyFontSlot(); searchFilter = ""; PopulateEntries(); foreach (var entry in entries) { if (entry.type == SpriteCollectionEditorEntry.Type.Font && entry.index == addedFontIndex) entry.selected = true; } UpdateSelection(); } break; } } , null); } // Filter box GUILayout.Space(8); string newSearchFilter = GUILayout.TextField(searchFilter, tk2dEditorSkin.ToolbarSearch, GUILayout.ExpandWidth(true)); if (newSearchFilter != searchFilter) { searchFilter = newSearchFilter; PopulateEntries(); } if (searchFilter.Length > 0) { if (GUILayout.Button("", tk2dEditorSkin.ToolbarSearchClear, GUILayout.ExpandWidth(false))) { searchFilter = ""; PopulateEntries(); } } else { GUILayout.Label("", tk2dEditorSkin.ToolbarSearchRightCap); } GUILayout.EndHorizontal(); // Label if (_spriteCollection != null) GUILayout.Label(_spriteCollection.name); // RHS GUILayout.FlexibleSpace(); // Always in settings view when empty if (spriteCollectionProxy != null && spriteCollectionProxy.Empty) { GUILayout.Toggle(true, "Settings", EditorStyles.toolbarButton); } else { bool newSettingsView = GUILayout.Toggle(settingsView.show, "Settings", EditorStyles.toolbarButton); if (newSettingsView != settingsView.show) { ClearSelection(); settingsView.show = newSettingsView; } } if (GUILayout.Button("Revert", EditorStyles.toolbarButton) && spriteCollectionProxy != null) { spriteCollectionProxy.CopyFromSource(); OnSpriteCollectionChanged(false); } if (GUILayout.Button("Commit", EditorStyles.toolbarButton) && spriteCollectionProxy != null) Commit(); GUILayout.EndHorizontal(); } public void Commit() { spriteCollectionProxy.DeleteUnusedData(); spriteCollectionProxy.CopyToTarget(); tk2dSpriteCollectionBuilder.ResetCurrentBuild(); if (!tk2dSpriteCollectionBuilder.Rebuild(_spriteCollection)) { EditorUtility.DisplayDialog("Failed to commit sprite collection", "Please check the console for more details.", "Ok"); } spriteCollectionProxy.CopyFromSource(); } void HandleListKeyboardShortcuts(int controlId) { Event ev = Event.current; if (ev.type == EventType.KeyDown && (GUIUtility.keyboardControl == controlId || GUIUtility.keyboardControl == 0) && entries != null && entries.Count > 0) { int selectedIndex = 0; foreach (var e in entries) { if (e.selected) break; selectedIndex++; } int newSelectedIndex = selectedIndex; switch (ev.keyCode) { case KeyCode.Home: newSelectedIndex = 0; break; case KeyCode.End: newSelectedIndex = entries.Count - 1; break; case KeyCode.UpArrow: newSelectedIndex = Mathf.Max(selectedIndex - 1, 0); break; case KeyCode.DownArrow: newSelectedIndex = Mathf.Min(selectedIndex + 1, entries.Count - 1); break; case KeyCode.PageUp: newSelectedIndex = Mathf.Max(selectedIndex - 10, 0); break; case KeyCode.PageDown: newSelectedIndex = Mathf.Min(selectedIndex + 10, entries.Count - 1); break; } if (newSelectedIndex != selectedIndex) { for (int i = 0; i < entries.Count; ++i) entries[i].selected = (i == newSelectedIndex); UpdateSelection(); Repaint(); ev.Use(); } } } Vector2 spriteListScroll = Vector2.zero; int spriteListSelectionKey = 0; void DrawSpriteList() { if (spriteCollectionProxy != null && spriteCollectionProxy.Empty) { DrawDropZone(); return; } int spriteListControlId = GUIUtility.GetControlID("tk2d.SpriteList".GetHashCode(), FocusType.Keyboard); HandleListKeyboardShortcuts(spriteListControlId); spriteListScroll = GUILayout.BeginScrollView(spriteListScroll, GUILayout.Width(leftBarWidth)); GUILayout.BeginVertical(tk2dEditorSkin.SC_ListBoxBG, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); bool multiSelectKey = (Application.platform == RuntimePlatform.OSXEditor)?Event.current.command:Event.current.control; bool shiftSelectKey = Event.current.shift; bool selectionChanged = false; SpriteCollectionEditorEntry.Type lastType = SpriteCollectionEditorEntry.Type.None; foreach (var entry in entries) { if (lastType != entry.type) { if (lastType != SpriteCollectionEditorEntry.Type.None) GUILayout.Space(8); else GUI.SetNextControlName("firstLabel"); GUILayout.Label(GetEntryTypeString(entry.type), tk2dEditorSkin.SC_ListBoxSectionHeader, GUILayout.ExpandWidth(true)); lastType = entry.type; } bool newSelected = GUILayout.Toggle(entry.selected, entry.name, tk2dEditorSkin.SC_ListBoxItem, GUILayout.ExpandWidth(true)); if (newSelected != entry.selected) { GUI.FocusControl("firstLabel"); entry.selectionKey = spriteListSelectionKey++; if (multiSelectKey) { // Only allow multiselection with sprites bool selectionAllowed = entry.type == SpriteCollectionEditorEntry.Type.Sprite; foreach (var e in entries) { if (e != entry && e.selected && e.type != entry.type) { selectionAllowed = false; break; } } if (selectionAllowed) { entry.selected = newSelected; selectionChanged = true; } else { foreach (var e in entries) { e.selected = false; } entry.selected = true; selectionChanged = true; } } else if (shiftSelectKey) { // find first selected entry in list int firstSelection = int.MaxValue; foreach (var e in entries) { if (e.selected && e.listIndex < firstSelection) { firstSelection = e.listIndex; } } int lastSelection = entry.listIndex; if (lastSelection < firstSelection) { lastSelection = firstSelection; firstSelection = entry.listIndex; } // Filter for multiselection if (entry.type == SpriteCollectionEditorEntry.Type.Sprite) { for (int i = firstSelection; i <= lastSelection; ++i) { if (entries[i].type != entry.type) { firstSelection = entry.listIndex; lastSelection = entry.listIndex; } } } else { firstSelection = lastSelection = entry.listIndex; } foreach (var e in entries) { e.selected = (e.listIndex >= firstSelection && e.listIndex <= lastSelection); } selectionChanged = true; } else { foreach (var e in entries) { e.selected = false; } entry.selected = true; selectionChanged = true; } } } if (selectionChanged) { GUIUtility.keyboardControl = spriteListControlId; UpdateSelection(); Repaint(); } GUILayout.EndVertical(); GUILayout.EndScrollView(); Rect viewRect = GUILayoutUtility.GetLastRect(); tk2dPreferences.inst.spriteCollectionListWidth = (int)tk2dGuiUtility.DragableHandle(4819283, viewRect, tk2dPreferences.inst.spriteCollectionListWidth, tk2dGuiUtility.DragDirection.Horizontal); } bool IsValidDragPayload() { int idx = 0; foreach (var v in DragAndDrop.objectReferences) { var type = v.GetType(); if (type == typeof(Texture2D)) return true; else if (type == typeof(Object) && System.IO.Directory.Exists(DragAndDrop.paths[idx])) return true; ++idx; } return false; } string GetEntryTypeString(SpriteCollectionEditorEntry.Type kind) { switch (kind) { case SpriteCollectionEditorEntry.Type.Sprite: return "Sprites"; case SpriteCollectionEditorEntry.Type.SpriteSheet: return "Sprite Sheets"; case SpriteCollectionEditorEntry.Type.Font: return "Fonts"; } Debug.LogError("Unhandled type"); return ""; } void HandleDroppedPayload(Object[] objects) { List<int> addedIndices = new List<int>(); foreach (var obj in objects) { Texture2D tex = obj as Texture2D; string name = spriteCollectionProxy.FindUniqueTextureName(tex.name); int slot = spriteCollectionProxy.FindOrCreateEmptySpriteSlot(); spriteCollectionProxy.textureParams[slot].name = name; spriteCollectionProxy.textureParams[slot].colliderType = tk2dSpriteCollectionDefinition.ColliderType.UserDefined; spriteCollectionProxy.textureParams[slot].texture = (Texture2D)obj; addedIndices.Add(slot); } // And now select them searchFilter = ""; PopulateEntries(); foreach (var entry in entries) { if (entry.type == SpriteCollectionEditorEntry.Type.Sprite && addedIndices.IndexOf(entry.index) != -1) entry.selected = true; } UpdateSelection(); } // recursively find textures in path List<Object> AddTexturesInPath(string path) { List<Object> localObjects = new List<Object>(); foreach (var q in System.IO.Directory.GetFiles(path)) { string f = q.Replace('\\', '/'); System.IO.FileInfo fi = new System.IO.FileInfo(f); if (fi.Extension.ToLower() == ".meta") continue; Object obj = AssetDatabase.LoadAssetAtPath(f, typeof(Texture2D)); if (obj != null) localObjects.Add(obj); } foreach (var q in System.IO.Directory.GetDirectories(path)) { string d = q.Replace('\\', '/'); localObjects.AddRange(AddTexturesInPath(d)); } return localObjects; } int leftBarWidth { get { return tk2dPreferences.inst.spriteCollectionListWidth; } } Object[] deferredDroppedObjects; void DrawDropZone() { GUILayout.BeginVertical(tk2dEditorSkin.SC_ListBoxBG, GUILayout.Width(leftBarWidth), GUILayout.ExpandHeight(true)); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (DragAndDrop.objectReferences.Length == 0 && !SpriteCollection.Empty) GUILayout.Label("Drop sprite here", tk2dEditorSkin.SC_DropBox); else GUILayout.Label("Drop sprites here", tk2dEditorSkin.SC_DropBox); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); GUILayout.EndVertical(); Rect rect = new Rect(0, 0, leftBarWidth, Screen.height); if (rect.Contains(Event.current.mousePosition)) { switch (Event.current.type) { case EventType.DragUpdated: if (IsValidDragPayload()) DragAndDrop.visualMode = DragAndDropVisualMode.Copy; else DragAndDrop.visualMode = DragAndDropVisualMode.None; break; case EventType.DragPerform: var droppedObjectsList = new List<Object>(); for (int i = 0; i < DragAndDrop.objectReferences.Length; ++i) { var type = DragAndDrop.objectReferences[i].GetType(); if (type == typeof(Texture2D)) droppedObjectsList.Add(DragAndDrop.objectReferences[i]); else if (type == typeof(Object) && System.IO.Directory.Exists(DragAndDrop.paths[i])) droppedObjectsList.AddRange(AddTexturesInPath(DragAndDrop.paths[i])); } deferredDroppedObjects = droppedObjectsList.ToArray(); Repaint(); break; } } } bool dragging = false; bool currentDraggingValue = false; bool firstRun = true; List<UnityEngine.Object> assetsInResources = new List<UnityEngine.Object>(); bool InResources(UnityEngine.Object obj) { return AssetDatabase.GetAssetPath(obj).ToLower().IndexOf("/resources/") != -1; } void CheckForAssetsInResources() { assetsInResources.Clear(); foreach (tk2dSpriteCollectionDefinition tex in SpriteCollection.textureParams) { if (tex.texture == null) continue; if (InResources(tex.texture) && assetsInResources.IndexOf(tex.texture) == -1) assetsInResources.Add(tex.texture); } foreach (tk2dSpriteCollectionFont font in SpriteCollection.fonts) { if (font.texture != null && InResources(font.texture) && assetsInResources.IndexOf(font.texture) == -1) assetsInResources.Add(font.texture); if (font.bmFont != null && InResources(font.bmFont) && assetsInResources.IndexOf(font.bmFont) == -1) assetsInResources.Add(font.bmFont); } } Vector2 assetWarningScroll = Vector2.zero; bool HandleAssetsInResources() { if (firstRun && SpriteCollection != null) { CheckForAssetsInResources(); firstRun = false; } if (assetsInResources.Count > 0) { tk2dGuiUtility.InfoBox("Warning: The following assets are in one or more resources directories.\n" + "These files will be included in the build.", tk2dGuiUtility.WarningLevel.Warning); assetWarningScroll = GUILayout.BeginScrollView(assetWarningScroll, GUILayout.ExpandWidth(true)); foreach (UnityEngine.Object obj in assetsInResources) { EditorGUILayout.ObjectField(obj, typeof(UnityEngine.Object), false); } GUILayout.EndScrollView(); GUILayout.Space(8); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Ok", GUILayout.MinWidth(100))) { assetsInResources.Clear(); Repaint(); } GUILayout.EndHorizontal(); return true; } return false; } void OnGUI() { if (Event.current.type == EventType.DragUpdated) { if (IsValidDragPayload()) dragging = true; } else if (Event.current.type == EventType.DragExited) { dragging = false; Repaint(); } else { if (currentDraggingValue != dragging) { currentDraggingValue = dragging; } } if (Event.current.type == EventType.Layout && deferredDroppedObjects != null) { HandleDroppedPayload(deferredDroppedObjects); deferredDroppedObjects = null; } if (HandleAssetsInResources()) return; GUILayout.BeginVertical(); DrawToolbar(); GUILayout.BeginHorizontal(); if (currentDraggingValue) DrawDropZone(); else DrawSpriteList(); if (settingsView.show || (spriteCollectionProxy != null && spriteCollectionProxy.Empty)) settingsView.Draw(); else if (fontView.Draw(selectedEntries)) { } else if (spriteSheetView.Draw(selectedEntries)) { } else spriteView.Draw(selectedEntries); GUILayout.EndHorizontal(); GUILayout.EndVertical(); } }
/* * MindTouch Core - open source enterprise collaborative networking * Copyright (c) 2006-2010 MindTouch Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit www.opengarden.org; * please review the licensing section. * * 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. * http://www.gnu.org/copyleft/gpl.html */ using System; using System.Collections.Generic; using System.Data; using System.Text; using MindTouch.Data; namespace MindTouch.Deki.Data.MySql { public partial class MySqlDekiDataSession { //--- Constants --- public const string ANON_USERNAME = "Anonymous"; private static readonly IDictionary<UsersSortField, string> USERS_SORT_FIELD_MAPPING = new Dictionary<UsersSortField, string>() { { UsersSortField.DATE_CREATED, "users.user_create_timestamp" }, { UsersSortField.EMAIL, "users.user_email" }, { UsersSortField.FULLNAME, "users.user_real_name" }, { UsersSortField.ID, "users.user_id" }, { UsersSortField.DATE_LASTLOGIN, "users.user_touched" }, { UsersSortField.NICK, "users.user_name" }, { UsersSortField.ROLE, "roles.role_name" }, { UsersSortField.SERVICE, "services.service_description" }, { UsersSortField.STATUS, "users.user_active" }, { UsersSortField.USERNAME, "users.user_name" } }; //--- Methods --- public IList<UserBE> Users_GetByIds(IList<uint> userIds) { List<UserBE> users = new List<UserBE>(); if(ArrayUtil.IsNullOrEmpty(userIds)) { return users; } string userIdsText = string.Join(",", DbUtils.ConvertArrayToStringArray<uint>(userIds).ToArray()); Catalog.NewQuery( string.Format(@" /* Users_GetByIds */ SELECT * FROM users WHERE user_id IN ({0})", userIdsText)) .Execute(delegate(IDataReader dr) { while(dr.Read()) { UserBE u = Users_Populate(dr); users.Add(u); } }); return users; } public IList<UserBE> Users_GetByQuery(string usernamefilter, string realnamefilter, string usernameemailfilter, string rolefilter, bool? activatedfilter, uint? groupId, uint? serviceIdFilter, SortDirection sortDir, UsersSortField sortField, uint? offset, uint? limit, out uint totalCount, out uint queryCount) { List<UserBE> users = new List<UserBE>(); uint totalCountTemp = 0; uint queryCountTemp = 0; StringBuilder joinQuery = new StringBuilder(); string sortFieldString; USERS_SORT_FIELD_MAPPING.TryGetValue(sortField, out sortFieldString); if(!string.IsNullOrEmpty(rolefilter) || (sortFieldString ?? string.Empty).StartsWith("roles.")) { joinQuery.Append(@" left join roles on users.user_role_id = roles.role_id"); } if((sortFieldString ?? string.Empty).StartsWith("services.")) { joinQuery.AppendFormat(@" left join services on users.user_service_id = services.service_id"); } if(groupId != null) { joinQuery.AppendFormat(@" join groups on groups.group_id = {0} join user_groups on user_groups.group_id = groups.group_id", groupId.Value); } StringBuilder whereQuery = new StringBuilder(" where 1=1"); if(groupId != null) { whereQuery.AppendFormat(" AND users.user_id = user_groups.user_id"); } if(!string.IsNullOrEmpty(usernamefilter) && !string.IsNullOrEmpty(realnamefilter)) { whereQuery.AppendFormat(" AND (user_name like '{0}%' OR user_real_name like '{1}%')", DataCommand.MakeSqlSafe(usernamefilter), DataCommand.MakeSqlSafe(realnamefilter)); } else if(!string.IsNullOrEmpty(usernamefilter)) { whereQuery.AppendFormat(" AND user_name like '{0}%'", DataCommand.MakeSqlSafe(usernamefilter)); } else if(!string.IsNullOrEmpty(realnamefilter)) { whereQuery.AppendFormat(" AND user_real_name like '{0}%'", DataCommand.MakeSqlSafe(realnamefilter)); } if(!string.IsNullOrEmpty(usernameemailfilter)) { whereQuery.AppendFormat(" AND (user_name like '{0}%' OR user_email like '{0}%')", DataCommand.MakeSqlSafe(usernameemailfilter)); } if(activatedfilter != null) { whereQuery.AppendFormat(" AND user_active = {0}", activatedfilter.Value ? "1" : "0"); } if(!string.IsNullOrEmpty(rolefilter)) { whereQuery.AppendFormat(" AND role_name = '{0}'", DataCommand.MakeSqlSafe(rolefilter)); } if(serviceIdFilter != null) { whereQuery.AppendFormat(" AND user_service_id = {0}", serviceIdFilter.Value); } StringBuilder sortLimitQuery = new StringBuilder(); if(!string.IsNullOrEmpty(sortFieldString)) { sortLimitQuery.AppendFormat(" order by {0} ", sortFieldString); if(sortDir != SortDirection.UNDEFINED) { sortLimitQuery.Append(sortDir.ToString()); } } if(limit != null || offset != null) { sortLimitQuery.AppendFormat(" limit {0} offset {1}", limit ?? int.MaxValue, offset ?? 0); } string query = string.Format(@" /* Users_GetByQuery */ select * from users {0} {1} {2}; select count(*) as totalcount from users {0} {3}; select count(*) as querycount from users {0} {1};", joinQuery, whereQuery, sortLimitQuery, groupId == null ? string.Empty : "where users.user_id = user_groups.user_id"); Catalog.NewQuery(query) .Execute(delegate(IDataReader dr) { while(dr.Read()) { UserBE u = Users_Populate(dr); users.Add(u); } if(dr.NextResult() && dr.Read()) { totalCountTemp = DbUtils.Convert.To<uint>(dr["totalcount"], 0); } if(dr.NextResult() && dr.Read()) { queryCountTemp = DbUtils.Convert.To<uint>(dr["querycount"], 0); } }); totalCount = totalCountTemp; queryCount = queryCountTemp; return users; } public UserBE Users_GetByName(string userName) { if(string.IsNullOrEmpty(userName)) return null; UserBE user = null; Catalog.NewQuery(@" /* Users_GetByName */ SELECT * FROM users WHERE user_name = ?USERNAME") .With("USERNAME", userName) .Execute(delegate(IDataReader dr) { if(dr.Read()) { user = Users_Populate(dr); } }); return user; } public UserBE Users_GetByExternalName(string externalUserName, uint serviceId) { if(string.IsNullOrEmpty(externalUserName)) return null; UserBE user = null; Catalog.NewQuery(@" /* Users_GetByExternalName */ select * from users where user_external_name = ?EXTERNAL_NAME AND user_service_id = ?SERVICE_ID;") .With("EXTERNAL_NAME", externalUserName) .With("SERVICE_ID", serviceId) .Execute(delegate(IDataReader dr) { if(dr.Read()) { user = Users_Populate(dr); } }); return user; } public uint Users_Insert(UserBE newUser) { uint userId = Catalog.NewQuery(@" /* Users_Insert */ insert into users (user_role_id,user_name,user_password,user_newpassword,user_touched,user_email,user_service_id,user_active,user_real_name,user_external_name,user_create_timestamp,user_language,user_timezone) values (?ROLEID, ?USERNAME, ?USERPASSWORD, ?NEWPASSWORD, ?TOUCHED, ?EMAIL, ?SERVICEID, ?ACTIVE, ?REALNAME, ?EXTERNALNAME, ?USER_CREATE_TIMESTAMP, ?USER_LANGUAGE, ?USER_TIMEZONE); select LAST_INSERT_ID();") .With("USERPASSWORD", newUser._Password) .With("NEWPASSWORD", newUser._NewPassword) .With("ROLEID", newUser.RoleId) .With("USERNAME", newUser.Name) .With("TOUCHED", newUser._Touched) .With("EMAIL", newUser.Email) .With("SERVICEID", newUser.ServiceId) .With("ACTIVE", newUser.UserActive) .With("REALNAME", newUser.RealName) .With("EXTERNALNAME", newUser.ExternalName) .With("USER_CREATE_TIMESTAMP", newUser.CreateTimestamp) .With("USER_TIMEZONE", newUser.Timezone) .With("USER_LANGUAGE", newUser.Language) .ReadAsUInt() ?? 0; return userId; } public void Users_Update(UserBE user) { if(user == null || user.ID == 0) return; Catalog.NewQuery(@" /* Users_Update */ UPDATE users SET user_role_id = ?ROLEID, user_name = ?USERNAME, user_password = ?USERPASSWORD, user_newpassword = ?NEWPASSWORD, user_touched = ?TOUCHED, user_email = ?EMAIL, user_service_id = ?SERVICEID, user_active = ?ACTIVE, user_real_name = ?REALNAME, user_external_name = ?EXTERNALNAME, user_create_timestamp = ?USER_CREATE_TIMESTAMP, user_timezone = ?USER_TIMEZONE, user_language = ?USER_LANGUAGE WHERE user_id = ?USERID;") .With("USERPASSWORD", user._Password) .With("NEWPASSWORD", user._NewPassword) .With("ROLEID", user.RoleId) .With("USERNAME", user.Name) .With("TOUCHED", user._Touched) .With("EMAIL", user.Email) .With("SERVICEID", user.ServiceId) .With("ACTIVE", user.UserActive) .With("REALNAME", user.RealName) .With("USERID", user.ID) .With("EXTERNALNAME", user.ExternalName) .With("USER_CREATE_TIMESTAMP", user.CreateTimestamp) .With("USER_TIMEZONE", user.Timezone) .With("USER_LANGUAGE", user.Language) .Execute(); } public IList<uint> Users_UpdateServicesToLocal(uint oldServiceId) { List<uint> userIds = new List<uint>(); string query = string.Format(@"/* Users_UpdateServicesToLocal */ SELECT user_id FROM users WHERE user_service_id = ?OLDSERVICEID; UPDATE users SET user_service_id = 1, user_external_name = null where user_service_id = ?OLDSERVICEID; "); Catalog.NewQuery(query) .With("OLDSERVICEID", oldServiceId) .Execute(delegate(IDataReader dr) { while(dr.Read()) { userIds.Add((uint)dr.GetInt32(0)); } }); return userIds; } public uint Users_GetCount() { // retrieve the number of users on this wiki string query = String.Format("SELECT COUNT(*) as user_count FROM users WHERE user_active=1 AND user_name!='{0}'", ANON_USERNAME); return Catalog.NewQuery(query).ReadAsUInt() ?? 0; } private UserBE Users_Populate(IDataReader dr) { UserBE user = new UserBE(); user._NewPassword = dr.Read<byte[]>("user_newpassword"); user._Password = dr.Read<byte[]>("user_password"); user._Touched = dr.Read<string>("user_touched"); user.CreateTimestamp = dr.Read<DateTime>("user_create_timestamp"); user.Email = dr.Read<string>("user_email"); user.ExternalName = dr.Read<string>("user_external_name"); user.ID = dr.Read<uint>("user_id"); user.Language = dr.Read<string>("user_language"); user.Name = dr.Read<string>("user_name"); user.RealName = dr.Read<string>("user_real_name"); user.RoleId = dr.Read<uint>("user_role_id"); user.ServiceId = dr.Read<uint>("user_service_id"); user.Timezone = dr.Read<string>("user_timezone"); user.UserActive = dr.Read<bool>("user_active"); return user; } } }
// 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 defines an internal class used to throw exceptions in BCL code. // The main purpose is to reduce code size. // // The old way to throw an exception generates quite a lot IL code and assembly code. // Following is an example: // C# source // throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); // IL code: // IL_0003: ldstr "key" // IL_0008: ldstr "ArgumentNull_Key" // IL_000d: call string System.Environment::GetResourceString(string) // IL_0012: newobj instance void System.ArgumentNullException::.ctor(string,string) // IL_0017: throw // which is 21bytes in IL. // // So we want to get rid of the ldstr and call to Environment.GetResource in IL. // In order to do that, I created two enums: ExceptionResource, ExceptionArgument to represent the // argument name and resource name in a small integer. The source code will be changed to // ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key, ExceptionResource.ArgumentNull_Key); // // The IL code will be 7 bytes. // IL_0008: ldc.i4.4 // IL_0009: ldc.i4.4 // IL_000a: call void System.ThrowHelper::ThrowArgumentNullException(valuetype System.ExceptionArgument) // IL_000f: ldarg.0 // // This will also reduce the Jitted code size a lot. // // It is very important we do this for generic classes because we can easily generate the same code // multiple times for different instantiation. // using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Diagnostics; namespace System { [StackTraceHidden] internal static class ThrowHelper { internal static void ThrowArrayTypeMismatchException() { throw new ArrayTypeMismatchException(); } internal static void ThrowInvalidTypeWithPointersNotSupported(Type targetType) { // TODO: SR //throw new ArgumentException(SR.Format(SR.Argument_InvalidTypeWithPointersNotSupported, targetType)); throw new ArgumentException(SR.Format("Cannot use type '{0}'. Only value types without pointers or references are supported.", targetType)); } internal static void ThrowIndexOutOfRangeException() { throw new IndexOutOfRangeException(); } internal static void ThrowArgumentOutOfRangeException() { throw new ArgumentOutOfRangeException(); } internal static void ThrowArgumentException_DestinationTooShort() { // TODO: SR //throw new ArgumentException(SR.Argument_DestinationTooShort); throw new ArgumentException("Destination is too short."); } internal static void ThrowArgumentException_OverlapAlignmentMismatch() { // TODO: SR //throw new ArgumentException(SR.Argument_OverlapAlignmentMismatch); throw new ArgumentException("Overlapping spans have mismatching alignment."); } internal static void ThrowArgumentOutOfRange_IndexException() { throw GetArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index); } internal static void ThrowIndexArgumentOutOfRange_NeedNonNegNumException() { throw GetArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } internal static void ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum() { throw GetArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } internal static void ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index() { throw GetArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } internal static void ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count() { throw GetArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count); } internal static void ThrowWrongKeyTypeArgumentException<T>(T key, Type targetType) { // Generic key to move the boxing to the right hand side of throw throw GetWrongKeyTypeArgumentException((object)key, targetType); } internal static void ThrowWrongValueTypeArgumentException<T>(T value, Type targetType) { // Generic key to move the boxing to the right hand side of throw throw GetWrongValueTypeArgumentException((object)value, targetType); } private static ArgumentException GetAddingDuplicateWithKeyArgumentException(object key) { // TODO: SR //return new ArgumentException(SR.Format(SR.Argument_AddingDuplicateWithKey, key)); return new ArgumentException(SR.Format("An item with the same key has already been added. Key: {0}", key)); } internal static void ThrowAddingDuplicateWithKeyArgumentException<T>(T key) { // Generic key to move the boxing to the right hand side of throw throw GetAddingDuplicateWithKeyArgumentException((object)key); } internal static void ThrowKeyNotFoundException<T>(T key) { // Generic key to move the boxing to the right hand side of throw throw GetKeyNotFoundException((object)key); } internal static void ThrowArgumentException(ExceptionResource resource) { throw GetArgumentException(resource); } internal static void ThrowArgumentException(ExceptionResource resource, ExceptionArgument argument) { throw GetArgumentException(resource, argument); } private static ArgumentNullException GetArgumentNullException(ExceptionArgument argument) { return new ArgumentNullException(GetArgumentName(argument)); } internal static void ThrowArgumentNullException(ExceptionArgument argument) { throw GetArgumentNullException(argument); } internal static void ThrowArgumentNullException(ExceptionResource resource) { throw new ArgumentNullException(GetResourceString(resource)); } internal static void ThrowArgumentNullException(ExceptionArgument argument, ExceptionResource resource) { throw new ArgumentNullException(GetArgumentName(argument), GetResourceString(resource)); } internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) { throw new ArgumentOutOfRangeException(GetArgumentName(argument)); } internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) { throw GetArgumentOutOfRangeException(argument, resource); } internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, int paramNumber, ExceptionResource resource) { throw GetArgumentOutOfRangeException(argument, paramNumber, resource); } internal static void ThrowInvalidOperationException(ExceptionResource resource) { throw GetInvalidOperationException(resource); } internal static void ThrowInvalidOperationException_OutstandingReferences() { ThrowInvalidOperationException(ExceptionResource.Memory_OutstandingReferences); } internal static void ThrowInvalidOperationException(ExceptionResource resource, Exception e) { throw new InvalidOperationException(GetResourceString(resource), e); } internal static void ThrowSerializationException(ExceptionResource resource) { throw new SerializationException(GetResourceString(resource)); } internal static void ThrowSecurityException(ExceptionResource resource) { throw new System.Security.SecurityException(GetResourceString(resource)); } internal static void ThrowRankException(ExceptionResource resource) { throw new RankException(GetResourceString(resource)); } internal static void ThrowNotSupportedException(ExceptionResource resource) { throw new NotSupportedException(GetResourceString(resource)); } internal static void ThrowUnauthorizedAccessException(ExceptionResource resource) { throw new UnauthorizedAccessException(GetResourceString(resource)); } internal static void ThrowObjectDisposedException(string objectName, ExceptionResource resource) { throw new ObjectDisposedException(objectName, GetResourceString(resource)); } internal static void ThrowObjectDisposedException(ExceptionResource resource) { throw new ObjectDisposedException(null, GetResourceString(resource)); } internal static void ThrowObjectDisposedException_MemoryDisposed() { throw new ObjectDisposedException("OwnedMemory<T>", GetResourceString(ExceptionResource.MemoryDisposed)); } internal static void ThrowNotSupportedException() { throw new NotSupportedException(); } internal static void ThrowAggregateException(List<Exception> exceptions) { throw new AggregateException(exceptions); } internal static void ThrowOutOfMemoryException() { throw new OutOfMemoryException(); } internal static void ThrowArgumentException_Argument_InvalidArrayType() { throw GetArgumentException(ExceptionResource.Argument_InvalidArrayType); } internal static void ThrowInvalidOperationException_InvalidOperation_EnumNotStarted() { throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumNotStarted); } internal static void ThrowInvalidOperationException_InvalidOperation_EnumEnded() { throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumEnded); } internal static void ThrowInvalidOperationException_EnumCurrent(int index) { throw GetInvalidOperationException_EnumCurrent(index); } internal static void ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion() { throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } internal static void ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen() { throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen); } internal static void ThrowInvalidOperationException_InvalidOperation_NoValue() { throw GetInvalidOperationException(ExceptionResource.InvalidOperation_NoValue); } internal static void ThrowArraySegmentCtorValidationFailedExceptions(Array array, int offset, int count) { throw GetArraySegmentCtorValidationFailedException(array, offset, count); } private static Exception GetArraySegmentCtorValidationFailedException(Array array, int offset, int count) { if (array == null) return GetArgumentNullException(ExceptionArgument.array); if (offset < 0) return GetArgumentOutOfRangeException(ExceptionArgument.offset, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) return GetArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); Debug.Assert(array.Length - offset < count); return GetArgumentException(ExceptionResource.Argument_InvalidOffLen); } private static ArgumentException GetArgumentException(ExceptionResource resource) { return new ArgumentException(GetResourceString(resource)); } internal static InvalidOperationException GetInvalidOperationException(ExceptionResource resource) { return new InvalidOperationException(GetResourceString(resource)); } private static ArgumentException GetWrongKeyTypeArgumentException(object key, Type targetType) { // TODO: SR //return new ArgumentException(SR.Format(SR.Arg_WrongType, key, targetType), nameof(key)); return new ArgumentException(SR.Format("The value \"{0}\" is not of type \"{1}\" and cannot be used in this generic collection.", key, targetType), nameof(key)); } private static ArgumentException GetWrongValueTypeArgumentException(object value, Type targetType) { // TODO: SR //return new ArgumentException(SR.Format(SR.Arg_WrongType, value, targetType), nameof(value)); return new ArgumentException(SR.Format("The value \"{0}\" is not of type \"{1}\" and cannot be used in this generic collection.", value, targetType), nameof(value)); } private static KeyNotFoundException GetKeyNotFoundException(object key) { // TODO: SR //return new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); return new KeyNotFoundException(SR.Format("The given key '{0}' was not present in the dictionary.", key.ToString())); } internal static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) { return new ArgumentOutOfRangeException(GetArgumentName(argument), GetResourceString(resource)); } private static ArgumentException GetArgumentException(ExceptionResource resource, ExceptionArgument argument) { return new ArgumentException(GetResourceString(resource), GetArgumentName(argument)); } private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, int paramNumber, ExceptionResource resource) { return new ArgumentOutOfRangeException(GetArgumentName(argument) + "[" + paramNumber.ToString() + "]", GetResourceString(resource)); } private static InvalidOperationException GetInvalidOperationException_EnumCurrent(int index) { return GetInvalidOperationException( index < 0 ? ExceptionResource.InvalidOperation_EnumNotStarted : ExceptionResource.InvalidOperation_EnumEnded); } // Allow nulls for reference types and Nullable<U>, but not for value types. // Aggressively inline so the jit evaluates the if in place and either drops the call altogether // Or just leaves null test and call to the Non-returning ThrowHelper.ThrowArgumentNullException [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void IfNullAndNullsAreIllegalThenThrow<T>(object value, ExceptionArgument argName) { // Note that default(T) is not equal to null for value types except when T is Nullable<U>. if (!(default(T) == null) && value == null) ThrowHelper.ThrowArgumentNullException(argName); } // This function will convert an ExceptionArgument enum value to the argument name string. [MethodImpl(MethodImplOptions.NoInlining)] private static string GetArgumentName(ExceptionArgument argument) { Debug.Assert(Enum.IsDefined(typeof(ExceptionArgument), argument), "The enum value is not defined, please check the ExceptionArgument Enum."); return argument.ToString(); } // This function will convert an ExceptionResource enum value to the resource string. [MethodImpl(MethodImplOptions.NoInlining)] private static string GetResourceString(ExceptionResource resource) { Debug.Assert(Enum.IsDefined(typeof(ExceptionResource), resource), "The enum value is not defined, please check the ExceptionResource Enum."); return SR.GetResourceString(resource.ToString()); } internal static void ThrowNotSupportedExceptionIfNonNumericType<T>() { if (typeof(T) != typeof(Byte) && typeof(T) != typeof(SByte) && typeof(T) != typeof(Int16) && typeof(T) != typeof(UInt16) && typeof(T) != typeof(Int32) && typeof(T) != typeof(UInt32) && typeof(T) != typeof(Int64) && typeof(T) != typeof(UInt64) && typeof(T) != typeof(Single) && typeof(T) != typeof(Double)) { // TODO: SR //throw new NotSupportedException(SR.Arg_TypeNotSupported); throw new NotSupportedException("Specified type is not supported"); } } } // // The convention for this enum is using the argument name as the enum name // internal enum ExceptionArgument { obj, dictionary, array, info, key, collection, list, match, converter, capacity, index, startIndex, value, count, arrayIndex, name, item, options, view, sourceBytesToCopy, action, comparison, offset, newSize, elementType, length, length1, length2, length3, lengths, len, lowerBounds, sourceArray, destinationArray, sourceIndex, destinationIndex, indices, index1, index2, index3, other, comparer, endIndex, keys, creationOptions, timeout, tasks, scheduler, continuationFunction, millisecondsTimeout, millisecondsDelay, function, exceptions, exception, cancellationToken, delay, asyncResult, endMethod, endFunction, beginMethod, continuationOptions, continuationAction, concurrencyLevel, text, callBack, type, stateMachine, pHandle, values, task, s, keyValuePair, input, ownedMemory, pointer, start, format, culture, comparable, source, state } // // The convention for this enum is using the resource name as the enum name // internal enum ExceptionResource { Argument_ImplementIComparable, Argument_InvalidType, Argument_InvalidArgumentForComparison, Argument_InvalidRegistryKeyPermissionCheck, ArgumentOutOfRange_NeedNonNegNum, Arg_ArrayPlusOffTooSmall, Arg_NonZeroLowerBound, Arg_RankMultiDimNotSupported, Arg_RegKeyDelHive, Arg_RegKeyStrLenBug, Arg_RegSetStrArrNull, Arg_RegSetMismatchedKind, Arg_RegSubKeyAbsent, Arg_RegSubKeyValueAbsent, Argument_AddingDuplicate, Serialization_InvalidOnDeser, Serialization_MissingKeys, Serialization_NullKey, Argument_InvalidArrayType, NotSupported_KeyCollectionSet, NotSupported_ValueCollectionSet, ArgumentOutOfRange_SmallCapacity, ArgumentOutOfRange_Index, Argument_InvalidOffLen, Argument_ItemNotExist, ArgumentOutOfRange_Count, ArgumentOutOfRange_InvalidThreshold, ArgumentOutOfRange_ListInsert, NotSupported_ReadOnlyCollection, InvalidOperation_CannotRemoveFromStackOrQueue, InvalidOperation_EmptyQueue, InvalidOperation_EnumOpCantHappen, InvalidOperation_EnumFailedVersion, InvalidOperation_EmptyStack, ArgumentOutOfRange_BiggerThanCollection, InvalidOperation_EnumNotStarted, InvalidOperation_EnumEnded, NotSupported_SortedListNestedWrite, InvalidOperation_NoValue, InvalidOperation_RegRemoveSubKey, Security_RegistryPermission, UnauthorizedAccess_RegistryNoWrite, ObjectDisposed_RegKeyClosed, NotSupported_InComparableType, Argument_InvalidRegistryOptionsCheck, Argument_InvalidRegistryViewCheck, InvalidOperation_NullArray, Arg_MustBeType, Arg_NeedAtLeast1Rank, ArgumentOutOfRange_HugeArrayNotSupported, Arg_RanksAndBounds, Arg_RankIndices, Arg_Need1DArray, Arg_Need2DArray, Arg_Need3DArray, NotSupported_FixedSizeCollection, ArgumentException_OtherNotArrayOfCorrectLength, Rank_MultiDimNotSupported, InvalidOperation_IComparerFailed, ArgumentOutOfRange_EndIndexStartIndex, Arg_LowerBoundsMustMatch, Arg_BogusIComparer, Task_WaitMulti_NullTask, Task_ThrowIfDisposed, Task_Start_TaskCompleted, Task_Start_Promise, Task_Start_ContinuationTask, Task_Start_AlreadyStarted, Task_RunSynchronously_TaskCompleted, Task_RunSynchronously_Continuation, Task_RunSynchronously_Promise, Task_RunSynchronously_AlreadyStarted, Task_MultiTaskContinuation_NullTask, Task_MultiTaskContinuation_EmptyTaskList, Task_Dispose_NotCompleted, Task_Delay_InvalidMillisecondsDelay, Task_Delay_InvalidDelay, Task_ctor_LRandSR, Task_ContinueWith_NotOnAnything, Task_ContinueWith_ESandLR, TaskT_TransitionToFinal_AlreadyCompleted, TaskCompletionSourceT_TrySetException_NullException, TaskCompletionSourceT_TrySetException_NoExceptions, MemoryDisposed, Memory_OutstandingReferences, InvalidOperation_WrongAsyncResultOrEndCalledMultiple, ConcurrentDictionary_ConcurrencyLevelMustBePositive, ConcurrentDictionary_CapacityMustNotBeNegative, ConcurrentDictionary_TypeOfValueIncorrect, ConcurrentDictionary_TypeOfKeyIncorrect, ConcurrentDictionary_KeyAlreadyExisted, ConcurrentDictionary_ItemKeyIsNull, ConcurrentDictionary_IndexIsNegative, ConcurrentDictionary_ArrayNotLargeEnough, ConcurrentDictionary_ArrayIncorrectType, ConcurrentCollection_SyncRoot_NotSupported, ArgumentOutOfRange_Enum, InvalidOperation_HandleIsNotInitialized, AsyncMethodBuilder_InstanceNotInitialized, ArgumentNull_SafeHandle, } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Build.Construction; using Microsoft.DotNet.Tools.Test.Utilities; using System.Linq; using Xunit; using FluentAssertions; using Microsoft.DotNet.ProjectJsonMigration; using Microsoft.DotNet.ProjectJsonMigration.Rules; using System; namespace Microsoft.DotNet.ProjectJsonMigration.Tests { public class GivenThatIWantToMigratePackageDependencies : PackageDependenciesTestBase { [Fact] public void ItMigratesBasicPackageReference() { var mockProj = RunPackageDependenciesRuleOnPj(@" { ""dependencies"": { ""APackage"" : ""1.0.0-preview"", ""BPackage"" : ""1.0.0"" } }"); EmitsPackageReferences(mockProj, Tuple.Create("APackage", "1.0.0-preview", ""), Tuple.Create("BPackage", "1.0.0", "")); } [Fact] public void ItMigratesTypeBuildToPrivateAssets() { var mockProj = RunPackageDependenciesRuleOnPj(@" { ""dependencies"": { ""APackage"" : { ""version"": ""1.0.0-preview"", ""type"": ""build"" } } }"); var packageRef = mockProj.Items.First(i => i.Include == "APackage" && i.ItemType == "PackageReference"); var privateAssetsMetadata = packageRef.GetMetadataWithName("PrivateAssets"); privateAssetsMetadata.Value.Should().NotBeNull(); privateAssetsMetadata.Value.Should().Be("All"); } [Fact] public void ItMigratesSuppressParentArrayToPrivateAssets() { var mockProj = RunPackageDependenciesRuleOnPj(@" { ""dependencies"": { ""APackage"" : { ""version"": ""1.0.0-preview"", ""suppressParent"":[ ""runtime"", ""native"" ] } } }"); var packageRef = mockProj.Items.First(i => i.Include == "APackage" && i.ItemType == "PackageReference"); var privateAssetsMetadata = packageRef.GetMetadataWithName("PrivateAssets"); privateAssetsMetadata.Value.Should().NotBeNull(); privateAssetsMetadata.Value.Should().Be("Native;Runtime"); } [Fact] public void ItMigratesSuppressParentStringToPrivateAssets() { var mockProj = RunPackageDependenciesRuleOnPj(@" { ""dependencies"": { ""APackage"" : { ""version"": ""1.0.0-preview"", ""suppressParent"":""runtime"" } } }"); var packageRef = mockProj.Items.First(i => i.Include == "APackage" && i.ItemType == "PackageReference"); var privateAssetsMetadata = packageRef.GetMetadataWithName("PrivateAssets"); privateAssetsMetadata.Value.Should().NotBeNull(); privateAssetsMetadata.Value.Should().Be("Runtime"); } [Fact] public void ItMigratesIncludeExcludeArraysToIncludeAssets() { var mockProj = RunPackageDependenciesRuleOnPj(@" { ""dependencies"": { ""APackage"" : { ""version"": ""1.0.0-preview"", ""include"": [ ""compile"", ""runtime"", ""native"" ], ""exclude"": [ ""native"" ] } } }"); var packageRef = mockProj.Items.First(i => i.Include == "APackage" && i.ItemType == "PackageReference"); var includeAssetsMetadata = packageRef.GetMetadataWithName("IncludeAssets"); includeAssetsMetadata.Value.Should().NotBeNull(); includeAssetsMetadata.Value.Should().Be("Compile;Runtime"); } [Fact] public void ItMigratesIncludeStringToIncludeAssets() { var mockProj = RunPackageDependenciesRuleOnPj(@" { ""dependencies"": { ""APackage"" : { ""version"": ""1.0.0-preview"", ""include"": ""compile"", ""exclude"": ""runtime"" } } }"); var packageRef = mockProj.Items.First(i => i.Include == "APackage" && i.ItemType == "PackageReference"); var includeAssetsMetadata = packageRef.GetMetadataWithName("IncludeAssets"); includeAssetsMetadata.Value.Should().NotBeNull(); includeAssetsMetadata.Value.Should().Be("Compile"); } [Fact] public void ItMigratesIncludeExcludeOverlappingStringsToIncludeAssets() { var mockProj = RunPackageDependenciesRuleOnPj(@" { ""dependencies"": { ""APackage"" : { ""version"": ""1.0.0-preview"", ""include"": ""compile"", ""exclude"": ""compile"", } } }"); var packageRef = mockProj.Items.First(i => i.Include == "APackage" && i.ItemType == "PackageReference"); var includeAssetsMetadata = packageRef.GetMetadataWithName("IncludeAssets"); includeAssetsMetadata.Value.Should().NotBeNull(); includeAssetsMetadata.Value.Should().Be("None"); } [Fact] public void ItMigratesTools() { var mockProj = RunPackageDependenciesRuleOnPj(@" { ""tools"": { ""APackage"" : ""1.0.0-preview"", ""BPackage"" : ""1.0.0"" } }"); EmitsToolReferences(mockProj, Tuple.Create("APackage", "1.0.0-preview"), Tuple.Create("BPackage", "1.0.0")); } [Fact] public void ItMigratesImportsPerFramework() { var importPropertyName = "PackageTargetFallback"; var mockProj = RunPackageDependenciesRuleOnPj(@" { ""frameworks"": { ""netcoreapp1.0"" : { ""imports"": [""netstandard1.3"", ""net451""] }, ""netstandard1.3"" : { ""imports"": [""net451""] }, ""net451"" : { ""imports"": ""netstandard1.3"" } } }"); var imports = mockProj.Properties.Where(p => p.Name == importPropertyName); imports.Should().HaveCount(3); var netcoreappImport = imports.First(p => p.Condition.Contains("netcoreapp1.0")); var netstandardImport = imports.First(p => p.Condition.Contains("netstandard1.3")); var net451Import = imports.First(p => p.Condition.Contains("net451")); netcoreappImport.Should().NotBe(netstandardImport); netcoreappImport.Condition.Should().Be(" '$(TargetFramework)' == 'netcoreapp1.0' "); netstandardImport.Condition.Should().Be(" '$(TargetFramework)' == 'netstandard1.3' "); net451Import.Condition.Should().Be(" '$(TargetFramework)' == 'net451' "); netcoreappImport.Value.Split(';').Should().BeEquivalentTo($"$({importPropertyName})", "netstandard1.3", "net451"); netstandardImport.Value.Split(';').Should().BeEquivalentTo($"$({importPropertyName})", "net451"); net451Import.Value.Split(';').Should().BeEquivalentTo($"$({importPropertyName})", "netstandard1.3"); } [Fact] public void ItDoesNotAddConditionToPackageTargetFallBackWhenMigratingASingleTFM() { var importPropertyName = "PackageTargetFallback"; var mockProj = RunPackageDependenciesRuleOnPj(@" { ""frameworks"": { ""netcoreapp1.0"" : { ""imports"": [""netstandard1.3"", ""net451""] } } }"); var imports = mockProj.Properties.Where(p => p.Name == importPropertyName); imports.Should().HaveCount(1); imports.Single().Condition.Should().BeEmpty(); } [Fact] public void ItAutoAddDesktopReferencesDuringMigrate() { var mockProj = RunPackageDependenciesRuleOnPj(@" { ""frameworks"": { ""net35"" : {}, ""net4"" : {}, ""net451"" : {} } }"); var itemGroup = mockProj.ItemGroups.Where(i => i.Condition == " '$(TargetFramework)' == 'net451' "); itemGroup.Should().HaveCount(1); itemGroup.First().Items.Should().HaveCount(2); var items = itemGroup.First().Items.ToArray(); items[0].Include.Should().Be("System"); items[1].Include.Should().Be("Microsoft.CSharp"); itemGroup = mockProj.ItemGroups.Where(i => i.Condition == " '$(TargetFramework)' == 'net40' "); itemGroup.Should().HaveCount(1); itemGroup.First().Items.Should().HaveCount(2); items = itemGroup.First().Items.ToArray(); items[0].Include.Should().Be("System"); items[1].Include.Should().Be("Microsoft.CSharp"); itemGroup = mockProj.ItemGroups.Where(i => i.Condition == " '$(TargetFramework)' == 'net35' "); itemGroup.Should().HaveCount(1); itemGroup.First().Items.Should().HaveCount(1); items = itemGroup.First().Items.ToArray(); items[0].Include.Should().Be("System"); } [Fact] public void ItMigratesTestProjectsToHaveTestSdk() { var mockProj = RunPackageDependenciesRuleOnPj(@" { ""buildOptions"": { ""emitEntryPoint"": true }, ""frameworks"": { ""netcoreapp1.0"": {} }, ""testRunner"": ""somerunner"" }"); mockProj.Items.Should().ContainSingle( i => (i.Include == "Microsoft.NET.Test.Sdk" && i.ItemType == "PackageReference" && i.GetMetadataWithName("Version").Value == "15.0.0-preview-20170106-08" && i.GetMetadataWithName("Version").ExpressedAsAttribute)); mockProj.Items.Should().NotContain( i => (i.Include == "xunit" && i.ItemType == "PackageReference")); mockProj.Items.Should().NotContain( i => (i.Include == "xunit.runner.visualstudio" && i.ItemType == "PackageReference")); mockProj.Items.Should().NotContain( i => (i.Include == "MSTest.TestAdapter" && i.ItemType == "PackageReference")); mockProj.Items.Should().NotContain( i => (i.Include == "MSTest.TestFramework" && i.ItemType == "PackageReference")); } [Fact] public void ItMigratesTestProjectsToHaveTestSdkAndXunitPackagedependencies() { var mockProj = RunPackageDependenciesRuleOnPj(@" { ""buildOptions"": { ""emitEntryPoint"": true }, ""frameworks"": { ""netcoreapp1.0"": {} }, ""testRunner"": ""xunit"" }"); mockProj.Items.Should().ContainSingle( i => (i.Include == "Microsoft.NET.Test.Sdk" && i.ItemType == "PackageReference" && i.GetMetadataWithName("Version").Value == "15.0.0-preview-20170106-08") && i.GetMetadataWithName("Version").ExpressedAsAttribute); mockProj.Items.Should().ContainSingle( i => (i.Include == "xunit" && i.ItemType == "PackageReference" && i.GetMetadataWithName("Version").Value == "2.2.0-beta5-build3474" && i.GetMetadataWithName("Version").ExpressedAsAttribute)); mockProj.Items.Should().ContainSingle( i => (i.Include == "xunit.runner.visualstudio" && i.ItemType == "PackageReference" && i.GetMetadataWithName("Version").Value == "2.2.0-beta5-build1225" && i.GetMetadataWithName("Version").ExpressedAsAttribute)); mockProj.Items.Should().NotContain( i => (i.Include == "MSTest.TestAdapter" && i.ItemType == "PackageReference")); mockProj.Items.Should().NotContain( i => (i.Include == "MSTest.TestFramework" && i.ItemType == "PackageReference")); } [Fact] public void ItMigratesTestProjectsToHaveTestSdkAndXunitPackagedependenciesOverwriteExistingPackagedependencies() { var mockProj = RunPackageDependenciesRuleOnPj(@" { ""buildOptions"": { ""emitEntryPoint"": true }, ""dependencies"": { ""xunit"": ""2.2.0-beta3-build3330"" }, ""frameworks"": { ""netcoreapp1.0"": {} }, ""testRunner"": ""xunit"" }"); mockProj.Items.Should().ContainSingle( i => (i.Include == "Microsoft.NET.Test.Sdk" && i.ItemType == "PackageReference" && i.GetMetadataWithName("Version").Value == "15.0.0-preview-20170106-08" && i.GetMetadataWithName("Version").ExpressedAsAttribute)); mockProj.Items.Should().ContainSingle( i => (i.Include == "xunit" && i.ItemType == "PackageReference" && i.GetMetadataWithName("Version").Value == "2.2.0-beta5-build3474" && i.GetMetadataWithName("Version").ExpressedAsAttribute)); mockProj.Items.Should().ContainSingle( i => (i.Include == "xunit.runner.visualstudio" && i.ItemType == "PackageReference" && i.GetMetadataWithName("Version").Value == "2.2.0-beta5-build1225" && i.GetMetadataWithName("Version").ExpressedAsAttribute)); mockProj.Items.Should().NotContain( i => (i.Include == "MSTest.TestAdapter" && i.ItemType == "PackageReference")); mockProj.Items.Should().NotContain( i => (i.Include == "MSTest.TestFramework" && i.ItemType == "PackageReference")); } [Fact] public void ItMigratesTestProjectsToHaveTestSdkAndMstestPackagedependencies() { var mockProj = RunPackageDependenciesRuleOnPj(@" { ""buildOptions"": { ""emitEntryPoint"": true }, ""frameworks"": { ""netcoreapp1.0"": {} }, ""testRunner"": ""mstest"" }"); mockProj.Items.Should().ContainSingle( i => (i.Include == "Microsoft.NET.Test.Sdk" && i.ItemType == "PackageReference" && i.GetMetadataWithName("Version").Value == "15.0.0-preview-20170106-08" && i.GetMetadataWithName("Version").ExpressedAsAttribute)); mockProj.Items.Should().ContainSingle( i => (i.Include == "MSTest.TestAdapter" && i.ItemType == "PackageReference" && i.GetMetadataWithName("Version").Value == "1.1.8-rc" && i.GetMetadataWithName("Version").ExpressedAsAttribute)); mockProj.Items.Should().ContainSingle( i => (i.Include == "MSTest.TestFramework" && i.ItemType == "PackageReference" && i.GetMetadataWithName("Version").Value == "1.0.8-rc" && i.GetMetadataWithName("Version").ExpressedAsAttribute)); mockProj.Items.Should().NotContain( i => (i.Include == "xunit" && i.ItemType == "PackageReference")); mockProj.Items.Should().NotContain( i => (i.Include == "xunit.runner.visualstudio" && i.ItemType == "PackageReference")); } [Theory] [InlineData(@" { ""frameworks"": { ""netstandard1.3"": { ""dependencies"": { ""System.AppContext"": ""4.1.0"", ""NETStandard.Library"": ""1.5.0"" } } } }")] [InlineData(@" { ""frameworks"": { ""netstandard1.3"": { ""dependencies"": { ""System.AppContext"": ""4.1.0"" } } } }")] public void ItMigratesLibraryAndDoesNotDoubleNetstandardRef(string pjContent) { var mockProj = RunPackageDependenciesRuleOnPj(pjContent); mockProj.Items.Should().ContainSingle( i => (i.Include == "NETStandard.Library" && i.ItemType == "PackageReference")); } new private void EmitsPackageReferences(ProjectRootElement mockProj, params Tuple<string, string, string>[] packageSpecs) { foreach (var packageSpec in packageSpecs) { var packageName = packageSpec.Item1; var packageVersion = packageSpec.Item2; var packageTFM = packageSpec.Item3; var items = mockProj.Items .Where(i => i.ItemType == "PackageReference") .Where(i => string.IsNullOrEmpty(packageTFM) || i.ConditionChain().Any(c => c.Contains(packageTFM))) .Where(i => i.Include == packageName) .Where(i => i.GetMetadataWithName("Version").Value == packageVersion && i.GetMetadataWithName("Version").ExpressedAsAttribute); items.Should().HaveCount(1); } } new private void EmitsToolReferences(ProjectRootElement mockProj, params Tuple<string, string>[] toolSpecs) { foreach (var toolSpec in toolSpecs) { var packageName = toolSpec.Item1; var packageVersion = toolSpec.Item2; var items = mockProj.Items .Where(i => i.ItemType == "DotNetCliToolReference") .Where(i => i.Include == packageName) .Where(i => i.GetMetadataWithName("Version").Value == packageVersion && i.GetMetadataWithName("Version").ExpressedAsAttribute); items.Should().HaveCount(1); } } new private ProjectRootElement RunPackageDependenciesRuleOnPj(string s, string testDirectory = null) { testDirectory = testDirectory ?? Temp.CreateDirectory().Path; return TemporaryProjectFileRuleRunner.RunRules(new IMigrationRule[] { new MigratePackageDependenciesAndToolsRule() }, s, testDirectory); } } }
// Copyright 2017, Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.ErrorReporting.V1Beta1 { /// <summary> /// Settings for a <see cref="ErrorGroupServiceClient"/>. /// </summary> public sealed partial class ErrorGroupServiceSettings : ServiceSettingsBase { /// <summary> /// Get a new instance of the default <see cref="ErrorGroupServiceSettings"/>. /// </summary> /// <returns> /// A new instance of the default <see cref="ErrorGroupServiceSettings"/>. /// </returns> public static ErrorGroupServiceSettings GetDefault() => new ErrorGroupServiceSettings(); /// <summary> /// Constructs a new <see cref="ErrorGroupServiceSettings"/> object with default settings. /// </summary> public ErrorGroupServiceSettings() { } private ErrorGroupServiceSettings(ErrorGroupServiceSettings existing) : base(existing) { GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetGroupSettings = existing.GetGroupSettings; UpdateGroupSettings = existing.UpdateGroupSettings; OnCopy(existing); } partial void OnCopy(ErrorGroupServiceSettings existing); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "Idempotent" <see cref="ErrorGroupServiceClient"/> RPC methods. /// </summary> /// <remarks> /// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are: /// <list type="bullet"> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// </remarks> public static Predicate<RpcException> IdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "NonIdempotent" <see cref="ErrorGroupServiceClient"/> RPC methods. /// </summary> /// <remarks> /// The eligible RPC <see cref="StatusCode"/>s for retry for "NonIdempotent" RPC methods are: /// <list type="bullet"> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// </remarks> public static Predicate<RpcException> NonIdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(StatusCode.Unavailable); /// <summary> /// "Default" retry backoff for <see cref="ErrorGroupServiceClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" retry backoff for <see cref="ErrorGroupServiceClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" retry backoff for <see cref="ErrorGroupServiceClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial delay: 100 milliseconds</description></item> /// <item><description>Maximum delay: 60000 milliseconds</description></item> /// <item><description>Delay multiplier: 1.3</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(100), maxDelay: TimeSpan.FromMilliseconds(60000), delayMultiplier: 1.3 ); /// <summary> /// "Default" timeout backoff for <see cref="ErrorGroupServiceClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" timeout backoff for <see cref="ErrorGroupServiceClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" timeout backoff for <see cref="ErrorGroupServiceClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Maximum timeout: 20000 milliseconds</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(20000), maxDelay: TimeSpan.FromMilliseconds(20000), delayMultiplier: 1.0 ); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>ErrorGroupServiceClient.GetGroup</c> and <c>ErrorGroupServiceClient.GetGroupAsync</c>. /// </summary> /// <remarks> /// The default <c>ErrorGroupServiceClient.GetGroup</c> and /// <c>ErrorGroupServiceClient.GetGroupAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 20000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings GetGroupSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>ErrorGroupServiceClient.UpdateGroup</c> and <c>ErrorGroupServiceClient.UpdateGroupAsync</c>. /// </summary> /// <remarks> /// The default <c>ErrorGroupServiceClient.UpdateGroup</c> and /// <c>ErrorGroupServiceClient.UpdateGroupAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 20000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings UpdateGroupSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// Creates a deep clone of this object, with all the same property values. /// </summary> /// <returns>A deep clone of this <see cref="ErrorGroupServiceSettings"/> object.</returns> public ErrorGroupServiceSettings Clone() => new ErrorGroupServiceSettings(this); } /// <summary> /// ErrorGroupService client wrapper, for convenient use. /// </summary> public abstract partial class ErrorGroupServiceClient { /// <summary> /// The default endpoint for the ErrorGroupService service, which is a host of "clouderrorreporting.googleapis.com" and a port of 443. /// </summary> public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("clouderrorreporting.googleapis.com", 443); /// <summary> /// The default ErrorGroupService scopes. /// </summary> /// <remarks> /// The default ErrorGroupService scopes are: /// <list type="bullet"> /// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item> /// </list> /// </remarks> public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes); // Note: we could have parameterless overloads of Create and CreateAsync, // documented to just use the default endpoint, settings and credentials. // Pros: // - Might be more reassuring on first use // - Allows method group conversions // Con: overloads! /// <summary> /// Asynchronously creates a <see cref="ErrorGroupServiceClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="ErrorGroupServiceSettings"/>.</param> /// <returns>The task representing the created <see cref="ErrorGroupServiceClient"/>.</returns> public static async Task<ErrorGroupServiceClient> CreateAsync(ServiceEndpoint endpoint = null, ErrorGroupServiceSettings settings = null) { Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false); return Create(channel, settings); } /// <summary> /// Synchronously creates a <see cref="ErrorGroupServiceClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="ErrorGroupServiceSettings"/>.</param> /// <returns>The created <see cref="ErrorGroupServiceClient"/>.</returns> public static ErrorGroupServiceClient Create(ServiceEndpoint endpoint = null, ErrorGroupServiceSettings settings = null) { Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint); return Create(channel, settings); } /// <summary> /// Creates a <see cref="ErrorGroupServiceClient"/> which uses the specified channel for remote operations. /// </summary> /// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param> /// <param name="settings">Optional <see cref="ErrorGroupServiceSettings"/>.</param> /// <returns>The created <see cref="ErrorGroupServiceClient"/>.</returns> public static ErrorGroupServiceClient Create(Channel channel, ErrorGroupServiceSettings settings = null) { GaxPreconditions.CheckNotNull(channel, nameof(channel)); ErrorGroupService.ErrorGroupServiceClient grpcClient = new ErrorGroupService.ErrorGroupServiceClient(channel); return new ErrorGroupServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, ErrorGroupServiceSettings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, ErrorGroupServiceSettings)"/>. Channels which weren't automatically /// created are not affected. /// </summary> /// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, ErrorGroupServiceSettings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, ErrorGroupServiceSettings)"/> 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 Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync(); /// <summary> /// The underlying gRPC ErrorGroupService client. /// </summary> public virtual ErrorGroupService.ErrorGroupServiceClient GrpcClient { get { throw new NotImplementedException(); } } /// <summary> /// Get the specified group. /// </summary> /// <param name="groupName"> /// [Required] The group resource name. Written as /// &lt;code&gt;projects/&lt;var&gt;projectID&lt;/var&gt;/groups/&lt;var&gt;group_name&lt;/var&gt;&lt;/code&gt;. /// Call /// &lt;a href="/error-reporting/reference/rest/v1beta1/projects.groupStats/list"&gt; /// &lt;code&gt;groupStats.list&lt;/code&gt;&lt;/a&gt; to return a list of groups belonging to /// this project. /// /// Example: &lt;code&gt;projects/my-project-123/groups/my-group&lt;/code&gt; /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<ErrorGroup> GetGroupAsync( GroupName groupName, CallSettings callSettings = null) => GetGroupAsync( new GetGroupRequest { GroupNameAsGroupName = GaxPreconditions.CheckNotNull(groupName, nameof(groupName)), }, callSettings); /// <summary> /// Get the specified group. /// </summary> /// <param name="groupName"> /// [Required] The group resource name. Written as /// &lt;code&gt;projects/&lt;var&gt;projectID&lt;/var&gt;/groups/&lt;var&gt;group_name&lt;/var&gt;&lt;/code&gt;. /// Call /// &lt;a href="/error-reporting/reference/rest/v1beta1/projects.groupStats/list"&gt; /// &lt;code&gt;groupStats.list&lt;/code&gt;&lt;/a&gt; to return a list of groups belonging to /// this project. /// /// Example: &lt;code&gt;projects/my-project-123/groups/my-group&lt;/code&gt; /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<ErrorGroup> GetGroupAsync( GroupName groupName, CancellationToken cancellationToken) => GetGroupAsync( groupName, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Get the specified group. /// </summary> /// <param name="groupName"> /// [Required] The group resource name. Written as /// &lt;code&gt;projects/&lt;var&gt;projectID&lt;/var&gt;/groups/&lt;var&gt;group_name&lt;/var&gt;&lt;/code&gt;. /// Call /// &lt;a href="/error-reporting/reference/rest/v1beta1/projects.groupStats/list"&gt; /// &lt;code&gt;groupStats.list&lt;/code&gt;&lt;/a&gt; to return a list of groups belonging to /// this project. /// /// Example: &lt;code&gt;projects/my-project-123/groups/my-group&lt;/code&gt; /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual ErrorGroup GetGroup( GroupName groupName, CallSettings callSettings = null) => GetGroup( new GetGroupRequest { GroupNameAsGroupName = GaxPreconditions.CheckNotNull(groupName, nameof(groupName)), }, callSettings); /// <summary> /// Get the specified group. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<ErrorGroup> GetGroupAsync( GetGroupRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Get the specified group. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual ErrorGroup GetGroup( GetGroupRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Replace the data for the specified group. /// Fails if the group does not exist. /// </summary> /// <param name="group"> /// [Required] The group which replaces the resource on the server. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<ErrorGroup> UpdateGroupAsync( ErrorGroup group, CallSettings callSettings = null) => UpdateGroupAsync( new UpdateGroupRequest { Group = GaxPreconditions.CheckNotNull(group, nameof(group)), }, callSettings); /// <summary> /// Replace the data for the specified group. /// Fails if the group does not exist. /// </summary> /// <param name="group"> /// [Required] The group which replaces the resource on the server. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<ErrorGroup> UpdateGroupAsync( ErrorGroup group, CancellationToken cancellationToken) => UpdateGroupAsync( group, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Replace the data for the specified group. /// Fails if the group does not exist. /// </summary> /// <param name="group"> /// [Required] The group which replaces the resource on the server. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual ErrorGroup UpdateGroup( ErrorGroup group, CallSettings callSettings = null) => UpdateGroup( new UpdateGroupRequest { Group = GaxPreconditions.CheckNotNull(group, nameof(group)), }, callSettings); /// <summary> /// Replace the data for the specified group. /// Fails if the group does not exist. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<ErrorGroup> UpdateGroupAsync( UpdateGroupRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Replace the data for the specified group. /// Fails if the group does not exist. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual ErrorGroup UpdateGroup( UpdateGroupRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } } /// <summary> /// ErrorGroupService client wrapper implementation, for convenient use. /// </summary> public sealed partial class ErrorGroupServiceClientImpl : ErrorGroupServiceClient { private readonly ApiCall<GetGroupRequest, ErrorGroup> _callGetGroup; private readonly ApiCall<UpdateGroupRequest, ErrorGroup> _callUpdateGroup; /// <summary> /// Constructs a client wrapper for the ErrorGroupService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="ErrorGroupServiceSettings"/> used within this client </param> public ErrorGroupServiceClientImpl(ErrorGroupService.ErrorGroupServiceClient grpcClient, ErrorGroupServiceSettings settings) { this.GrpcClient = grpcClient; ErrorGroupServiceSettings effectiveSettings = settings ?? ErrorGroupServiceSettings.GetDefault(); ClientHelper clientHelper = new ClientHelper(effectiveSettings); _callGetGroup = clientHelper.BuildApiCall<GetGroupRequest, ErrorGroup>( GrpcClient.GetGroupAsync, GrpcClient.GetGroup, effectiveSettings.GetGroupSettings); _callUpdateGroup = clientHelper.BuildApiCall<UpdateGroupRequest, ErrorGroup>( GrpcClient.UpdateGroupAsync, GrpcClient.UpdateGroup, effectiveSettings.UpdateGroupSettings); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void OnConstruction(ErrorGroupService.ErrorGroupServiceClient grpcClient, ErrorGroupServiceSettings effectiveSettings, ClientHelper clientHelper); /// <summary> /// The underlying gRPC ErrorGroupService client. /// </summary> public override ErrorGroupService.ErrorGroupServiceClient GrpcClient { get; } // Partial modifier methods contain '_' to ensure no name conflicts with RPC methods. partial void Modify_GetGroupRequest(ref GetGroupRequest request, ref CallSettings settings); partial void Modify_UpdateGroupRequest(ref UpdateGroupRequest request, ref CallSettings settings); /// <summary> /// Get the specified group. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<ErrorGroup> GetGroupAsync( GetGroupRequest request, CallSettings callSettings = null) { Modify_GetGroupRequest(ref request, ref callSettings); return _callGetGroup.Async(request, callSettings); } /// <summary> /// Get the specified group. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override ErrorGroup GetGroup( GetGroupRequest request, CallSettings callSettings = null) { Modify_GetGroupRequest(ref request, ref callSettings); return _callGetGroup.Sync(request, callSettings); } /// <summary> /// Replace the data for the specified group. /// Fails if the group does not exist. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<ErrorGroup> UpdateGroupAsync( UpdateGroupRequest request, CallSettings callSettings = null) { Modify_UpdateGroupRequest(ref request, ref callSettings); return _callUpdateGroup.Async(request, callSettings); } /// <summary> /// Replace the data for the specified group. /// Fails if the group does not exist. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override ErrorGroup UpdateGroup( UpdateGroupRequest request, CallSettings callSettings = null) { Modify_UpdateGroupRequest(ref request, ref callSettings); return _callUpdateGroup.Sync(request, callSettings); } } // Partial classes to enable page-streaming }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; namespace XenAPI { /// <summary> /// The metrics reported by the guest (as opposed to inferred from outside) /// First published in XenServer 4.0. /// </summary> public partial class VM_guest_metrics : XenObject<VM_guest_metrics> { public VM_guest_metrics() { } public VM_guest_metrics(string uuid, Dictionary<string, string> os_version, Dictionary<string, string> PV_drivers_version, bool PV_drivers_up_to_date, Dictionary<string, string> memory, Dictionary<string, string> disks, Dictionary<string, string> networks, Dictionary<string, string> other, DateTime last_updated, Dictionary<string, string> other_config, bool live, tristate_type can_use_hotplug_vbd, tristate_type can_use_hotplug_vif, bool PV_drivers_detected) { this.uuid = uuid; this.os_version = os_version; this.PV_drivers_version = PV_drivers_version; this.PV_drivers_up_to_date = PV_drivers_up_to_date; this.memory = memory; this.disks = disks; this.networks = networks; this.other = other; this.last_updated = last_updated; this.other_config = other_config; this.live = live; this.can_use_hotplug_vbd = can_use_hotplug_vbd; this.can_use_hotplug_vif = can_use_hotplug_vif; this.PV_drivers_detected = PV_drivers_detected; } /// <summary> /// Creates a new VM_guest_metrics from a Proxy_VM_guest_metrics. /// </summary> /// <param name="proxy"></param> public VM_guest_metrics(Proxy_VM_guest_metrics proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(VM_guest_metrics update) { uuid = update.uuid; os_version = update.os_version; PV_drivers_version = update.PV_drivers_version; PV_drivers_up_to_date = update.PV_drivers_up_to_date; memory = update.memory; disks = update.disks; networks = update.networks; other = update.other; last_updated = update.last_updated; other_config = update.other_config; live = update.live; can_use_hotplug_vbd = update.can_use_hotplug_vbd; can_use_hotplug_vif = update.can_use_hotplug_vif; PV_drivers_detected = update.PV_drivers_detected; } internal void UpdateFromProxy(Proxy_VM_guest_metrics proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; os_version = proxy.os_version == null ? null : Maps.convert_from_proxy_string_string(proxy.os_version); PV_drivers_version = proxy.PV_drivers_version == null ? null : Maps.convert_from_proxy_string_string(proxy.PV_drivers_version); PV_drivers_up_to_date = (bool)proxy.PV_drivers_up_to_date; memory = proxy.memory == null ? null : Maps.convert_from_proxy_string_string(proxy.memory); disks = proxy.disks == null ? null : Maps.convert_from_proxy_string_string(proxy.disks); networks = proxy.networks == null ? null : Maps.convert_from_proxy_string_string(proxy.networks); other = proxy.other == null ? null : Maps.convert_from_proxy_string_string(proxy.other); last_updated = proxy.last_updated; other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); live = (bool)proxy.live; can_use_hotplug_vbd = proxy.can_use_hotplug_vbd == null ? (tristate_type) 0 : (tristate_type)Helper.EnumParseDefault(typeof(tristate_type), (string)proxy.can_use_hotplug_vbd); can_use_hotplug_vif = proxy.can_use_hotplug_vif == null ? (tristate_type) 0 : (tristate_type)Helper.EnumParseDefault(typeof(tristate_type), (string)proxy.can_use_hotplug_vif); PV_drivers_detected = (bool)proxy.PV_drivers_detected; } public Proxy_VM_guest_metrics ToProxy() { Proxy_VM_guest_metrics result_ = new Proxy_VM_guest_metrics(); result_.uuid = uuid ?? ""; result_.os_version = Maps.convert_to_proxy_string_string(os_version); result_.PV_drivers_version = Maps.convert_to_proxy_string_string(PV_drivers_version); result_.PV_drivers_up_to_date = PV_drivers_up_to_date; result_.memory = Maps.convert_to_proxy_string_string(memory); result_.disks = Maps.convert_to_proxy_string_string(disks); result_.networks = Maps.convert_to_proxy_string_string(networks); result_.other = Maps.convert_to_proxy_string_string(other); result_.last_updated = last_updated; result_.other_config = Maps.convert_to_proxy_string_string(other_config); result_.live = live; result_.can_use_hotplug_vbd = tristate_type_helper.ToString(can_use_hotplug_vbd); result_.can_use_hotplug_vif = tristate_type_helper.ToString(can_use_hotplug_vif); result_.PV_drivers_detected = PV_drivers_detected; return result_; } /// <summary> /// Creates a new VM_guest_metrics from a Hashtable. /// </summary> /// <param name="table"></param> public VM_guest_metrics(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); os_version = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "os_version")); PV_drivers_version = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "PV_drivers_version")); PV_drivers_up_to_date = Marshalling.ParseBool(table, "PV_drivers_up_to_date"); memory = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "memory")); disks = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "disks")); networks = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "networks")); other = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other")); last_updated = Marshalling.ParseDateTime(table, "last_updated"); other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); live = Marshalling.ParseBool(table, "live"); can_use_hotplug_vbd = (tristate_type)Helper.EnumParseDefault(typeof(tristate_type), Marshalling.ParseString(table, "can_use_hotplug_vbd")); can_use_hotplug_vif = (tristate_type)Helper.EnumParseDefault(typeof(tristate_type), Marshalling.ParseString(table, "can_use_hotplug_vif")); PV_drivers_detected = Marshalling.ParseBool(table, "PV_drivers_detected"); } public bool DeepEquals(VM_guest_metrics other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._os_version, other._os_version) && Helper.AreEqual2(this._PV_drivers_version, other._PV_drivers_version) && Helper.AreEqual2(this._PV_drivers_up_to_date, other._PV_drivers_up_to_date) && Helper.AreEqual2(this._memory, other._memory) && Helper.AreEqual2(this._disks, other._disks) && Helper.AreEqual2(this._networks, other._networks) && Helper.AreEqual2(this._other, other._other) && Helper.AreEqual2(this._last_updated, other._last_updated) && Helper.AreEqual2(this._other_config, other._other_config) && Helper.AreEqual2(this._live, other._live) && Helper.AreEqual2(this._can_use_hotplug_vbd, other._can_use_hotplug_vbd) && Helper.AreEqual2(this._can_use_hotplug_vif, other._can_use_hotplug_vif) && Helper.AreEqual2(this._PV_drivers_detected, other._PV_drivers_detected); } public override string SaveChanges(Session session, string opaqueRef, VM_guest_metrics server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { VM_guest_metrics.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given VM_guest_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static VM_guest_metrics get_record(Session session, string _vm_guest_metrics) { return new VM_guest_metrics((Proxy_VM_guest_metrics)session.proxy.vm_guest_metrics_get_record(session.uuid, _vm_guest_metrics ?? "").parse()); } /// <summary> /// Get a reference to the VM_guest_metrics instance with the specified UUID. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<VM_guest_metrics> get_by_uuid(Session session, string _uuid) { return XenRef<VM_guest_metrics>.Create(session.proxy.vm_guest_metrics_get_by_uuid(session.uuid, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given VM_guest_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static string get_uuid(Session session, string _vm_guest_metrics) { return (string)session.proxy.vm_guest_metrics_get_uuid(session.uuid, _vm_guest_metrics ?? "").parse(); } /// <summary> /// Get the os_version field of the given VM_guest_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static Dictionary<string, string> get_os_version(Session session, string _vm_guest_metrics) { return Maps.convert_from_proxy_string_string(session.proxy.vm_guest_metrics_get_os_version(session.uuid, _vm_guest_metrics ?? "").parse()); } /// <summary> /// Get the PV_drivers_version field of the given VM_guest_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static Dictionary<string, string> get_PV_drivers_version(Session session, string _vm_guest_metrics) { return Maps.convert_from_proxy_string_string(session.proxy.vm_guest_metrics_get_pv_drivers_version(session.uuid, _vm_guest_metrics ?? "").parse()); } /// <summary> /// Get the PV_drivers_up_to_date field of the given VM_guest_metrics. /// First published in XenServer 4.0. /// Deprecated since XenServer 7.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> [Deprecated("XenServer 7.0")] public static bool get_PV_drivers_up_to_date(Session session, string _vm_guest_metrics) { return (bool)session.proxy.vm_guest_metrics_get_pv_drivers_up_to_date(session.uuid, _vm_guest_metrics ?? "").parse(); } /// <summary> /// Get the memory field of the given VM_guest_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static Dictionary<string, string> get_memory(Session session, string _vm_guest_metrics) { return Maps.convert_from_proxy_string_string(session.proxy.vm_guest_metrics_get_memory(session.uuid, _vm_guest_metrics ?? "").parse()); } /// <summary> /// Get the disks field of the given VM_guest_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static Dictionary<string, string> get_disks(Session session, string _vm_guest_metrics) { return Maps.convert_from_proxy_string_string(session.proxy.vm_guest_metrics_get_disks(session.uuid, _vm_guest_metrics ?? "").parse()); } /// <summary> /// Get the networks field of the given VM_guest_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static Dictionary<string, string> get_networks(Session session, string _vm_guest_metrics) { return Maps.convert_from_proxy_string_string(session.proxy.vm_guest_metrics_get_networks(session.uuid, _vm_guest_metrics ?? "").parse()); } /// <summary> /// Get the other field of the given VM_guest_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static Dictionary<string, string> get_other(Session session, string _vm_guest_metrics) { return Maps.convert_from_proxy_string_string(session.proxy.vm_guest_metrics_get_other(session.uuid, _vm_guest_metrics ?? "").parse()); } /// <summary> /// Get the last_updated field of the given VM_guest_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static DateTime get_last_updated(Session session, string _vm_guest_metrics) { return session.proxy.vm_guest_metrics_get_last_updated(session.uuid, _vm_guest_metrics ?? "").parse(); } /// <summary> /// Get the other_config field of the given VM_guest_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static Dictionary<string, string> get_other_config(Session session, string _vm_guest_metrics) { return Maps.convert_from_proxy_string_string(session.proxy.vm_guest_metrics_get_other_config(session.uuid, _vm_guest_metrics ?? "").parse()); } /// <summary> /// Get the live field of the given VM_guest_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static bool get_live(Session session, string _vm_guest_metrics) { return (bool)session.proxy.vm_guest_metrics_get_live(session.uuid, _vm_guest_metrics ?? "").parse(); } /// <summary> /// Get the can_use_hotplug_vbd field of the given VM_guest_metrics. /// First published in XenServer 7.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static tristate_type get_can_use_hotplug_vbd(Session session, string _vm_guest_metrics) { return (tristate_type)Helper.EnumParseDefault(typeof(tristate_type), (string)session.proxy.vm_guest_metrics_get_can_use_hotplug_vbd(session.uuid, _vm_guest_metrics ?? "").parse()); } /// <summary> /// Get the can_use_hotplug_vif field of the given VM_guest_metrics. /// First published in XenServer 7.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static tristate_type get_can_use_hotplug_vif(Session session, string _vm_guest_metrics) { return (tristate_type)Helper.EnumParseDefault(typeof(tristate_type), (string)session.proxy.vm_guest_metrics_get_can_use_hotplug_vif(session.uuid, _vm_guest_metrics ?? "").parse()); } /// <summary> /// Get the PV_drivers_detected field of the given VM_guest_metrics. /// First published in XenServer 7.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> public static bool get_PV_drivers_detected(Session session, string _vm_guest_metrics) { return (bool)session.proxy.vm_guest_metrics_get_pv_drivers_detected(session.uuid, _vm_guest_metrics ?? "").parse(); } /// <summary> /// Set the other_config field of the given VM_guest_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _vm_guest_metrics, Dictionary<string, string> _other_config) { session.proxy.vm_guest_metrics_set_other_config(session.uuid, _vm_guest_metrics ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given VM_guest_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _vm_guest_metrics, string _key, string _value) { session.proxy.vm_guest_metrics_add_to_other_config(session.uuid, _vm_guest_metrics ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given VM_guest_metrics. If the key is not in that Map, then do nothing. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_guest_metrics">The opaque_ref of the given vm_guest_metrics</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _vm_guest_metrics, string _key) { session.proxy.vm_guest_metrics_remove_from_other_config(session.uuid, _vm_guest_metrics ?? "", _key ?? "").parse(); } /// <summary> /// Return a list of all the VM_guest_metrics instances known to the system. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static List<XenRef<VM_guest_metrics>> get_all(Session session) { return XenRef<VM_guest_metrics>.Create(session.proxy.vm_guest_metrics_get_all(session.uuid).parse()); } /// <summary> /// Get all the VM_guest_metrics Records at once, in a single XML RPC call /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<VM_guest_metrics>, VM_guest_metrics> get_all_records(Session session) { return XenRef<VM_guest_metrics>.Create<Proxy_VM_guest_metrics>(session.proxy.vm_guest_metrics_get_all_records(session.uuid).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid; /// <summary> /// version of the OS /// </summary> public virtual Dictionary<string, string> os_version { get { return _os_version; } set { if (!Helper.AreEqual(value, _os_version)) { _os_version = value; Changed = true; NotifyPropertyChanged("os_version"); } } } private Dictionary<string, string> _os_version; /// <summary> /// version of the PV drivers /// </summary> public virtual Dictionary<string, string> PV_drivers_version { get { return _PV_drivers_version; } set { if (!Helper.AreEqual(value, _PV_drivers_version)) { _PV_drivers_version = value; Changed = true; NotifyPropertyChanged("PV_drivers_version"); } } } private Dictionary<string, string> _PV_drivers_version; /// <summary> /// Logically equivalent to PV_drivers_detected /// </summary> public virtual bool PV_drivers_up_to_date { get { return _PV_drivers_up_to_date; } set { if (!Helper.AreEqual(value, _PV_drivers_up_to_date)) { _PV_drivers_up_to_date = value; Changed = true; NotifyPropertyChanged("PV_drivers_up_to_date"); } } } private bool _PV_drivers_up_to_date; /// <summary> /// This field exists but has no data. Use the memory and memory_internal_free RRD data-sources instead. /// </summary> public virtual Dictionary<string, string> memory { get { return _memory; } set { if (!Helper.AreEqual(value, _memory)) { _memory = value; Changed = true; NotifyPropertyChanged("memory"); } } } private Dictionary<string, string> _memory; /// <summary> /// This field exists but has no data. /// </summary> public virtual Dictionary<string, string> disks { get { return _disks; } set { if (!Helper.AreEqual(value, _disks)) { _disks = value; Changed = true; NotifyPropertyChanged("disks"); } } } private Dictionary<string, string> _disks; /// <summary> /// network configuration /// </summary> public virtual Dictionary<string, string> networks { get { return _networks; } set { if (!Helper.AreEqual(value, _networks)) { _networks = value; Changed = true; NotifyPropertyChanged("networks"); } } } private Dictionary<string, string> _networks; /// <summary> /// anything else /// </summary> public virtual Dictionary<string, string> other { get { return _other; } set { if (!Helper.AreEqual(value, _other)) { _other = value; Changed = true; NotifyPropertyChanged("other"); } } } private Dictionary<string, string> _other; /// <summary> /// Time at which this information was last updated /// </summary> public virtual DateTime last_updated { get { return _last_updated; } set { if (!Helper.AreEqual(value, _last_updated)) { _last_updated = value; Changed = true; NotifyPropertyChanged("last_updated"); } } } private DateTime _last_updated; /// <summary> /// additional configuration /// First published in XenServer 5.0. /// </summary> public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config; /// <summary> /// True if the guest is sending heartbeat messages via the guest agent /// First published in XenServer 5.0. /// </summary> public virtual bool live { get { return _live; } set { if (!Helper.AreEqual(value, _live)) { _live = value; Changed = true; NotifyPropertyChanged("live"); } } } private bool _live; /// <summary> /// The guest's statement of whether it supports VBD hotplug, i.e. whether it is capable of responding immediately to instantiation of a new VBD by bringing online a new PV block device. If the guest states that it is not capable, then the VBD plug and unplug operations will not be allowed while the guest is running. /// First published in XenServer 7.0. /// </summary> public virtual tristate_type can_use_hotplug_vbd { get { return _can_use_hotplug_vbd; } set { if (!Helper.AreEqual(value, _can_use_hotplug_vbd)) { _can_use_hotplug_vbd = value; Changed = true; NotifyPropertyChanged("can_use_hotplug_vbd"); } } } private tristate_type _can_use_hotplug_vbd; /// <summary> /// The guest's statement of whether it supports VIF hotplug, i.e. whether it is capable of responding immediately to instantiation of a new VIF by bringing online a new PV network device. If the guest states that it is not capable, then the VIF plug and unplug operations will not be allowed while the guest is running. /// First published in XenServer 7.0. /// </summary> public virtual tristate_type can_use_hotplug_vif { get { return _can_use_hotplug_vif; } set { if (!Helper.AreEqual(value, _can_use_hotplug_vif)) { _can_use_hotplug_vif = value; Changed = true; NotifyPropertyChanged("can_use_hotplug_vif"); } } } private tristate_type _can_use_hotplug_vif; /// <summary> /// At least one of the guest's devices has successfully connected to the backend. /// First published in XenServer 7.0. /// </summary> public virtual bool PV_drivers_detected { get { return _PV_drivers_detected; } set { if (!Helper.AreEqual(value, _PV_drivers_detected)) { _PV_drivers_detected = value; Changed = true; NotifyPropertyChanged("PV_drivers_detected"); } } } private bool _PV_drivers_detected; } }
/////////////////////////////////////////////////////////////////////////////////// // Open 3D Model Viewer (open3mod) (v2.0) // [LogViewer.cs] // (c) 2012-2015, Open3Mod Contributors // // Licensed under the terms and conditions of the 3-clause BSD license. See // the LICENSE file in the root folder of the repository for the details. // // HIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /////////////////////////////////////////////////////////////////////////////////// using System; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; using open3mod.Properties; namespace open3mod { public partial class LogViewer : Form { private readonly MainWindow _mainWindow; private LogStore _currentLogStore; private const string RtfHeader = @"{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Consolas;}}" + @"{\colortbl;" + // color palette: @"\red255\green0\blue0;" + @"\red255\green120\blue0;" + @"\red0\green150\blue0;" + @"\red0\green0\blue180;" + @"\red0\green0\blue0;}"; public MainWindow MainWindow { get { return _mainWindow; } } public LogViewer(MainWindow mainWindow) { _mainWindow = mainWindow; InitializeComponent(); _mainWindow.TabChanged += (tab, add) => { if(IsDisposed) { return; } PopulateList(); }; PopulateList(); } private void PopulateList() { comboBoxSource.Items.Clear(); int select = -1; foreach (var tab in MainWindow.UiState.Tabs) { if(tab.File == null) { continue; } var index = comboBoxSource.Items.Add(tab.File); if (tab == MainWindow.UiState.ActiveTab) { select = index; } } if (select != -1) { comboBoxSource.SelectedItem = comboBoxSource.Items[select]; } else { comboBoxSource.SelectedItem = comboBoxSource.Items.Count > 0 ? comboBoxSource.Items[0] : null; } FetchLogEntriesFromScene(); } private void FetchLogEntriesFromScene() { var sceneName = (string)comboBoxSource.SelectedItem; var scene = (from tab in MainWindow.UiState.Tabs where tab.File == sceneName select tab.ActiveScene).FirstOrDefault(); if (scene == null) { richTextBox.Text = Resources.LogViewer_FetchLogEntriesFromScene_No_scene_loaded; return; } _currentLogStore = scene.LogStore; BuildRtf(); } private void BuildRtf() { var sb = new StringBuilder(); sb.Append(RtfHeader); foreach (var entry in _currentLogStore.Messages) { string s; switch (entry.Cat) { case LogStore.Category.Info: if(!checkBoxFilterInformation.Checked) { continue; } s = @"\pard \cf3 \b \fs18 "; break; case LogStore.Category.Warn: if (!checkBoxFilterWarning.Checked) { continue; } s = @"\pard \cf2 \b \fs18 "; break; case LogStore.Category.Error: if (!checkBoxFilterError.Checked) { continue; } s = @"\pard \cf1 \b \fs18 "; break; case LogStore.Category.Debug: if (!checkBoxFilterVerbose.Checked) { continue; } s = @"\pard \cf4 \b \fs18 "; break; case LogStore.Category.System: s = @"\pard \cf5 \b \fs18 "; break; default: throw new ArgumentOutOfRangeException(); } s = s + "job: " + entry.ThreadId.ToString(CultureInfo.InvariantCulture).PadLeft(5, ' ') + ",\t time: " + entry.Time.ToString(CultureInfo.InvariantCulture).PadLeft(10, ' ') + ",\t"; sb.Append(s); foreach (var ch in entry.Message) { if (ch == '\n' || ch == '\r') { continue; } if (ch == '\\' || ch == '}' || ch == '{') { sb.Append('\\'); } sb.Append(ch); } sb.Append(@"\par "); } sb.Append('}'); var rtfCode = sb.ToString(); richTextBox.Rtf = rtfCode; } private void OnClearAll(object sender, EventArgs e) { _currentLogStore.Drop(); richTextBox.Text = Resources.LogViewer_OnClearAll_Nothing_to_display; } private void OnSave(object sender, EventArgs e) { if(saveFileDialog.ShowDialog() != DialogResult.OK) { return; } using (var stream = new StreamWriter(saveFileDialog.OpenFile())) { foreach (var entry in _currentLogStore.Messages) { stream.Write(LogEntryToPlainText(entry) + "\r\n"); } } } private string LogEntryToPlainText(LogStore.Entry entry) { string s; switch (entry.Cat) { case LogStore.Category.Info: s = "Info: "; break; case LogStore.Category.Warn: s = "Warn: "; break; case LogStore.Category.Error: s = "Error: "; break; case LogStore.Category.Debug: s = "Debug: "; break; case LogStore.Category.System: s = "System: "; break; default: throw new ArgumentOutOfRangeException(); } return entry.ThreadId.ToString(CultureInfo.InvariantCulture).PadLeft(4) + "|" + entry.Time.ToString(CultureInfo.InvariantCulture).PadLeft(10,'0') + " " + s + entry.Message; } private void OnFilterChange(object sender, EventArgs e) { BuildRtf(); } private void filterToolStripMenuItem_Click(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } private void ChangeLogSource(object sender, EventArgs e) { FetchLogEntriesFromScene(); } } } /* vi: set shiftwidth=4 tabstop=4: */
// Copyright 2006-2008 Splicer Project - http://www.codeplex.com/splicer/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Specialized; using System.Drawing; using System.IO; using NUnit.Framework; using Splicer.Renderer; using Splicer.WindowsMedia; namespace Splicer.Timeline.Tests { [TestFixture] public class TrackFixture : AbstractFixture { [Test] public void AddAudioOverloads() { // test all the overloads for AddAudio using (ITimeline timeline = new DefaultTimeline()) { ITrack track = timeline.AddAudioGroup().AddTrack(); IClip clip1 = track.AddAudio("1sec.wav"); Assert.AreEqual(0, clip1.Offset); Assert.AreEqual(1, clip1.Duration); IClip clip2 = track.AddAudio("1sec.wav", 1); Assert.AreEqual(2, clip2.Offset); Assert.AreEqual(1, clip2.Duration); IClip clip3 = track.AddAudio("1sec.wav", 0, 0.5); Assert.AreEqual(3, clip3.Offset); Assert.AreEqual(0.5, clip3.Duration); IClip clip4 = track.AddAudio("1sec.wav", 0, 0.5, 1.0); Assert.AreEqual(3.5, clip4.Offset); Assert.AreEqual(0.5, clip4.Duration); Assert.AreEqual(0.5, clip4.MediaStart); IClip clip5 = track.AddAudio("1sec.wav", InsertPosition.Absolute, 6, 0, -1); Assert.AreEqual(6, clip5.Offset); Assert.AreEqual(1, clip5.Duration); IClip clip6 = track.AddAudio("myclip", "1sec.wav", InsertPosition.Absolute, 8, 0, 0.5); Assert.AreEqual(8, clip6.Offset); Assert.AreEqual(0, clip6.MediaStart); Assert.AreEqual(0.5, clip6.Duration); Assert.AreEqual("myclip", clip6.Name); } } [Test] public void AddClipsToTrack() { using (ITimeline timeline = new DefaultTimeline()) { IGroup group = timeline.AddVideoGroup(24, 320, 200); ITrack track1 = group.AddTrack(); ITrack track2 = group.AddTrack(); track1.AddClip("image1.jpg", GroupMediaType.Image, InsertPosition.Relative, 0, 0, 2); track2.AddClip("image2.jpg", GroupMediaType.Image, InsertPosition.Relative, 0, 0, 2); track1.AddClip("image3.jpg", GroupMediaType.Image, InsertPosition.Relative, 0, 0, 2); track2.AddClip("image4.jpg", GroupMediaType.Image, InsertPosition.Relative, 0, 0, 2); Assert.AreEqual(2, track1.Clips.Count); Assert.AreEqual(2, track2.Clips.Count); PrepareToExecute(timeline, @"<timeline framerate=""30.0000000""> <group type=""video"" bitdepth=""24"" height=""200"" framerate=""30.0000000"" previewmode=""0""> <track> <clip start=""0"" stop=""2"" src=""image1.jpg"" /> <clip start=""2"" stop=""4"" src=""image3.jpg"" /> </track> <track> <clip start=""0"" stop=""2"" src=""image2.jpg"" /> <clip start=""2"" stop=""4"" src=""image4.jpg"" /> </track> </group> </timeline>"); } } [Test] public void AddEffectsToTrack() { using (ITimeline timeline = new DefaultTimeline()) { IGroup group = timeline.AddVideoGroup(24, 320, 200); ITrack track = group.AddTrack(); IEffect effect = track.AddEffect("test", -1, 1, 3, StandardEffects.CreateBlurEffect(2, 2, 15)); Assert.AreEqual(1, track.Effects.Count); Assert.AreSame(effect, track.Effects[0]); PrepareToExecute(timeline, @"<timeline framerate=""30.0000000""> <group type=""video"" bitdepth=""24"" height=""200"" framerate=""30.0000000"" previewmode=""0""> <track> <effect clsid=""{7312498D-E87A-11D1-81E0-0000F87557DB}"" username=""test""> <param name=""PixelRadius"" value=""2""> <linear time=""2"" value=""15"" /> </param> </effect> </track> </group> </timeline>"); } } [Test] public void AddImageOverloads() { // test all the overloads for AddVideo using (ITimeline timeline = new DefaultTimeline()) { ITrack track = timeline.AddVideoGroup(24, 320, 240).AddTrack(); IClip clip1 = track.AddImage("image1.jpg"); Assert.AreEqual(0, clip1.Offset); Assert.AreEqual(1, clip1.Duration); IClip clip2 = track.AddImage("image1.jpg", 1); Assert.AreEqual(2, clip2.Offset); Assert.AreEqual(1, clip2.Duration); IClip clip3 = track.AddImage("image1.jpg", 0, 0.5); Assert.AreEqual(3, clip3.Offset); Assert.AreEqual(0.5, clip3.Duration); IClip clip4 = track.AddImage("image1.jpg", 0, 0.5, 1.0); Assert.AreEqual(3.5, clip4.Offset); Assert.AreEqual(0.5, clip4.Duration); Assert.AreEqual(0.5, clip4.MediaStart); IClip clip5 = track.AddImage("image1.jpg", InsertPosition.Absolute, 6, 0, -1); Assert.AreEqual(6, clip5.Offset); Assert.AreEqual(1, clip5.Duration); IClip clip6 = track.AddImage("myclip", "image1.jpg", InsertPosition.Absolute, 8, 0, 0.5); Assert.AreEqual(8, clip6.Offset); Assert.AreEqual(0, clip6.MediaStart); Assert.AreEqual(0.5, clip6.Duration); Assert.AreEqual("myclip", clip6.Name); } } [Test] public void AddInMemoryImageClipsToTrack() { var tempFiles = new StringCollection(); Action<IClip> addClip = delegate(IClip clip) { if (tempFiles.Contains(clip.File.FileName)) Assert.Fail("TempFile: {0} duplicated", clip.File.FileName); }; string outputFile = "AddInMemoryImageClipsToTrack.wmv"; Image image = Image.FromFile("image1.jpg"); using (ITimeline timeline = new DefaultTimeline()) { timeline.AddAudioGroup().AddTrack().AddAudio("testinput.wav", 0, 7.5); ITrack videoTrack = timeline.AddVideoGroup(24, 320, 200).AddTrack(); addClip(videoTrack.AddImage(image)); // 0->1 addClip(videoTrack.AddImage(image, 1)); // 2->3 addClip(videoTrack.AddImage(image, 1, 0.5)); // 4->4.5 addClip(videoTrack.AddImage(image, InsertPosition.Absolute, 5, 0, 1)); // 5->6 IClip clip = videoTrack.AddImage("named", image, InsertPosition.Absolute, 7, 0.5, 1); // 7->7.5 addClip(clip); Assert.AreEqual("named", clip.Name); Assert.AreEqual(7.5, videoTrack.Duration); using ( var renderer = new WindowsMediaRenderer(timeline, outputFile, WindowsMediaProfiles.HighQualityVideo) ) { renderer.Render(); } } foreach (string file in tempFiles) { Assert.IsFalse(File.Exists(file)); } } [Test] public void AddOverlappingClips1() { // Though we've added 3 clips, the DES track only contains 2 tracks because the third has been occluded. // this behaviour is mimicked by the virtual clip collection, which demonstrates which clips are actually // visible at run time (only on clip on a track is being rendered at any one time) // clip 1 is added, 2 thru 10 secs (8 sec duration) // clip 2 is added 1 second before clip 1, and completely occluded it at 56 secs in length - clip 1 is gone // clip 3 is added 1 second before clip 1, it will play to completion, so the start position for clip 2 is placed // and the end of clip3, and it's media start value is incremented accordingly. using (ITimeline timeline = new DefaultTimeline()) { IGroup group = timeline.AddAudioGroup(); ITrack track = group.AddTrack(); track.AddClip("testinput.mp3", GroupMediaType.Audio, InsertPosition.Absolute, 2, 0, -1); track.AddClip("testinput.wav", GroupMediaType.Audio, InsertPosition.Absolute, 1, 0, -1); track.AddClip("testinput.mp3", GroupMediaType.Audio, InsertPosition.Absolute, 0, 0, -1); Assert.AreEqual( @"<clip start=""0"" stop=""8.051875"" src=""testinput.mp3"" mstart=""0"" /> <clip start=""8.051875"" stop=""56.125"" src=""testinput.wav"" mstart=""7.051875"" />", track.VirtualClips.ToString().Replace(Environment.CurrentDirectory + "\\", "")); Console.WriteLine(track.VirtualClips.ToString()); PrepareToExecute(timeline, @"<timeline framerate=""30.0000000""> <group type=""audio"" framerate=""30.0000000"" previewmode=""0""> <track> <clip start=""0"" stop=""8.0518750"" src=""testinput.mp3"" mstart=""0"" /> <clip start=""8.0518750"" stop=""56.1250000"" src=""testinput.wav"" mstart=""7.0518750"" /> </track> </group> </timeline>"); } } [Test] public void AddOverlappingClips2() { // What's happening here is.. // clip 1 is added, 2 thru 10 secs (8 sec duration) // clip 2 is added 1 second before clip 1, and completely occluded it at 56 secs in length - clip 1 is gone // clip 3 is added 1 second before clip 1, it will play to completion, so the start position for clip 2 is placed // and the end of clip3, and it's media start value is incremented accordingly. using (ITimeline timeline = new DefaultTimeline()) { IGroup group = timeline.AddAudioGroup(); ITrack track = group.AddTrack(); track.AddClip("testinput.mp3", GroupMediaType.Audio, InsertPosition.Absolute, 0, 0, -1); track.AddClip("testinput.wav", GroupMediaType.Audio, InsertPosition.Absolute, 1, 0, -1); track.AddClip("testinput.mp3", GroupMediaType.Audio, InsertPosition.Absolute, 2, 0, -1); Assert.AreEqual( @"<clip start=""0"" stop=""1"" src=""testinput.mp3"" mstart=""0"" /> <clip start=""1"" stop=""2"" src=""testinput.wav"" mstart=""0"" /> <clip start=""2"" stop=""10.051875"" src=""testinput.mp3"" mstart=""0"" /> <clip start=""10.051875"" stop=""56.125"" src=""testinput.wav"" mstart=""9.051875"" />", track.VirtualClips.ToString().Replace(Environment.CurrentDirectory +"\\","")); PrepareToExecute(timeline, @"<timeline framerate=""30.0000000""> <group type=""audio"" framerate=""30.0000000"" previewmode=""0""> <track> <clip start=""0"" stop=""1"" src=""testinput.mp3"" mstart=""0"" /> <clip start=""1"" stop=""2"" src=""testinput.wav"" mstart=""0"" /> <clip start=""2"" stop=""10.0518750"" src=""testinput.mp3"" mstart=""0"" /> <clip start=""10.0518750"" stop=""56.1250000"" src=""testinput.wav"" mstart=""9.0518750"" /> </track> </group> </timeline>"); } } [Test] public void AddTrack() { using (ITimeline timeline = new DefaultTimeline()) { IGroup group = timeline.AddAudioGroup(); ITrack rootTrack = group.AddTrack(); Assert.AreSame(group, rootTrack.Group); Assert.AreSame(group, rootTrack.Container); Assert.AreEqual(1, group.Tracks.Count); Assert.AreSame(group.Tracks[0], rootTrack); ITrack track2 = group.AddTrack(); Assert.AreEqual(2, group.Tracks.Count); Assert.AreEqual(group.Tracks[1], track2); PrepareToExecute(timeline, @"<timeline framerate=""30.0000000""> <group type=""audio"" framerate=""30.0000000"" previewmode=""0""> <track /> <track /> </group> </timeline>"); } } [Test] public void AddTrackWithNames() { using (ITimeline timeline = new DefaultTimeline()) { IGroup group = timeline.AddAudioGroup(); ITrack track1 = group.AddTrack("track1", -1); Assert.AreEqual("track1", track1.Name); Assert.AreEqual(1, group.Tracks.Count); track1.AddClip("testinput.wav", GroupMediaType.Audio, InsertPosition.Relative, 0, 0, -1); Assert.AreSame(group.Tracks[0], track1); ITrack track2 = group.AddTrack("track2", -1); Assert.AreEqual("track2", track2.Name); track2.AddClip("testinput.wav", GroupMediaType.Audio, InsertPosition.Relative, 0, 0, -1); Assert.AreEqual(2, group.Tracks.Count); Assert.AreEqual(group.Tracks[1], track2); PrepareToExecute(timeline, @"<timeline framerate=""30.0000000""> <group type=""audio"" framerate=""30.0000000"" previewmode=""0""> <track username=""track1""> <clip start=""0"" stop=""55.1250000"" src=""testinput.wav"" mstart=""0"" /> </track> <track username=""track2""> <clip start=""0"" stop=""55.1250000"" src=""testinput.wav"" mstart=""0"" /> </track> </group> </timeline>"); } } [Test] public void AddTransitionsToTrack() { using (ITimeline timeline = new DefaultTimeline()) { IGroup group = timeline.AddVideoGroup(24, 320, 200); ITrack track = group.AddTrack(); TransitionDefinition definition = StandardTransitions.CreateFade(); ITransition transition = track.AddTransition("test", 1, 3, definition, false); Assert.AreEqual(1, track.Transitions.Count); Assert.AreSame(transition, track.Transitions[0]); Assert.AreEqual("test", transition.Name); Assert.AreSame(definition, transition.TransitionDefinition); PrepareToExecute(timeline, @"<timeline framerate=""30.0000000""> <group type=""video"" bitdepth=""24"" height=""200"" framerate=""30.0000000"" previewmode=""0""> <track> <transition start=""1"" stop=""4"" clsid=""{16B280C5-EE70-11D1-9066-00C04FD9189D}"" username=""test"" /> </track> </group> </timeline>"); } } [Test] public void AddVideoOverloads() { // test all the overloads for AddVideo using (ITimeline timeline = new DefaultTimeline()) { ITrack track = timeline.AddVideoGroup(24, 320, 240).AddTrack(); IClip clip1 = track.AddVideo("1sec.wmv"); Assert.AreEqual(0, clip1.Offset); Assert.AreEqual(1, clip1.Duration); IClip clip2 = track.AddVideo("1sec.wmv", 1); Assert.AreEqual(2, clip2.Offset); Assert.AreEqual(1, clip2.Duration); IClip clip3 = track.AddVideo("1sec.wmv", 0, 0.5); Assert.AreEqual(3, clip3.Offset); Assert.AreEqual(0.5, clip3.Duration); IClip clip4 = track.AddVideo("1sec.wmv", 0, 0.5, 1.0); Assert.AreEqual(3.5, clip4.Offset); Assert.AreEqual(0.5, clip4.Duration); Assert.AreEqual(0.5, clip4.MediaStart); IClip clip5 = track.AddVideo("1sec.wmv", InsertPosition.Absolute, 6, 0, -1); Assert.AreEqual(6, clip5.Offset); Assert.AreEqual(1, clip5.Duration); IClip clip6 = track.AddVideo("myclip", "1sec.wmv", InsertPosition.Absolute, 8, 0, 0.5); Assert.AreEqual(8, clip6.Offset); Assert.AreEqual(0, clip6.MediaStart); Assert.AreEqual(0.5, clip6.Duration); Assert.AreEqual("myclip", clip6.Name); } } [Test] public void ClipsAssignedContainer() { using (ITimeline timeline = new DefaultTimeline()) { IGroup group = timeline.AddVideoGroup(24, 320, 200); ITrack track = group.AddTrack(); IClip clip = track.AddClip("image1.jpg", GroupMediaType.Image, InsertPosition.Relative, 0, 0, 2); Assert.AreSame(track, clip.Container); } } [Test] public void EnsureClipBubblesBeforeAndAfterEffectAddedUp() { int beforeCount = 0; int afterCount = 0; using (ITimeline timeline = new DefaultTimeline()) { IGroup group = timeline.AddAudioGroup(); ITrack track = group.AddTrack(); track.AddingEffect += delegate { beforeCount++; }; track.AddedEffect += delegate { afterCount++; }; IClip clip = track.AddClip("testinput.mp3", GroupMediaType.Audio, InsertPosition.Absolute, 0, 0, -1); clip.AddEffect(0, 1, StandardEffects.CreateDefaultBlur()); Assert.AreEqual(1, beforeCount); Assert.AreEqual(1, afterCount); } } [Test] public void RemoveEvents() { int count = 0; EventHandler increment = delegate { count++; }; EventHandler<AddedEffectEventArgs> incrementForAfterEffectAdded = delegate { count++; }; EventHandler<AddedTransitionEventArgs> incrementForAfterTransitionAdded = delegate { count++; }; EventHandler<AddedClipEventArgs> incrementForAfterClipAdded = delegate { count++; }; using (ITimeline timeline = new DefaultTimeline()) { ITrack track = timeline.AddAudioGroup().AddTrack(); track.AddedEffect += incrementForAfterEffectAdded; track.AddedTransition += incrementForAfterTransitionAdded; track.AddedClip += incrementForAfterClipAdded; track.AddingEffect += increment; track.AddingTransition += increment; track.AddingClip += increment; track.AddEffect(0, 2, StandardEffects.CreateDefaultBlur()); track.AddClip("testinput.mp3", GroupMediaType.Audio, InsertPosition.Absolute, 0, 0, 1); track.AddTransition(0, 2, StandardTransitions.CreateFade()); Assert.AreEqual(6, count); count = 0; track.AddedEffect -= incrementForAfterEffectAdded; track.AddedTransition -= incrementForAfterTransitionAdded; track.AddedClip -= incrementForAfterClipAdded; track.AddingEffect -= increment; track.AddingTransition -= increment; track.AddingClip -= increment; track.AddEffect(0, 2, StandardEffects.CreateDefaultBlur()); track.AddClip("testinput.mp3", GroupMediaType.Audio, InsertPosition.Relative, 0, 0, 1); track.AddTransition(2, 2, StandardTransitions.CreateFade()); Assert.AreEqual(0, count); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; namespace System.Transactions { internal delegate void FinishVolatileDelegate(InternalEnlistment enlistment); // Base class for all volatile enlistment states internal abstract class VolatileEnlistmentState : EnlistmentState { // Double-checked locking pattern requires volatile for read/write synchronization private static volatile VolatileEnlistmentActive s_volatileEnlistmentActive; private static volatile VolatileEnlistmentPreparing s_volatileEnlistmentPreparing; private static volatile VolatileEnlistmentPrepared s_volatileEnlistmentPrepared; private static volatile VolatileEnlistmentSPC s_volatileEnlistmentSPC; private static volatile VolatileEnlistmentPreparingAborting s_volatileEnlistmentPreparingAborting; private static volatile VolatileEnlistmentAborting s_volatileEnlistmentAborting; private static volatile VolatileEnlistmentCommitting s_volatileEnlistmentCommitting; private static volatile VolatileEnlistmentInDoubt s_volatileEnlistmentInDoubt; private static volatile VolatileEnlistmentEnded s_volatileEnlistmentEnded; private static volatile VolatileEnlistmentDone s_volatileEnlistmentDone; // Object for synchronizing access to the entire class( avoiding lock( typeof( ... )) ) private static object s_classSyncObject; internal static VolatileEnlistmentActive VolatileEnlistmentActive { get { if (s_volatileEnlistmentActive == null) { lock (ClassSyncObject) { if (s_volatileEnlistmentActive == null) { VolatileEnlistmentActive temp = new VolatileEnlistmentActive(); s_volatileEnlistmentActive = temp; } } } return s_volatileEnlistmentActive; } } protected static VolatileEnlistmentPreparing VolatileEnlistmentPreparing { get { if (s_volatileEnlistmentPreparing == null) { lock (ClassSyncObject) { if (s_volatileEnlistmentPreparing == null) { VolatileEnlistmentPreparing temp = new VolatileEnlistmentPreparing(); s_volatileEnlistmentPreparing = temp; } } } return s_volatileEnlistmentPreparing; } } protected static VolatileEnlistmentPrepared VolatileEnlistmentPrepared { get { if (s_volatileEnlistmentPrepared == null) { lock (ClassSyncObject) { if (s_volatileEnlistmentPrepared == null) { VolatileEnlistmentPrepared temp = new VolatileEnlistmentPrepared(); s_volatileEnlistmentPrepared = temp; } } } return s_volatileEnlistmentPrepared; } } protected static VolatileEnlistmentSPC VolatileEnlistmentSPC { get { if (s_volatileEnlistmentSPC == null) { lock (ClassSyncObject) { if (s_volatileEnlistmentSPC == null) { VolatileEnlistmentSPC temp = new VolatileEnlistmentSPC(); s_volatileEnlistmentSPC = temp; } } } return s_volatileEnlistmentSPC; } } protected static VolatileEnlistmentPreparingAborting VolatileEnlistmentPreparingAborting { get { if (s_volatileEnlistmentPreparingAborting == null) { lock (ClassSyncObject) { if (s_volatileEnlistmentPreparingAborting == null) { VolatileEnlistmentPreparingAborting temp = new VolatileEnlistmentPreparingAborting(); s_volatileEnlistmentPreparingAborting = temp; } } } return s_volatileEnlistmentPreparingAborting; } } protected static VolatileEnlistmentAborting VolatileEnlistmentAborting { get { if (s_volatileEnlistmentAborting == null) { lock (ClassSyncObject) { if (s_volatileEnlistmentAborting == null) { VolatileEnlistmentAborting temp = new VolatileEnlistmentAborting(); s_volatileEnlistmentAborting = temp; } } } return s_volatileEnlistmentAborting; } } protected static VolatileEnlistmentCommitting VolatileEnlistmentCommitting { get { if (s_volatileEnlistmentCommitting == null) { lock (ClassSyncObject) { if (s_volatileEnlistmentCommitting == null) { VolatileEnlistmentCommitting temp = new VolatileEnlistmentCommitting(); s_volatileEnlistmentCommitting = temp; } } } return s_volatileEnlistmentCommitting; } } protected static VolatileEnlistmentInDoubt VolatileEnlistmentInDoubt { get { if (s_volatileEnlistmentInDoubt == null) { lock (ClassSyncObject) { if (s_volatileEnlistmentInDoubt == null) { VolatileEnlistmentInDoubt temp = new VolatileEnlistmentInDoubt(); s_volatileEnlistmentInDoubt = temp; } } } return s_volatileEnlistmentInDoubt; } } protected static VolatileEnlistmentEnded VolatileEnlistmentEnded { get { if (s_volatileEnlistmentEnded == null) { lock (ClassSyncObject) { if (s_volatileEnlistmentEnded == null) { VolatileEnlistmentEnded temp = new VolatileEnlistmentEnded(); s_volatileEnlistmentEnded = temp; } } } return s_volatileEnlistmentEnded; } } protected static VolatileEnlistmentDone VolatileEnlistmentDone { get { if (s_volatileEnlistmentDone == null) { lock (ClassSyncObject) { if (s_volatileEnlistmentDone == null) { VolatileEnlistmentDone temp = new VolatileEnlistmentDone(); s_volatileEnlistmentDone = temp; } } } return s_volatileEnlistmentDone; } } // Helper object for static synchronization private static object ClassSyncObject { get { if (s_classSyncObject == null) { object o = new object(); Interlocked.CompareExchange(ref s_classSyncObject, o, null); } return s_classSyncObject; } } // Override of get_RecoveryInformation to be more specific with the exception string. internal override byte[] RecoveryInformation(InternalEnlistment enlistment) { throw TransactionException.CreateInvalidOperationException(TraceSourceType.TraceSourceLtm, SR.VolEnlistNoRecoveryInfo, null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId); } } // Active state for a volatile enlistment indicates that the enlistment has been created // but no one has begun committing or aborting the transaction. From this state the enlistment // can abort the transaction or call read only to indicate that it does not want to // participate further in the transaction. internal class VolatileEnlistmentActive : VolatileEnlistmentState { internal override void EnterState(InternalEnlistment enlistment) { // Set the enlistment state enlistment.State = this; // Yeah it's active. } #region IEnlistment Related Events internal override void EnlistmentDone(InternalEnlistment enlistment) { // End this enlistment VolatileEnlistmentDone.EnterState(enlistment); // Note another enlistment finished. enlistment.FinishEnlistment(); } #endregion #region State Change Events internal override void ChangeStatePreparing(InternalEnlistment enlistment) { VolatileEnlistmentPreparing.EnterState(enlistment); } internal override void ChangeStateSinglePhaseCommit(InternalEnlistment enlistment) { VolatileEnlistmentSPC.EnterState(enlistment); } #endregion #region Internal Events internal override void InternalAborted(InternalEnlistment enlistment) { // Change the enlistment state to aborting. VolatileEnlistmentAborting.EnterState(enlistment); } #endregion } // Preparing state is the time after prepare has been called but no response has been received. internal class VolatileEnlistmentPreparing : VolatileEnlistmentState { internal override void EnterState(InternalEnlistment enlistment) { // Set the enlistment state enlistment.State = this; Monitor.Exit(enlistment.Transaction); try // Don't hold this lock while calling into the application code. { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.EnlistmentStatus(enlistment, NotificationCall.Prepare); } enlistment.EnlistmentNotification.Prepare(enlistment.PreparingEnlistment); } finally { Monitor.Enter(enlistment.Transaction); } } internal override void EnlistmentDone(InternalEnlistment enlistment) { VolatileEnlistmentDone.EnterState(enlistment); // Process Finished InternalEnlistment enlistment.FinishEnlistment(); } internal override void Prepared(InternalEnlistment enlistment) { // Change the enlistments state to prepared. VolatileEnlistmentPrepared.EnterState(enlistment); // Process Finished InternalEnlistment enlistment.FinishEnlistment(); } // The enlistment says to abort start the abort sequence. internal override void ForceRollback(InternalEnlistment enlistment, Exception e) { // Change enlistment state to aborting VolatileEnlistmentEnded.EnterState(enlistment); // Start the transaction aborting enlistment.Transaction.State.ChangeStateTransactionAborted(enlistment.Transaction, e); // Process Finished InternalEnlistment enlistment.FinishEnlistment(); } internal override void ChangeStatePreparing(InternalEnlistment enlistment) { // If the transaction promotes during phase 0 then the transition to // the promoted phase 0 state for the transaction may cause this // notification to be delivered again. So in this case it should be // ignored. } internal override void InternalAborted(InternalEnlistment enlistment) { VolatileEnlistmentPreparingAborting.EnterState(enlistment); } } // SPC state for a volatile enlistment is the point at which there is exactly 1 enlisment // and it supports SPC. The TM will send a single phase commit to the enlistment and wait // for the response from the TM. internal class VolatileEnlistmentSPC : VolatileEnlistmentState { internal override void EnterState(InternalEnlistment enlistment) { bool spcCommitted = false; // Set the enlistment state enlistment.State = this; // Send Single Phase Commit to the enlistment TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.EnlistmentStatus(enlistment, NotificationCall.SinglePhaseCommit); } Monitor.Exit(enlistment.Transaction); try // Don't hold this lock while calling into the application code. { enlistment.SinglePhaseNotification.SinglePhaseCommit(enlistment.SinglePhaseEnlistment); spcCommitted = true; } finally { if (!spcCommitted) { //If we have an exception thrown in SPC, we don't know the if the enlistment is committed or not //reply indoubt enlistment.SinglePhaseEnlistment.InDoubt(); } Monitor.Enter(enlistment.Transaction); } } internal override void EnlistmentDone(InternalEnlistment enlistment) { VolatileEnlistmentEnded.EnterState(enlistment); enlistment.Transaction.State.ChangeStateTransactionCommitted(enlistment.Transaction); } internal override void Committed(InternalEnlistment enlistment) { VolatileEnlistmentEnded.EnterState(enlistment); enlistment.Transaction.State.ChangeStateTransactionCommitted(enlistment.Transaction); } internal override void Aborted(InternalEnlistment enlistment, Exception e) { VolatileEnlistmentEnded.EnterState(enlistment); enlistment.Transaction.State.ChangeStateTransactionAborted(enlistment.Transaction, e); } internal override void InDoubt(InternalEnlistment enlistment, Exception e) { VolatileEnlistmentEnded.EnterState(enlistment); if (enlistment.Transaction._innerException == null) { enlistment.Transaction._innerException = e; } enlistment.Transaction.State.InDoubtFromEnlistment(enlistment.Transaction); } } // Prepared state for a volatile enlistment is the point at which prepare has been called // and the enlistment has responded prepared. No enlistment operations are valid at this // point. The RM must wait for the TM to take the next action. internal class VolatileEnlistmentPrepared : VolatileEnlistmentState { internal override void EnterState(InternalEnlistment enlistment) { // Set the enlistment state enlistment.State = this; // Wait for Committed } internal override void InternalAborted(InternalEnlistment enlistment) { VolatileEnlistmentAborting.EnterState(enlistment); } internal override void InternalCommitted(InternalEnlistment enlistment) { VolatileEnlistmentCommitting.EnterState(enlistment); } internal override void InternalIndoubt(InternalEnlistment enlistment) { // Change the enlistment state to InDoubt. VolatileEnlistmentInDoubt.EnterState(enlistment); } internal override void ChangeStatePreparing(InternalEnlistment enlistment) { // This would happen in the second pass of a phase 0 wave. } } // Aborting state is when Rollback has been sent to the enlistment. internal class VolatileEnlistmentPreparingAborting : VolatileEnlistmentState { internal override void EnterState(InternalEnlistment enlistment) { // Set the enlistment state enlistment.State = this; } internal override void EnlistmentDone(InternalEnlistment enlistment) { // Move this enlistment to the ended state VolatileEnlistmentEnded.EnterState(enlistment); } internal override void Prepared(InternalEnlistment enlistment) { // The enlistment has respondend so changes it's state to aborting. VolatileEnlistmentAborting.EnterState(enlistment); // Process Finished InternalEnlistment enlistment.FinishEnlistment(); } // The enlistment says to abort start the abort sequence. internal override void ForceRollback(InternalEnlistment enlistment, Exception e) { // Change enlistment state to aborting VolatileEnlistmentEnded.EnterState(enlistment); // Record the exception in the transaction if (enlistment.Transaction._innerException == null) { // Arguably this is the second call to ForceRollback and not the call that // aborted the transaction but just in case. enlistment.Transaction._innerException = e; } // Process Finished InternalEnlistment enlistment.FinishEnlistment(); } internal override void InternalAborted(InternalEnlistment enlistment) { // If this event comes from multiple places just ignore it. Continue // waiting for the enlistment to respond so that we can respond to it. } } // Aborting state is when Rollback has been sent to the enlistment. internal class VolatileEnlistmentAborting : VolatileEnlistmentState { internal override void EnterState(InternalEnlistment enlistment) { // Set the enlistment state enlistment.State = this; Monitor.Exit(enlistment.Transaction); try // Don't hold this lock while calling into the application code. { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.EnlistmentStatus(enlistment, NotificationCall.Rollback); } enlistment.EnlistmentNotification.Rollback(enlistment.SinglePhaseEnlistment); } finally { Monitor.Enter(enlistment.Transaction); } } internal override void ChangeStatePreparing(InternalEnlistment enlistment) { // This enlistment was told to abort before being told to prepare } internal override void EnlistmentDone(InternalEnlistment enlistment) { // Move this enlistment to the ended state VolatileEnlistmentEnded.EnterState(enlistment); } internal override void InternalAborted(InternalEnlistment enlistment) { // Already working on it. } } // Committing state is when Commit has been sent to the enlistment. internal class VolatileEnlistmentCommitting : VolatileEnlistmentState { internal override void EnterState(InternalEnlistment enlistment) { // Set the enlistment state enlistment.State = this; Monitor.Exit(enlistment.Transaction); try // Don't hold this lock while calling into the application code. { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.EnlistmentStatus(enlistment, NotificationCall.Commit); } // Forward the notification to the enlistment enlistment.EnlistmentNotification.Commit(enlistment.Enlistment); } finally { Monitor.Enter(enlistment.Transaction); } } internal override void EnlistmentDone(InternalEnlistment enlistment) { // Move this enlistment to the ended state VolatileEnlistmentEnded.EnterState(enlistment); } } // InDoubt state is for an enlistment that has sent indoubt but has not been responeded to. internal class VolatileEnlistmentInDoubt : VolatileEnlistmentState { internal override void EnterState(InternalEnlistment enlistment) { // Set the enlistment state enlistment.State = this; Monitor.Exit(enlistment.Transaction); try // Don't hold this lock while calling into the application code. { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.EnlistmentStatus(enlistment, NotificationCall.InDoubt); } // Forward the notification to the enlistment enlistment.EnlistmentNotification.InDoubt(enlistment.PreparingEnlistment); } finally { Monitor.Enter(enlistment.Transaction); } } internal override void EnlistmentDone(InternalEnlistment enlistment) { // Move this enlistment to the ended state VolatileEnlistmentEnded.EnterState(enlistment); } } // Ended state is the state that is entered when the transaction has committed, // aborted, or said read only for an enlistment. At this point there are no valid // operations on the enlistment. internal class VolatileEnlistmentEnded : VolatileEnlistmentState { internal override void EnterState(InternalEnlistment enlistment) { // Set the enlistment state enlistment.State = this; // Nothing to do. } internal override void ChangeStatePreparing(InternalEnlistment enlistment) { // This enlistment was told to abort before being told to prepare } internal override void InternalAborted(InternalEnlistment enlistment) { // Ignore this in case the enlistment gets here before // the transaction tells it to do so } internal override void InternalCommitted(InternalEnlistment enlistment) { // Ignore this in case the enlistment gets here before // the transaction tells it to do so } internal override void InternalIndoubt(InternalEnlistment enlistment) { // Ignore this in case the enlistment gets here before // the transaction tells it to do so } internal override void InDoubt(InternalEnlistment enlistment, Exception e) { // Ignore this in case the enlistment gets here before // the transaction tells it to do so } } // At some point either early or late the enlistment responded ReadOnly internal class VolatileEnlistmentDone : VolatileEnlistmentEnded { internal override void EnterState(InternalEnlistment enlistment) { // Set the enlistment state enlistment.State = this; // Nothing to do. } internal override void ChangeStatePreparing(InternalEnlistment enlistment) { enlistment.CheckComplete(); } } }
// Generated by ProtoGen, Version=2.4.1.521, Culture=neutral, PublicKeyToken=17b3b1f090c3ea48. DO NOT EDIT! #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.ProtocolBuffers; using pbc = global::Google.ProtocolBuffers.Collections; using pbd = global::Google.ProtocolBuffers.Descriptors; using scg = global::System.Collections.Generic; namespace Google.ProtocolBuffers.Examples.AddressBook { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class AddressBookProtos { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_tutorial_Person__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.Person, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Builder> internal__static_tutorial_Person__FieldAccessorTable; internal static pbd::MessageDescriptor internal__static_tutorial_Person_PhoneNumber__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.Builder> internal__static_tutorial_Person_PhoneNumber__FieldAccessorTable; internal static pbd::MessageDescriptor internal__static_tutorial_AddressBook__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook, global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook.Builder> internal__static_tutorial_AddressBook__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static AddressBookProtos() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Chp0dXRvcmlhbC9hZGRyZXNzYm9vay5wcm90bxIIdHV0b3JpYWwaJGdvb2ds", "ZS9wcm90b2J1Zi9jc2hhcnBfb3B0aW9ucy5wcm90byLaAQoGUGVyc29uEgwK", "BG5hbWUYASACKAkSCgoCaWQYAiACKAUSDQoFZW1haWwYAyABKAkSKwoFcGhv", "bmUYBCADKAsyHC50dXRvcmlhbC5QZXJzb24uUGhvbmVOdW1iZXIaTQoLUGhv", "bmVOdW1iZXISDgoGbnVtYmVyGAEgAigJEi4KBHR5cGUYAiABKA4yGi50dXRv", "cmlhbC5QZXJzb24uUGhvbmVUeXBlOgRIT01FIisKCVBob25lVHlwZRIKCgZN", "T0JJTEUQABIICgRIT01FEAESCAoEV09SSxACIi8KC0FkZHJlc3NCb29rEiAK", "BnBlcnNvbhgBIAMoCzIQLnR1dG9yaWFsLlBlcnNvbkJFSAHCPkAKK0dvb2ds", "ZS5Qcm90b2NvbEJ1ZmZlcnMuRXhhbXBsZXMuQWRkcmVzc0Jvb2sSEUFkZHJl", "c3NCb29rUHJvdG9z")); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_tutorial_Person__Descriptor = Descriptor.MessageTypes[0]; internal__static_tutorial_Person__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.Person, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Builder>(internal__static_tutorial_Person__Descriptor, new string[] { "Name", "Id", "Email", "Phone", }); internal__static_tutorial_Person_PhoneNumber__Descriptor = internal__static_tutorial_Person__Descriptor.NestedTypes[0]; internal__static_tutorial_Person_PhoneNumber__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.Builder>(internal__static_tutorial_Person_PhoneNumber__Descriptor, new string[] { "Number", "Type", }); internal__static_tutorial_AddressBook__Descriptor = Descriptor.MessageTypes[1]; internal__static_tutorial_AddressBook__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook, global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook.Builder>(internal__static_tutorial_AddressBook__Descriptor, new string[] { "Person", }); pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance(); RegisterAllExtensions(registry); global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.RegisterAllExtensions(registry); return registry; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.Descriptor, }, assigner); } #endregion } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Person : pb::GeneratedMessage<Person, Person.Builder> { private Person() { } private static readonly Person defaultInstance = new Person().MakeReadOnly(); private static readonly string[] _personFieldNames = new string[] { "email", "id", "name", "phone" }; private static readonly uint[] _personFieldTags = new uint[] { 26, 16, 10, 34 }; public static Person DefaultInstance { get { return defaultInstance; } } public override Person DefaultInstanceForType { get { return DefaultInstance; } } protected override Person ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.internal__static_tutorial_Person__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<Person, Person.Builder> InternalFieldAccessors { get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.internal__static_tutorial_Person__FieldAccessorTable; } } #region Nested types [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Types { public enum PhoneType { MOBILE = 0, HOME = 1, WORK = 2, } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class PhoneNumber : pb::GeneratedMessage<PhoneNumber, PhoneNumber.Builder> { private PhoneNumber() { } private static readonly PhoneNumber defaultInstance = new PhoneNumber().MakeReadOnly(); private static readonly string[] _phoneNumberFieldNames = new string[] { "number", "type" }; private static readonly uint[] _phoneNumberFieldTags = new uint[] { 10, 16 }; public static PhoneNumber DefaultInstance { get { return defaultInstance; } } public override PhoneNumber DefaultInstanceForType { get { return DefaultInstance; } } protected override PhoneNumber ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.internal__static_tutorial_Person_PhoneNumber__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<PhoneNumber, PhoneNumber.Builder> InternalFieldAccessors { get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.internal__static_tutorial_Person_PhoneNumber__FieldAccessorTable; } } public const int NumberFieldNumber = 1; private bool hasNumber; private string number_ = ""; public bool HasNumber { get { return hasNumber; } } public string Number { get { return number_; } } public const int TypeFieldNumber = 2; private bool hasType; private global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType type_ = global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType.HOME; public bool HasType { get { return hasType; } } public global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType Type { get { return type_; } } public override bool IsInitialized { get { if (!hasNumber) return false; return true; } } public override void WriteTo(pb::ICodedOutputStream output) { int size = SerializedSize; string[] field_names = _phoneNumberFieldNames; if (hasNumber) { output.WriteString(1, field_names[0], Number); } if (hasType) { output.WriteEnum(2, field_names[1], (int) Type, Type); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasNumber) { size += pb::CodedOutputStream.ComputeStringSize(1, Number); } if (hasType) { size += pb::CodedOutputStream.ComputeEnumSize(2, (int) Type); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } } public static PhoneNumber ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static PhoneNumber ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static PhoneNumber ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static PhoneNumber ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static PhoneNumber ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static PhoneNumber ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static PhoneNumber ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static PhoneNumber ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static PhoneNumber ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static PhoneNumber ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private PhoneNumber MakeReadOnly() { return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(PhoneNumber prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<PhoneNumber, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(PhoneNumber cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private PhoneNumber result; private PhoneNumber PrepareBuilder() { if (resultIsReadOnly) { PhoneNumber original = result; result = new PhoneNumber(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override PhoneNumber MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.Descriptor; } } public override PhoneNumber DefaultInstanceForType { get { return global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.DefaultInstance; } } public override PhoneNumber BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is PhoneNumber) { return MergeFrom((PhoneNumber) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(PhoneNumber other) { if (other == global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.DefaultInstance) return this; PrepareBuilder(); if (other.HasNumber) { Number = other.Number; } if (other.HasType) { Type = other.Type; } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_phoneNumberFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _phoneNumberFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 10: { result.hasNumber = input.ReadString(ref result.number_); break; } case 16: { object unknown; if(input.ReadEnum(ref result.type_, out unknown)) { result.hasType = true; } else if(unknown is int) { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } unknownFields.MergeVarintField(2, (ulong)(int)unknown); } break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasNumber { get { return result.hasNumber; } } public string Number { get { return result.Number; } set { SetNumber(value); } } public Builder SetNumber(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasNumber = true; result.number_ = value; return this; } public Builder ClearNumber() { PrepareBuilder(); result.hasNumber = false; result.number_ = ""; return this; } public bool HasType { get { return result.hasType; } } public global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType Type { get { return result.Type; } set { SetType(value); } } public Builder SetType(global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType value) { PrepareBuilder(); result.hasType = true; result.type_ = value; return this; } public Builder ClearType() { PrepareBuilder(); result.hasType = false; result.type_ = global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType.HOME; return this; } } static PhoneNumber() { object.ReferenceEquals(global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.Descriptor, null); } } } #endregion public const int NameFieldNumber = 1; private bool hasName; private string name_ = ""; public bool HasName { get { return hasName; } } public string Name { get { return name_; } } public const int IdFieldNumber = 2; private bool hasId; private int id_; public bool HasId { get { return hasId; } } public int Id { get { return id_; } } public const int EmailFieldNumber = 3; private bool hasEmail; private string email_ = ""; public bool HasEmail { get { return hasEmail; } } public string Email { get { return email_; } } public const int PhoneFieldNumber = 4; private pbc::PopsicleList<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber> phone_ = new pbc::PopsicleList<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber>(); public scg::IList<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber> PhoneList { get { return phone_; } } public int PhoneCount { get { return phone_.Count; } } public global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber GetPhone(int index) { return phone_[index]; } public override bool IsInitialized { get { if (!hasName) return false; if (!hasId) return false; foreach (global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber element in PhoneList) { if (!element.IsInitialized) return false; } return true; } } public override void WriteTo(pb::ICodedOutputStream output) { int size = SerializedSize; string[] field_names = _personFieldNames; if (hasName) { output.WriteString(1, field_names[2], Name); } if (hasId) { output.WriteInt32(2, field_names[1], Id); } if (hasEmail) { output.WriteString(3, field_names[0], Email); } if (phone_.Count > 0) { output.WriteMessageArray(4, field_names[3], phone_); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasName) { size += pb::CodedOutputStream.ComputeStringSize(1, Name); } if (hasId) { size += pb::CodedOutputStream.ComputeInt32Size(2, Id); } if (hasEmail) { size += pb::CodedOutputStream.ComputeStringSize(3, Email); } foreach (global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber element in PhoneList) { size += pb::CodedOutputStream.ComputeMessageSize(4, element); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } } public static Person ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static Person ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static Person ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static Person ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static Person ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static Person ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static Person ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static Person ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static Person ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static Person ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private Person MakeReadOnly() { phone_.MakeReadOnly(); return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(Person prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<Person, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(Person cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private Person result; private Person PrepareBuilder() { if (resultIsReadOnly) { Person original = result; result = new Person(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override Person MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::Google.ProtocolBuffers.Examples.AddressBook.Person.Descriptor; } } public override Person DefaultInstanceForType { get { return global::Google.ProtocolBuffers.Examples.AddressBook.Person.DefaultInstance; } } public override Person BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is Person) { return MergeFrom((Person) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(Person other) { if (other == global::Google.ProtocolBuffers.Examples.AddressBook.Person.DefaultInstance) return this; PrepareBuilder(); if (other.HasName) { Name = other.Name; } if (other.HasId) { Id = other.Id; } if (other.HasEmail) { Email = other.Email; } if (other.phone_.Count != 0) { result.phone_.Add(other.phone_); } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_personFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _personFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 10: { result.hasName = input.ReadString(ref result.name_); break; } case 16: { result.hasId = input.ReadInt32(ref result.id_); break; } case 26: { result.hasEmail = input.ReadString(ref result.email_); break; } case 34: { input.ReadMessageArray(tag, field_name, result.phone_, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.DefaultInstance, extensionRegistry); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasName { get { return result.hasName; } } public string Name { get { return result.Name; } set { SetName(value); } } public Builder SetName(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasName = true; result.name_ = value; return this; } public Builder ClearName() { PrepareBuilder(); result.hasName = false; result.name_ = ""; return this; } public bool HasId { get { return result.hasId; } } public int Id { get { return result.Id; } set { SetId(value); } } public Builder SetId(int value) { PrepareBuilder(); result.hasId = true; result.id_ = value; return this; } public Builder ClearId() { PrepareBuilder(); result.hasId = false; result.id_ = 0; return this; } public bool HasEmail { get { return result.hasEmail; } } public string Email { get { return result.Email; } set { SetEmail(value); } } public Builder SetEmail(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasEmail = true; result.email_ = value; return this; } public Builder ClearEmail() { PrepareBuilder(); result.hasEmail = false; result.email_ = ""; return this; } public pbc::IPopsicleList<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber> PhoneList { get { return PrepareBuilder().phone_; } } public int PhoneCount { get { return result.PhoneCount; } } public global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber GetPhone(int index) { return result.GetPhone(index); } public Builder SetPhone(int index, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.phone_[index] = value; return this; } public Builder SetPhone(int index, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.phone_[index] = builderForValue.Build(); return this; } public Builder AddPhone(global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.phone_.Add(value); return this; } public Builder AddPhone(global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.phone_.Add(builderForValue.Build()); return this; } public Builder AddRangePhone(scg::IEnumerable<global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber> values) { PrepareBuilder(); result.phone_.Add(values); return this; } public Builder ClearPhone() { PrepareBuilder(); result.phone_.Clear(); return this; } } static Person() { object.ReferenceEquals(global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.Descriptor, null); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class AddressBook : pb::GeneratedMessage<AddressBook, AddressBook.Builder> { private AddressBook() { } private static readonly AddressBook defaultInstance = new AddressBook().MakeReadOnly(); private static readonly string[] _addressBookFieldNames = new string[] { "person" }; private static readonly uint[] _addressBookFieldTags = new uint[] { 10 }; public static AddressBook DefaultInstance { get { return defaultInstance; } } public override AddressBook DefaultInstanceForType { get { return DefaultInstance; } } protected override AddressBook ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.internal__static_tutorial_AddressBook__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<AddressBook, AddressBook.Builder> InternalFieldAccessors { get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.internal__static_tutorial_AddressBook__FieldAccessorTable; } } public const int PersonFieldNumber = 1; private pbc::PopsicleList<global::Google.ProtocolBuffers.Examples.AddressBook.Person> person_ = new pbc::PopsicleList<global::Google.ProtocolBuffers.Examples.AddressBook.Person>(); public scg::IList<global::Google.ProtocolBuffers.Examples.AddressBook.Person> PersonList { get { return person_; } } public int PersonCount { get { return person_.Count; } } public global::Google.ProtocolBuffers.Examples.AddressBook.Person GetPerson(int index) { return person_[index]; } public override bool IsInitialized { get { foreach (global::Google.ProtocolBuffers.Examples.AddressBook.Person element in PersonList) { if (!element.IsInitialized) return false; } return true; } } public override void WriteTo(pb::ICodedOutputStream output) { int size = SerializedSize; string[] field_names = _addressBookFieldNames; if (person_.Count > 0) { output.WriteMessageArray(1, field_names[0], person_); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; foreach (global::Google.ProtocolBuffers.Examples.AddressBook.Person element in PersonList) { size += pb::CodedOutputStream.ComputeMessageSize(1, element); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } } public static AddressBook ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static AddressBook ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static AddressBook ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static AddressBook ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static AddressBook ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static AddressBook ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static AddressBook ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static AddressBook ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static AddressBook ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static AddressBook ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private AddressBook MakeReadOnly() { person_.MakeReadOnly(); return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(AddressBook prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<AddressBook, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(AddressBook cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private AddressBook result; private AddressBook PrepareBuilder() { if (resultIsReadOnly) { AddressBook original = result; result = new AddressBook(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override AddressBook MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook.Descriptor; } } public override AddressBook DefaultInstanceForType { get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook.DefaultInstance; } } public override AddressBook BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is AddressBook) { return MergeFrom((AddressBook) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(AddressBook other) { if (other == global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook.DefaultInstance) return this; PrepareBuilder(); if (other.person_.Count != 0) { result.person_.Add(other.person_); } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_addressBookFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _addressBookFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 10: { input.ReadMessageArray(tag, field_name, result.person_, global::Google.ProtocolBuffers.Examples.AddressBook.Person.DefaultInstance, extensionRegistry); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public pbc::IPopsicleList<global::Google.ProtocolBuffers.Examples.AddressBook.Person> PersonList { get { return PrepareBuilder().person_; } } public int PersonCount { get { return result.PersonCount; } } public global::Google.ProtocolBuffers.Examples.AddressBook.Person GetPerson(int index) { return result.GetPerson(index); } public Builder SetPerson(int index, global::Google.ProtocolBuffers.Examples.AddressBook.Person value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.person_[index] = value; return this; } public Builder SetPerson(int index, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.person_[index] = builderForValue.Build(); return this; } public Builder AddPerson(global::Google.ProtocolBuffers.Examples.AddressBook.Person value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.person_.Add(value); return this; } public Builder AddPerson(global::Google.ProtocolBuffers.Examples.AddressBook.Person.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.person_.Add(builderForValue.Build()); return this; } public Builder AddRangePerson(scg::IEnumerable<global::Google.ProtocolBuffers.Examples.AddressBook.Person> values) { PrepareBuilder(); result.person_.Add(values); return this; } public Builder ClearPerson() { PrepareBuilder(); result.person_.Clear(); return this; } } static AddressBook() { object.ReferenceEquals(global::Google.ProtocolBuffers.Examples.AddressBook.AddressBookProtos.Descriptor, null); } } #endregion } #endregion Designer generated code
using System; namespace OTFontFile { /// <summary> /// Summary description for TableManager. /// </summary> public class TableManager { /************************ * constructors */ public TableManager(OTFile file) { m_file = file; CachedTables = new System.Collections.ArrayList(); } /************************ * public methods */ public OTTable GetTable(OTFont fontOwner, DirectoryEntry de) { // first try getting it from the table cache OTTable table = GetTableFromCache(de); if (table == null) { if ( de.length != 0 && de.offset != 0 && de.offset < m_file.GetFileLength() && de.offset + de.length <= m_file.GetFileLength()) { // read the table from the file MBOBuffer buf = m_file.ReadPaddedBuffer(de.offset, de.length); if (buf != null) { // put the buffer into a table object table = CreateTableObject(de.tag, buf); // add the table to the cache CachedTables.Add(table); } } } return table; } public string GetUnaliasedTableName(OTTag tag) { if (tag == null) return ""; string sName = tag; if (sName == "bloc") { sName = "EBLC"; } else if (sName == "bdat") { sName = "EBDT"; } return sName; } static public string [] GetKnownOTTableTypes() { string [] sTables = { "BASE", "CFF ", "cmap", "cvt ", "DSIG", "EBDT", "EBLC", "EBSC", "fpgm", "gasp", "GDEF", "glyf", "GPOS", "GSUB", "hdmx", "head", "hhea", "hmtx", "JSTF", "kern", "loca", "LTSH", "maxp", "name", "OS/2", "PCLT", "post", "prep", "VDMX", "vhea", "vmtx", "VORG" }; return sTables; } static public bool IsKnownOTTableType(OTTag tag) { bool bFound = false; string [] sTables = GetKnownOTTableTypes(); for (uint i=0; i<sTables.Length; i++) { if (sTables[i] == (string)tag) { bFound = true; break; } } return bFound; } public virtual OTTable CreateTableObject(OTTag tag, MBOBuffer buf) { OTTable table = null; string sName = GetUnaliasedTableName(tag); switch (sName) { case "BASE": table = new Table_BASE(tag, buf); break; case "CFF ": table = new Table_CFF(tag, buf); break; case "cmap": table = new Table_cmap(tag, buf); break; case "cvt ": table = new Table_cvt(tag, buf); break; case "DSIG": table = new Table_DSIG(tag, buf); break; case "EBDT": table = new Table_EBDT(tag, buf); break; case "EBLC": table = new Table_EBLC(tag, buf); break; case "EBSC": table = new Table_EBSC(tag, buf); break; case "fpgm": table = new Table_fpgm(tag, buf); break; case "gasp": table = new Table_gasp(tag, buf); break; case "GDEF": table = new Table_GDEF(tag, buf); break; case "glyf": table = new Table_glyf(tag, buf); break; case "GPOS": table = new Table_GPOS(tag, buf); break; case "GSUB": table = new Table_GSUB(tag, buf); break; case "hdmx": table = new Table_hdmx(tag, buf); break; case "head": table = new Table_head(tag, buf); break; case "hhea": table = new Table_hhea(tag, buf); break; case "hmtx": table = new Table_hmtx(tag, buf); break; case "JSTF": table = new Table_JSTF(tag, buf); break; case "kern": table = new Table_kern(tag, buf); break; case "loca": table = new Table_loca(tag, buf); break; case "LTSH": table = new Table_LTSH(tag, buf); break; case "maxp": table = new Table_maxp(tag, buf); break; case "name": table = new Table_name(tag, buf); break; case "OS/2": table = new Table_OS2(tag, buf); break; case "PCLT": table = new Table_PCLT(tag, buf); break; case "post": table = new Table_post(tag, buf); break; case "prep": table = new Table_prep(tag, buf); break; case "VDMX": table = new Table_VDMX(tag, buf); break; case "vhea": table = new Table_vhea(tag, buf); break; case "vmtx": table = new Table_vmtx(tag, buf); break; case "VORG": table = new Table_VORG(tag, buf); break; //case "Zapf": table = new Table_Zapf(tag, buf); break; default: table = new Table__Unknown(tag, buf); break; } return table; } /************************ * protected methods */ protected OTTable GetTableFromCache(DirectoryEntry de) { OTTable ot = null; for (int i=0; i<CachedTables.Count; i++) { OTTable temp = (OTTable)CachedTables[i]; if (temp.MatchFileOffsetLength(de.offset, de.length)) { ot = temp; break; } } return ot; } /************************ * member data */ OTFile m_file; System.Collections.ArrayList CachedTables; } }
// // XmlDataDocumentTest2.cs // // Author: // Atsushi Enomoto <atsushi@ximian.com> // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Data; using System.IO; using System.Xml; using NUnit.Framework; namespace MonoTests.System.Xml { [TestFixture] public class XmlDataDocumentTest2 : Assertion { string xml = "<NewDataSet><table><row><col1>1</col1><col2>2</col2></row></table></NewDataSet>"; [Test] [ExpectedException (typeof (ArgumentException))] public void TestCtorNullArgs () { new XmlDataDocument (null); } [Test] public void TestDefaultCtor () { XmlDataDocument doc = new XmlDataDocument (); AssertNotNull (doc.DataSet); AssertEquals ("NewDataSet", doc.DataSet.DataSetName); } [Test] [ExpectedException (typeof (InvalidOperationException))] public void TestMultipleLoadError () { DataSet ds = new DataSet (); ds.ReadXml (new XmlTextReader (xml, XmlNodeType.Document, null)); // If there is already data element, Load() fails. XmlDataDocument doc = new XmlDataDocument (ds); doc.LoadXml (xml); } [Test] public void TestMultipleLoadNoError () { DataSet ds = new DataSet (); DataTable dt = new DataTable (); dt.Columns.Add ("col1"); ds.Tables.Add (dt); XmlDataDocument doc = new XmlDataDocument (ds); doc.LoadXml (xml); } [Test] [ExpectedException (typeof (ArgumentException))] public void TestMultipleDataDocFromDataSet () { DataSet ds = new DataSet (); XmlDataDocument doc = new XmlDataDocument (ds); XmlDataDocument doc2 = new XmlDataDocument (ds); } [Test] public void TestLoadXml () { XmlDataDocument doc = new XmlDataDocument (); doc.LoadXml ("<NewDataSet><TestTable><TestRow><TestColumn>1</TestColumn></TestRow></TestTable></NewDataSet>"); doc = new XmlDataDocument (); doc.LoadXml ("<test>value</test>"); } [Test] public void TestCreateElementAndRow () { DataSet ds = new DataSet ("set"); DataTable dt = new DataTable ("tab1"); dt.Columns.Add ("col1"); dt.Columns.Add ("col2"); ds.Tables.Add (dt); DataTable dt2 = new DataTable ("child"); dt2.Columns.Add ("ref"); dt2.Columns.Add ("val"); ds.Tables.Add (dt2); DataRelation rel = new DataRelation ("rel", dt.Columns [0], dt2.Columns [0]); rel.Nested = true; ds.Relations.Add (rel); XmlDataDocument doc = new XmlDataDocument (ds); doc.LoadXml ("<set><tab1><col1>1</col1><col2/><child><ref>1</ref><val>aaa</val></child></tab1></set>"); AssertEquals (1, ds.Tables [0].Rows.Count); AssertEquals (1, ds.Tables [1].Rows.Count); // document element - no mapped row XmlElement el = doc.DocumentElement; AssertNull (doc.GetRowFromElement (el)); // tab1 element - has mapped row el = el.FirstChild as XmlElement; DataRow row = doc.GetRowFromElement (el); AssertNotNull (row); AssertEquals (DataRowState.Added, row.RowState); // col1 - it is column. no mapped row el = el.FirstChild as XmlElement; row = doc.GetRowFromElement (el); AssertNull (row); // col2 - it is column. np mapped row el = el.NextSibling as XmlElement; row = doc.GetRowFromElement (el); AssertNull (row); // child - has mapped row el = el.NextSibling as XmlElement; row = doc.GetRowFromElement (el); AssertNotNull (row); AssertEquals (DataRowState.Added, row.RowState); // created (detached) table 1 element (used later) el = doc.CreateElement ("tab1"); row = doc.GetRowFromElement (el); AssertEquals (DataRowState.Detached, row.RowState); AssertEquals (1, dt.Rows.Count); // not added yet // adding a node before setting EnforceConstraints // raises an error try { doc.DocumentElement.AppendChild (el); Fail ("Invalid Operation should occur; EnforceConstraints prevents addition."); } catch (InvalidOperationException) { } // try again... ds.EnforceConstraints = false; AssertEquals (1, dt.Rows.Count); // not added yet doc.DocumentElement.AppendChild (el); AssertEquals (2, dt.Rows.Count); // added row = doc.GetRowFromElement (el); AssertEquals (DataRowState.Added, row.RowState); // changed // Irrelevant element XmlElement el2 = doc.CreateElement ("hoge"); row = doc.GetRowFromElement (el2); AssertNull (row); // created table 2 element (used later) el = doc.CreateElement ("child"); row = doc.GetRowFromElement (el); AssertEquals (DataRowState.Detached, row.RowState); // Adding it to irrelevant element performs no row state change. AssertEquals (1, dt2.Rows.Count); // not added yet el2.AppendChild (el); AssertEquals (1, dt2.Rows.Count); // still not added row = doc.GetRowFromElement (el); AssertEquals (DataRowState.Detached, row.RowState); // still detached here } // bug #54505 public void TypedDataDocument () { string xml = @"<top xmlns=""urn:test""> <foo> <s>first</s> <d>2004-02-14T10:37:03</d> </foo> <foo> <s>second</s> <d>2004-02-17T12:41:49</d> </foo> </top>"; string xmlschema = @"<xs:schema id=""webstore"" targetNamespace=""urn:test"" xmlns:xs=""http://www.w3.org/2001/XMLSchema""> <xs:element name=""top""> <xs:complexType> <xs:sequence maxOccurs=""unbounded""> <xs:element name=""foo""> <xs:complexType> <xs:sequence maxOccurs=""unbounded""> <xs:element name=""s"" type=""xs:string""/> <xs:element name=""d"" type=""xs:dateTime""/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>"; XmlDataDocument doc = new XmlDataDocument (); doc.DataSet.ReadXmlSchema (new StringReader (xmlschema)); doc.LoadXml (xml); DataTable foo = doc.DataSet.Tables ["foo"]; DataRow newRow = foo.NewRow (); newRow ["s"] = "new"; newRow ["d"] = DateTime.Now; foo.Rows.Add (newRow); doc.Save (new StringWriter ()); } } }
using System; using System.Collections.Generic; using System.Linq; using PholioVisualisation.DataAccess; using PholioVisualisation.DataConstruction; using PholioVisualisation.DataSorting; using PholioVisualisation.PholioObjects; using SpreadsheetGear; namespace PholioVisualisation.Export { /// <summary> /// Builds a Excel file of Practice Profile data. /// </summary> public class PracticeProfileDataBuilder : ExcelFileBuilder { private PracticeProfileDataWriter writer; private PracticeDataAccess practiceReader = new PracticeDataAccess(); private IAreasReader areasReader = ReaderFactory.GetAreasReader(); private IGroupDataReader groupDataReader = ReaderFactory.GetGroupDataReader(); private PholioReader pholioReader = ReaderFactory.GetPholioReader(); private Dictionary<string, Area> practiceCodeToParentMap; private CoreDataSetProviderFactory coreDataSetProviderFactory; // Must be set before BuildWorkbook called public List<int> GroupIds { get; set; } public string AreaCode { get; set; } public int ParentAreaTypeId { get; set; } /// <summary> /// Creates instance to export population data. /// </summary> public PracticeProfileDataBuilder() { } public override IWorkbook BuildWorkbook() { writer = new PracticeProfileDataWriter(ParentAreaTypeId); CheckParameters(); Area area = areasReader.GetAreaFromCode(AreaCode); IList<string> practiceCodes = GetPracticeCodes(area); writer.AddPracticeCodes(practiceCodes); InitPracticeToParentAreaMaps(area, practiceCodes); IList<IndicatorMetadata> metadataList; writer.AddParentsToPracticeSheet(practiceCodeToParentMap, false); IEnumerable<Area> parentAreas = GetUniqueAreaCodesOfValues(practiceCodeToParentMap); parentAreas = from a in parentAreas orderby a.Name select a; writer.AddAreaNamesCodestoParentAreaSheet(parentAreas, ParentAreaTypeId); coreDataSetProviderFactory = new CoreDataSetProviderFactory { CcgPopulationProvider = new CcgPopulationProvider(pholioReader) }; metadataList = AddPopulationData(area, parentAreas); writer.AddIndicatorMetadata(metadataList); AddPracticeAddresses(area, practiceCodes); writer.FinaliseBeforeWrite(); return writer.Workbook; } private IList<IndicatorMetadata> AddPopulationData(Area area, IEnumerable<Area> ccgs) { Grouping grouping = groupDataReader.GetGroupingsByGroupIdAndIndicatorId( GroupIds.First(), // only ever 1 group Id for population data IndicatorIds.QuinaryPopulations); var metadataList = IndicatorMetadataProvider.Instance .GetIndicatorMetadataCollection(grouping) .IndicatorMetadata; IList<int> ageIds = QuinaryPopulationSorter.GetAgeIdsToOver95(); IEnumerable<int> sexIds = new[] { SexIds.Male, SexIds.Female }; var metadata = metadataList.First(); // Why First?? IList<TimePeriod> timePeriods = grouping.GetTimePeriodIterator(metadata.YearType).TimePeriods; var periodLabels = GetPeriodLabels(metadata, timePeriods); AddPopulationTitles(sexIds, ageIds, periodLabels); foreach (TimePeriod timePeriod in timePeriods) { foreach (int sexId in sexIds) { grouping.SexId = sexId; foreach (int ageId in ageIds) { grouping.AgeId = ageId; // Add data writer.AddPracticeIndicatorValues(GetPracticeDataMap(area, grouping, timePeriod)); } } } foreach (var ccg in ccgs) { List<QuinaryPopulation> populations = new List<QuinaryPopulation>(); foreach (TimePeriod timePeriod in timePeriods) { foreach (int sexId in sexIds) { // Get all populations populations.Add(practiceReader.GetCcgQuinaryPopulation(grouping.IndicatorId, timePeriod, ccg.Code, sexId)); } } writer.AddCcgPopulationValues(populations); } writer.AddIndicatorMetadata(metadataList); return metadataList; } private static IList<string> GetPeriodLabels(IndicatorMetadata metadata, IList<TimePeriod> timePeriods) { var builder = new TimePeriodTextListBuilder(metadata); builder.AddRange(timePeriods); IList<string> periodLabels = builder.GetTimePeriodStrings(); return periodLabels; } /// <summary> /// Check required parameters have been set. /// </summary> private void CheckParameters() { if (GroupIds.Count == 0) { throw new ArgumentException("GroupId is not set"); } if (AreaCode == null) { throw new ArgumentException("AreaCode is not set"); } if (ParentAreaTypeId == -1) { throw new ArgumentException("AreaTypeId is not set"); } } private void AddPopulationTitles(IEnumerable<int> sexIds, IList<int> ageIds, IList<string> periodLabels) { IList<string> populationLabels = ReaderFactory.GetPholioReader().GetQuinaryPopulationLabels(ageIds); PholioLabelReader labelReader = new PholioLabelReader(); IList<string> sexLabels = sexIds.Select(labelReader.LookUpSexLabel).ToList(); writer.AddPopulationTitles(sexLabels, periodLabels, populationLabels); } private IList<IndicatorMetadata> AddTopicData(Area area, IEnumerable<Area> parentAreas) { IndicatorMetadataCollection allMetadata = new IndicatorMetadataCollection(); foreach (var groupId in GroupIds) { IList<Grouping> groupings = groupDataReader.GetGroupingsByGroupId(groupId); IList<GroupRoot> roots = new GroupRootBuilder(groupDataReader).BuildGroupRoots(groupings); IndicatorMetadataCollection metadataCollection = IndicatorMetadataProvider.Instance.GetIndicatorMetadataCollection(groupings); allMetadata.AddIndicatorMetadata(metadataCollection.IndicatorMetadata); foreach (GroupRoot root in roots) { Grouping grouping = root.FirstGrouping; // Add indicator information IndicatorMetadata metadata = metadataCollection.GetIndicatorMetadataById(grouping.IndicatorId); IList<TimePeriod> periods = grouping.GetTimePeriodIterator(metadata.YearType).TimePeriods; writer.AddPracticeIndicatorTitles(metadata, periods); writer.AddCcgIndicatorTitles(metadata, periods); foreach (TimePeriod timePeriod in periods) { // Add data writer.AddPracticeIndicatorData(GetPracticeDataMap(area, grouping, timePeriod)); writer.AddAreaIndicatorData(GetParentAreaDataMap(grouping, timePeriod, parentAreas, metadata)); } } } return allMetadata.IndicatorMetadata; } private Dictionary<string, CoreDataSet> GetPracticeDataMap(Area area, Grouping grouping, TimePeriod timePeriod) { Dictionary<string, CoreDataSet> dataMap; if (area.IsCountry) { dataMap = practiceReader.GetPracticeCodeToBaseDataMap(grouping, timePeriod); } else if (area.IsGpPractice) { dataMap = new Dictionary<string, CoreDataSet>(); CoreDataSet data = groupDataReader.GetCoreData(grouping, timePeriod, area.Code).FirstOrDefault(); if (data != null && data.IsValueValid) { dataMap.Add(area.Code, data); } } else { dataMap = practiceReader.GetPracticeCodeToBaseDataMap(grouping, timePeriod, area.Code); } return dataMap; } private Dictionary<string, CoreDataSet> GetParentAreaDataMap(Grouping grouping, TimePeriod timePeriod, IEnumerable<Area> parentAreas, IndicatorMetadata indicatorMetadata) { var areaDataMap = new Dictionary<string, CoreDataSet>(); foreach (var parentArea in parentAreas) { var coreDataSet = coreDataSetProviderFactory.New(parentArea) .GetData(grouping, timePeriod, indicatorMetadata); if (coreDataSet != null && coreDataSet.IsValueValid) { areaDataMap.Add(parentArea.Code, coreDataSet); } } return areaDataMap; } private void InitPracticeToParentAreaMaps(Area area, IList<string> practiceCodes) { if (area.IsCountry) { // Add all Areas practiceCodeToParentMap = areasReader.GetParentsFromChildAreaIdAndParentAreaTypeId(ParentAreaTypeId, AreaTypeIds.GpPractice); } else if (area.IsGpPractice) { practiceCodeToParentMap = new Dictionary<string, Area>(); var code = area.Code; IList<Area> parentAreas = areasReader.GetParentAreas(code); AddCcgParent(practiceCodeToParentMap, code, parentAreas); } else if (area.IsCounty || area.IsUa || area.IsCcg) { practiceCodeToParentMap = new Dictionary<string, Area>(); foreach (var code in practiceCodes) { IList<Area> parentAreas = areasReader.GetParentAreas(code); if (area.IsCounty) { AddCountyParent(practiceCodeToParentMap, code, parentAreas); } else if (area.IsUa) { AddUaParent(practiceCodeToParentMap, code, parentAreas); } else { AddCcgParent(practiceCodeToParentMap, code, parentAreas); } } } } private void AddPracticeAddresses(Area area, IList<string> practiceCodes) { IList<AreaAddress> practiceAddresses; if (area.IsGpPractice) { practiceAddresses = new List<AreaAddress>(); AddAddressToList(area.Code, practiceAddresses); } else if (area.IsCountry) { practiceAddresses = areasReader.GetAreaWithAddressByAreaTypeId(AreaTypeIds.GpPractice); } else { practiceAddresses = new List<AreaAddress>(); foreach (var practiceCode in practiceCodes) { AddAddressToList(practiceCode, practiceAddresses); } } Dictionary<string, AreaAddress> practiceCodeToAddressMap = practiceAddresses.ToDictionary(a => a.Code); writer.AddPracticeAddresses(practiceCodeToAddressMap); } private void AddAddressToList(string areaCode, IList<AreaAddress> practiceAddresses) { AreaAddress address = areasReader.GetAreaWithAddressFromCode(areaCode); if (address != null) { practiceAddresses.Add(address); } } private static void AddCcgParent(Dictionary<string, Area> map, string code, IList<Area> parentAreas) { var area = parentAreas.FirstOrDefault(a => AreaType.IsCcgAreaTypeId(a.AreaTypeId)); AddArea(area, map, code); } private static void AddUaParent(Dictionary<string, Area> map, string code, IList<Area> parentAreas) { var area = parentAreas.FirstOrDefault(a => a.AreaTypeId == AreaTypeIds.UnitaryAuthority); AddArea(area, map, code); } private static void AddCountyParent(Dictionary<string, Area> map, string code, IList<Area> parentAreas) { var area = parentAreas.FirstOrDefault(a => a.AreaTypeId == AreaTypeIds.County); AddArea(area, map, code); } private static void AddArea(Area area, Dictionary<string, Area> map, string code) { if (area != null && map.ContainsKey(code) == false) { map.Add(code, area); } } private static IEnumerable<Area> GetUniqueAreaCodesOfValues(Dictionary<string, Area> practiceCodeToParentMap) { return practiceCodeToParentMap == null ? new List<Area>() : practiceCodeToParentMap.Values .GroupBy(a => a.Code) .Select(a => a.First()); } private IList<string> GetPracticeCodes(Area area) { if (area.IsCountry) { return areasReader.GetAreaCodesForAreaType(AreaTypeIds.GpPractice); } if (area.IsGpPractice) { return new List<string> { AreaCode }; } // CCG return areasReader.GetChildAreaCodes(AreaCode, AreaTypeIds.GpPractice); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================================= ** ** ** ** ** ** Purpose: For Assembly-related custom attributes. ** ** =============================================================================*/ namespace System.Reflection { using System; using System.Configuration.Assemblies; using System.Diagnostics.Contracts; [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyCopyrightAttribute : Attribute { private String m_copyright; public AssemblyCopyrightAttribute(String copyright) { m_copyright = copyright; } public String Copyright { get { return m_copyright; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyTrademarkAttribute : Attribute { private String m_trademark; public AssemblyTrademarkAttribute(String trademark) { m_trademark = trademark; } public String Trademark { get { return m_trademark; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyProductAttribute : Attribute { private String m_product; public AssemblyProductAttribute(String product) { m_product = product; } public String Product { get { return m_product; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyCompanyAttribute : Attribute { private String m_company; public AssemblyCompanyAttribute(String company) { m_company = company; } public String Company { get { return m_company; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyDescriptionAttribute : Attribute { private String m_description; public AssemblyDescriptionAttribute(String description) { m_description = description; } public String Description { get { return m_description; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyTitleAttribute : Attribute { private String m_title; public AssemblyTitleAttribute(String title) { m_title = title; } public String Title { get { return m_title; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyConfigurationAttribute : Attribute { private String m_configuration; public AssemblyConfigurationAttribute(String configuration) { m_configuration = configuration; } public String Configuration { get { return m_configuration; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyDefaultAliasAttribute : Attribute { private String m_defaultAlias; public AssemblyDefaultAliasAttribute(String defaultAlias) { m_defaultAlias = defaultAlias; } public String DefaultAlias { get { return m_defaultAlias; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyInformationalVersionAttribute : Attribute { private String m_informationalVersion; public AssemblyInformationalVersionAttribute(String informationalVersion) { m_informationalVersion = informationalVersion; } public String InformationalVersion { get { return m_informationalVersion; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyFileVersionAttribute : Attribute { private String _version; public AssemblyFileVersionAttribute(String version) { if (version == null) throw new ArgumentNullException("version"); Contract.EndContractBlock(); _version = version; } public String Version { get { return _version; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public unsafe sealed class AssemblyCultureAttribute : Attribute { private String m_culture; public AssemblyCultureAttribute(String culture) { m_culture = culture; } public String Culture { get { return m_culture; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public unsafe sealed class AssemblyVersionAttribute : Attribute { private String m_version; public AssemblyVersionAttribute(String version) { m_version = version; } public String Version { get { return m_version; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyKeyFileAttribute : Attribute { private String m_keyFile; public AssemblyKeyFileAttribute(String keyFile) { m_keyFile = keyFile; } public String KeyFile { get { return m_keyFile; } } } [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyDelaySignAttribute : Attribute { private bool m_delaySign; public AssemblyDelaySignAttribute(bool delaySign) { m_delaySign = delaySign; } public bool DelaySign { get { return m_delaySign; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public unsafe sealed class AssemblyAlgorithmIdAttribute : Attribute { private uint m_algId; public AssemblyAlgorithmIdAttribute(AssemblyHashAlgorithm algorithmId) { m_algId = (uint) algorithmId; } [CLSCompliant(false)] public AssemblyAlgorithmIdAttribute(uint algorithmId) { m_algId = algorithmId; } [CLSCompliant(false)] public uint AlgorithmId { get { return m_algId; } } } [AttributeUsage(AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public unsafe sealed class AssemblyFlagsAttribute : Attribute { private AssemblyNameFlags m_flags; [Obsolete("This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. http://go.microsoft.com/fwlink/?linkid=14202")] [CLSCompliant(false)] public AssemblyFlagsAttribute(uint flags) { m_flags = (AssemblyNameFlags)flags; } [Obsolete("This property has been deprecated. Please use AssemblyFlags instead. http://go.microsoft.com/fwlink/?linkid=14202")] [CLSCompliant(false)] public uint Flags { get { return (uint)m_flags; } } // This, of course, should be typed as AssemblyNameFlags. The compat police don't allow such changes. public int AssemblyFlags { get { return (int)m_flags; } } [Obsolete("This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. http://go.microsoft.com/fwlink/?linkid=14202")] public AssemblyFlagsAttribute(int assemblyFlags) { m_flags = (AssemblyNameFlags)assemblyFlags; } public AssemblyFlagsAttribute(AssemblyNameFlags assemblyFlags) { m_flags = assemblyFlags; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true, Inherited=false)] public sealed class AssemblyMetadataAttribute : Attribute { private String m_key; private String m_value; public AssemblyMetadataAttribute(string key, string value) { m_key = key; m_value = value; } public string Key { get { return m_key; } } public string Value { get { return m_value;} } } #if FEATURE_STRONGNAME_MIGRATION [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple=false)] public sealed class AssemblySignatureKeyAttribute : Attribute { private String _publicKey; private String _countersignature; public AssemblySignatureKeyAttribute(String publicKey, String countersignature) { _publicKey = publicKey; _countersignature = countersignature; } public String PublicKey { get { return _publicKey; } } public String Countersignature { get { return _countersignature; } } } #endif [AttributeUsage (AttributeTargets.Assembly, Inherited=false)] [System.Runtime.InteropServices.ComVisible(true)] public sealed class AssemblyKeyNameAttribute : Attribute { private String m_keyName; public AssemblyKeyNameAttribute(String keyName) { m_keyName = keyName; } public String KeyName { get { return m_keyName; } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Moq; using Newtonsoft.Json; using NUnit.Framework; using QuantConnect.Brokerages; using QuantConnect.Brokerages.GDAX; using QuantConnect.Interfaces; using QuantConnect.Orders; using RestSharp; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading; using QuantConnect.Util; using Order = QuantConnect.Orders.Order; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Lean.Engine.DataFeeds; namespace QuantConnect.Tests.Brokerages.GDAX { [TestFixture, Parallelizable(ParallelScope.Fixtures)] public class GDAXBrokerageTests { #region Declarations private GDAXFakeDataQueueHandler _unit; private readonly Mock<IWebSocket> _wss = new Mock<IWebSocket>(); private readonly Mock<IRestClient> _rest = new Mock<IRestClient>(); private readonly Mock<IAlgorithm> _algo = new Mock<IAlgorithm>(); private string _openOrderData; private string _fillData; private string _accountsData; private string _holdingData; private string _tickerData; private Symbol _symbol; private const string BrokerId = "d0c5340b-6d6c-49d9-b567-48c4bfca13d2"; private const string MatchBrokerId = "132fb6ae-456b-4654-b4e0-d681ac05cea1"; private const AccountType AccountType = QuantConnect.AccountType.Margin; #endregion [SetUp] public void Setup() { var priceProvider = new Mock<IPriceProvider>(); priceProvider.Setup(x => x.GetLastPrice(It.IsAny<Symbol>())).Returns(1.234m); _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => r.Resource.StartsWith("/products/")))) .Returns(new RestResponse { Content = File.ReadAllText("TestData//gdax_tick.txt"), StatusCode = HttpStatusCode.OK }); _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => r.Resource == "/orders" && r.Method == Method.GET))) .Returns(new RestResponse { Content = "[]", StatusCode = HttpStatusCode.OK }); _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => r.Resource == "/orders" && r.Method == Method.POST))) .Returns(new RestResponse { Content = File.ReadAllText("TestData//gdax_order.txt"), StatusCode = HttpStatusCode.OK }); _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => r.Resource.StartsWith("/orders/" + BrokerId) || r.Resource.StartsWith("/orders/" + MatchBrokerId)))) .Returns(new RestResponse { Content = File.ReadAllText("TestData//gdax_orderById.txt"), StatusCode = HttpStatusCode.OK }); _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => r.Resource == "/fills"))) .Returns(new RestResponse { Content = "[]", StatusCode = HttpStatusCode.OK }); _unit = new GDAXFakeDataQueueHandler("wss://localhost", _wss.Object, _rest.Object, "abc", "MTIz", "pass", _algo.Object, priceProvider.Object, new AggregationManager()); _fillData = File.ReadAllText("TestData//gdax_fill.txt"); _openOrderData = File.ReadAllText("TestData//gdax_openOrders.txt"); _accountsData = File.ReadAllText("TestData//gdax_accounts.txt"); _holdingData = File.ReadAllText("TestData//gdax_holding.txt"); _tickerData = File.ReadAllText("TestData//gdax_ticker.txt"); _symbol = Symbol.Create("BTCUSD", SecurityType.Crypto, Market.GDAX); _algo.Setup(a => a.BrokerageModel.AccountType).Returns(AccountType); _algo.Setup(a => a.AccountCurrency).Returns(Currencies.USD); } [TearDown] public void TearDown() { _unit.Disconnect(); _unit.DisposeSafely(); } private void SetupResponse(string body, HttpStatusCode httpStatus = HttpStatusCode.OK) { _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => !r.Resource.StartsWith("/products/") && !r.Resource.StartsWith("/orders/" + BrokerId)))) .Returns(new RestResponse { Content = body, StatusCode = httpStatus }); } [Test] public void IsConnectedTest() { _wss.Setup(w => w.IsOpen).Returns(true); Assert.IsTrue(_unit.IsConnected); _wss.Setup(w => w.IsOpen).Returns(false); Assert.IsFalse(_unit.IsConnected); } [Test] public void ConnectTest() { SetupResponse(_accountsData); _wss.Setup(m => m.Connect()).Raises(m => m.Open += null, EventArgs.Empty).Verifiable(); _wss.Setup(m => m.IsOpen).Returns(false); _unit.Connect(); _wss.Verify(); } [Test] public void DisconnectTest() { _wss.Setup(m => m.Close()).Verifiable(); _wss.Setup(m => m.IsOpen).Returns(true); _unit.Disconnect(); _wss.Verify(); } [Test] public void OnOrderFillTest() { const decimal orderQuantity = 6.1m; _unit.PlaceOrder(new MarketOrder(Symbols.BTCUSD, orderQuantity, DateTime.UtcNow) { // set the quote currency here to prevent the test from accessing algorithm.Securities PriceCurrency = "USD" }); _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => r.Resource == "/fills"))) .Returns(new RestResponse { Content = _fillData, StatusCode = HttpStatusCode.OK }); var raised = new ManualResetEvent(false); var isFilled = false; var actualFee = 0m; var actualQuantity = 0m; _unit.OrderStatusChanged += (s, e) => { Assert.AreEqual("BTCUSD", e.Symbol.Value); actualFee += e.OrderFee.Value.Amount; Assert.AreEqual(Currencies.USD, e.OrderFee.Value.Currency); actualQuantity += e.AbsoluteFillQuantity; Assert.IsTrue(actualQuantity != orderQuantity); Assert.AreEqual(OrderStatus.PartiallyFilled, e.Status); Assert.AreEqual(5.23512, e.FillQuantity); Assert.AreEqual(12, actualFee); isFilled = true; raised.Set(); }; raised.WaitOne(3000); raised.DisposeSafely(); Assert.IsTrue(isFilled); } [Test] public void GetAuthenticationTokenTest() { var actual = _unit.GetAuthenticationToken("", "POST", "http://localhost"); Assert.IsFalse(string.IsNullOrEmpty(actual.Signature)); Assert.IsFalse(string.IsNullOrEmpty(actual.Timestamp)); Assert.AreEqual("pass", actual.Passphrase); Assert.AreEqual("abc", actual.Key); } [TestCase("1", HttpStatusCode.OK, OrderStatus.Submitted, 1.23, 0, OrderType.Market)] [TestCase("1", HttpStatusCode.OK, OrderStatus.Submitted, -1.23, 0, OrderType.Market)] [TestCase("1", HttpStatusCode.OK, OrderStatus.Submitted, 1.23, 1234.56, OrderType.Limit)] [TestCase("1", HttpStatusCode.OK, OrderStatus.Submitted, -1.23, 1234.56, OrderType.Limit)] [TestCase("1", HttpStatusCode.OK, OrderStatus.Submitted, 1.23, 1234.56, OrderType.StopMarket)] [TestCase("1", HttpStatusCode.OK, OrderStatus.Submitted, -1.23, 1234.56, OrderType.StopMarket)] [TestCase(null, HttpStatusCode.BadRequest, OrderStatus.Invalid, 1.23, 1234.56, OrderType.Market)] [TestCase(null, HttpStatusCode.BadRequest, OrderStatus.Invalid, 1.23, 1234.56, OrderType.Limit)] [TestCase(null, HttpStatusCode.BadRequest, OrderStatus.Invalid, 1.23, 1234.56, OrderType.StopMarket)] public void PlaceOrderTest(string orderId, HttpStatusCode httpStatus, OrderStatus status, decimal quantity, decimal price, OrderType orderType) { var response = new { id = BrokerId, fill_fees = "0.11" }; SetupResponse(JsonConvert.SerializeObject(response), httpStatus); _unit.OrderStatusChanged += (s, e) => { Assert.AreEqual(status, e.Status); if (orderId != null) { Assert.AreEqual("BTCUSD", e.Symbol.Value); Assert.That((quantity > 0 && e.Direction == OrderDirection.Buy) || (quantity < 0 && e.Direction == OrderDirection.Sell)); Assert.IsTrue(orderId == null || _unit.CachedOrderIDs.SelectMany(c => c.Value.BrokerId.Where(b => b == BrokerId)).Any()); } }; Order order; if (orderType == OrderType.Limit) { order = new LimitOrder(_symbol, quantity, price, DateTime.UtcNow); } else if (orderType == OrderType.Market) { order = new MarketOrder(_symbol, quantity, DateTime.UtcNow); } else { order = new StopMarketOrder(_symbol, quantity, price, DateTime.UtcNow); } var actual = _unit.PlaceOrder(order); Assert.IsTrue(actual || (orderId == null && !actual)); } [Test] public void GetOpenOrdersTest() { SetupResponse(_openOrderData); _unit.CachedOrderIDs.TryAdd(1, new MarketOrder { BrokerId = new List<string> { "1" }, Price = 123 }); var actual = _unit.GetOpenOrders(); Assert.AreEqual(2, actual.Count); Assert.AreEqual(0.01, actual.First().Quantity); Assert.AreEqual(OrderDirection.Buy, actual.First().Direction); Assert.AreEqual(0.1, actual.First().Price); Assert.AreEqual(-1, actual.Last().Quantity); Assert.AreEqual(OrderDirection.Sell, actual.Last().Direction); Assert.AreEqual(1, actual.Last().Price); } [Test] public void GetTickTest() { var actual = _unit.GetTick(_symbol); Assert.AreEqual(333.98m, actual.BidPrice); Assert.AreEqual(333.99m, actual.AskPrice); Assert.AreEqual(5957.11914015, actual.Quantity); } [Test] public void GetCashBalanceTest() { SetupResponse(_accountsData); var actual = _unit.GetCashBalance(); Assert.AreEqual(2, actual.Count); var usd = actual.Single(a => a.Currency == Currencies.USD); var btc = actual.Single(a => a.Currency == "BTC"); Assert.AreEqual(80.2301373066930000m, usd.Amount); Assert.AreEqual(1.1, btc.Amount); } [Test, Ignore("Holdings are now set to 0 swaps at the start of each launch. Not meaningful.")] public void GetAccountHoldingsTest() { SetupResponse(_holdingData); _unit.CachedOrderIDs.TryAdd(1, new MarketOrder { BrokerId = new List<string> { "1" }, Price = 123 }); var actual = _unit.GetAccountHoldings(); Assert.AreEqual(0, actual.Count); } [TestCase(HttpStatusCode.OK, HttpStatusCode.NotFound, false)] [TestCase(HttpStatusCode.OK, HttpStatusCode.OK, true)] public void CancelOrderTest(HttpStatusCode code, HttpStatusCode code2, bool expected) { _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => !r.Resource.EndsWith("1")))) .Returns(new RestResponse { StatusCode = code }); _rest.Setup(m => m.Execute(It.Is<IRestRequest>(r => !r.Resource.EndsWith("2")))) .Returns(new RestResponse { StatusCode = code2 }); var actual = _unit.CancelOrder(new LimitOrder { BrokerId = new List<string> { "1", "2" } }); Assert.AreEqual(expected, actual); } [Test] public void UpdateOrderTest() { Assert.Throws<NotSupportedException>(() => _unit.UpdateOrder(new LimitOrder())); } [Test] public void SubscribeTest() { string actual = null; _wss.Setup(w => w.Send(It.IsAny<string>())).Callback<string>(c => actual = c); var gotBTCUSD = false; var gotGBPUSD = false; var gotETHBTC = false; _unit.Subscribe(GetSubscriptionDataConfig<Tick>(Symbol.Create("BTCUSD", SecurityType.Crypto, Market.GDAX), Resolution.Tick), (s, e) => { gotBTCUSD = true; }); StringAssert.Contains("[\"BTC-USD\"]", actual); _unit.Subscribe(GetSubscriptionDataConfig<Tick>(Symbol.Create("GBPUSD", SecurityType.Forex, Market.FXCM), Resolution.Tick), (s, e) => { gotGBPUSD = true; }); _unit.Subscribe(GetSubscriptionDataConfig<Tick>(Symbol.Create("ETHBTC", SecurityType.Crypto, Market.GDAX), Resolution.Tick), (s, e) => { gotETHBTC = true; }); StringAssert.Contains("[\"BTC-USD\",\"ETH-BTC\"]", actual); Thread.Sleep(1000); Assert.IsFalse(gotBTCUSD); Assert.IsTrue(gotGBPUSD); Assert.IsFalse(gotETHBTC); } [Test] public void UnsubscribeTest() { string actual = null; _wss.Setup(w => w.IsOpen).Returns(true); _wss.Setup(w => w.Send(It.IsAny<string>())).Callback<string>(c => actual = c); _unit.Unsubscribe(new List<Symbol> { Symbol.Create("BTCUSD", SecurityType.Crypto, Market.GDAX) }); StringAssert.Contains("user", actual); StringAssert.Contains("heartbeat", actual); StringAssert.DoesNotContain("matches", actual); } [Test] public void PollTickTest() { var gotGBPUSD = false; var enumerator = _unit.Subscribe(GetSubscriptionDataConfig<Tick>(Symbol.Create("GBPUSD", SecurityType.Forex, Market.FXCM), Resolution.Tick), (s, e) => { gotGBPUSD = true; }); Thread.Sleep(1000); // conversion rate is the price returned by the QC pricing API Assert.IsTrue(gotGBPUSD); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(1.234m, enumerator.Current.Price); } [Test] public void InvalidSymbolSubscribeTest() { string actual = null; _wss.Setup(w => w.Send(It.IsAny<string>())).Callback<string>(c => actual = c); // subscribe to invalid symbol _unit.Subscribe(new[] { Symbol.Create("BTCLTC", SecurityType.Crypto, Market.GDAX) }); // subscribe is not called for invalid symbols Assert.IsNull(actual); } private SubscriptionDataConfig GetSubscriptionDataConfig<T>(Symbol symbol, Resolution resolution) { return new SubscriptionDataConfig( typeof(T), symbol, resolution, TimeZones.Utc, TimeZones.Utc, true, true, false); } private class GDAXFakeDataQueueHandler : GDAXDataQueueHandler { protected override string[] ChannelNames => new[] { "heartbeat", "user" }; public GDAXFakeDataQueueHandler(string wssUrl, IWebSocket websocket, IRestClient restClient, string apiKey, string apiSecret, string passPhrase, IAlgorithm algorithm, IPriceProvider priceProvider, IDataAggregator aggregator) : base(wssUrl, websocket, restClient, apiKey, apiSecret, passPhrase, algorithm, priceProvider, aggregator, null) { } } } }
/* * TokenNFA.cs */ using System; namespace Core.Library { /** * A non-deterministic finite state automaton (NFA) for matching * tokens. It supports both fixed strings and simple regular * expressions, but should perform similar to a DFA due to highly * optimized data structures and tuning. The memory footprint during * matching should be near zero, since no heap memory is allocated * unless the pre-allocated queues need to be enlarged. The NFA also * does not use recursion, but iterates in a loop instead. * * * */ internal class TokenNFA { /** * The initial state lookup table, indexed by the first ASCII * character. This array is used to for speed optimizing the * first step in the match, since the initial state would * otherwise have a long list of transitions to consider. */ private NFAState[] initialChar = new NFAState[128]; /** * The initial state. This state contains any transitions not * already stored in the initial text state array, i.e. non-ASCII * or complex transitions (such as regular expressions). */ private NFAState initial = new NFAState(); /** * The NFA state queue to use. */ private NFAStateQueue queue = new NFAStateQueue(); /** * Adds a string match to this automaton. New states and * transitions will be added to extend this automaton to support * the specified string. * * @param str the string to match * @param ignoreCase the case-insensitive match flag * @param value the match value */ public void AddTextMatch(string str, bool ignoreCase, TokenPattern value) { NFAState state; char ch = str[0]; if (ch < 128 && !ignoreCase) { state = initialChar[ch]; if (state == null) { state = initialChar[ch] = new NFAState(); } } else { state = initial.AddOut(ch, ignoreCase, null); } for (int i = 1; i < str.Length; i++) { state = state.AddOut(str[i], ignoreCase, null); } state.value = value; } /** * Adds a regular expression match to this automaton. New states * and transitions will be added to extend this automaton to * support the specified string. Note that this method only * supports a subset of the full regular expression syntax, so * a more complete regular expression library must also be * provided. * * @param pattern the regular expression string * @param ignoreCase the case-insensitive match flag * @param value the match value * * @throws RegExpException if the regular expression parsing * failed */ public void AddRegExpMatch(string pattern, bool ignoreCase, TokenPattern value) { TokenRegExpParser parser = new TokenRegExpParser(pattern, ignoreCase); string debug = "DFA regexp; " + parser.GetDebugInfo(); bool isAscii; isAscii = parser.start.IsAsciiOutgoing(); for (int i = 0; isAscii && i < 128; i++) { bool match = false; for (int j = 0; j < parser.start.outgoing.Length; j++) { if (parser.start.outgoing[j].Match((char) i)) { if (match) { isAscii = false; break; } match = true; } } if (match && initialChar[i] != null) { isAscii = false; } } if (parser.start.incoming.Length > 0) { initial.AddOut(new NFAEpsilonTransition(parser.start)); debug += ", uses initial epsilon"; } else if (isAscii && !ignoreCase) { for (int i = 0; isAscii && i < 128; i++) { for (int j = 0; j < parser.start.outgoing.Length; j++) { if (parser.start.outgoing[j].Match((char) i)) { initialChar[i] = parser.start.outgoing[j].state; } } } debug += ", uses ASCII lookup"; } else { parser.start.MergeInto(initial); debug += ", uses initial state"; } parser.end.value = value; value.DebugInfo = debug; } /** * Checks if this NFA matches the specified input text. The * matching will be performed from position zero (0) in the * buffer. This method will not read any characters from the * stream, just peek ahead. * * @param buffer the input buffer to check * @param match the token match to update * * @return the number of characters matched, or * zero (0) if no match was found * * @throws IOException if an I/O error occurred */ public int Match(ReaderBuffer buffer, TokenMatch match) { int length = 0; int pos = 1; int peekChar; NFAState state; // The first step of the match loop has been unrolled and // optimized for performance below. this.queue.Clear(); peekChar = buffer.Peek(0); if (0 <= peekChar && peekChar < 128) { state = this.initialChar[peekChar]; if (state != null) { this.queue.AddLast(state); } } if (peekChar >= 0) { this.initial.MatchTransitions((char) peekChar, this.queue, true); } this.queue.MarkEnd(); peekChar = buffer.Peek(1); // The remaining match loop processes all subsequent states while (!this.queue.Empty) { if (this.queue.Marked) { pos++; peekChar = buffer.Peek(pos); this.queue.MarkEnd(); } state = this.queue.RemoveFirst(); if (state.value != null) { match.Update(pos, state.value); } if (peekChar >= 0) { state.MatchTransitions((char) peekChar, this.queue, false); } } return length; } } /** * An NFA state. The NFA consists of a series of states, each * having zero or more transitions to other states. */ internal class NFAState { /** * The optional state value (if it is a final state). */ internal TokenPattern value = null; /** * The incoming transitions to this state. */ internal NFATransition[] incoming = new NFATransition[0]; /** * The outgoing transitions from this state. */ internal NFATransition[] outgoing = new NFATransition[0]; /** * The outgoing epsilon transitions flag. */ internal bool epsilonOut = false; /** * Checks if this state has any incoming or outgoing * transitions. * * @return true if this state has transitions, or * false otherwise */ public bool HasTransitions() { return incoming.Length > 0 || outgoing.Length > 0; } /** * Checks if all outgoing transitions only match ASCII * characters. * * @return true if all transitions are ASCII-only, or * false otherwise */ public bool IsAsciiOutgoing() { for (int i = 0; i < outgoing.Length; i++) { if (!outgoing[i].IsAscii()) { return false; } } return true; } /** * Adds a new incoming transition. * * @param trans the transition to add */ public void AddIn(NFATransition trans) { Array.Resize(ref incoming, incoming.Length + 1); incoming[incoming.Length - 1] = trans; } /** * Adds a new outgoing character transition. If the target * state specified was null and an identical transition * already exists, it will be reused and its target returned. * * @param ch he character to match * @param ignoreCase the case-insensitive flag * @param state the target state, or null * * @return the transition target state */ public NFAState AddOut(char ch, bool ignoreCase, NFAState state) { if (ignoreCase) { if (state == null) { state = new NFAState(); } AddOut(new NFACharTransition(Char.ToLower(ch), state)); AddOut(new NFACharTransition(Char.ToUpper(ch), state)); return state; } else { if (state == null) { state = FindUniqueCharTransition(ch); if (state != null) { return state; } state = new NFAState(); } return AddOut(new NFACharTransition(ch, state)); } } /** * Adds a new outgoing transition. * * @param trans the transition to add * * @return the transition target state */ public NFAState AddOut(NFATransition trans) { Array.Resize(ref outgoing, outgoing.Length + 1); outgoing[outgoing.Length - 1] = trans; if (trans is NFAEpsilonTransition) { epsilonOut = true; } return trans.state; } /** * Merges all the transitions in this state into another * state. * * @param state the state to merge into */ public void MergeInto(NFAState state) { for (int i = 0; i < incoming.Length; i++) { state.AddIn(incoming[i]); incoming[i].state = state; } incoming = null; for (int i = 0; i < outgoing.Length; i++) { state.AddOut(outgoing[i]); } outgoing = null; } /** * Finds a unique character transition if one exists. The * transition must be the only matching single character * transition and no other transitions may reach the same * state. * * @param ch the character to search for * * @return the unique transition state found, or * null if not found */ private NFAState FindUniqueCharTransition(char ch) { NFATransition res = null; NFATransition trans; for (int i = 0; i < outgoing.Length; i++) { trans = outgoing[i]; if (trans.Match(ch) && trans is NFACharTransition) { if (res != null) { return null; } res = trans; } } for (int i = 0; res != null && i < outgoing.Length; i++) { trans = outgoing[i]; if (trans != res && trans.state == res.state) { return null; } } return (res == null) ? null : res.state; } /** * Attempts a match on each of the transitions leading from * this state. If a match is found, its state will be added * to the queue. If the initial match flag is set, epsilon * transitions will also be matched (and their targets called * recursively). * * @param ch the character to match * @param queue the state queue * @param initial the initial match flag */ public void MatchTransitions(char ch, NFAStateQueue queue, bool initial) { NFATransition trans; NFAState target; for (int i = 0; i < outgoing.Length; i++) { trans = outgoing[i]; target = trans.state; if (initial && trans is NFAEpsilonTransition) { target.MatchTransitions(ch, queue, true); } else if (trans.Match(ch)) { queue.AddLast(target); if (target.epsilonOut) { target.MatchEmpty(queue); } } } } /** * Adds all the epsilon transition targets to the specified * queue. * * @param queue the state queue */ public void MatchEmpty(NFAStateQueue queue) { NFATransition trans; NFAState target; for (int i = 0; i < outgoing.Length; i++) { trans = outgoing[i]; if (trans is NFAEpsilonTransition) { target = trans.state; queue.AddLast(target); if (target.epsilonOut) { target.MatchEmpty(queue); } } } } } /** * An NFA state transition. A transition checks a single * character of input an determines if it is a match. If a match * is encountered, the NFA should move forward to the transition * state. */ internal abstract class NFATransition { /** * The target state of the transition. */ internal NFAState state; /** * Creates a new state transition. * * @param state the target state */ public NFATransition(NFAState state) { this.state = state; this.state.AddIn(this); } /** * Checks if this transition only matches ASCII characters. * I.e. characters with numeric values between 0 and 127. * * @return true if this transition only matches ASCII, or * false otherwise */ public abstract bool IsAscii(); /** * Checks if the specified character matches the transition. * * @param ch the character to check * * @return true if the character matches, or * false otherwise */ public abstract bool Match(char ch); /** * Creates a copy of this transition but with another target * state. * * @param state the new target state * * @return an identical copy of this transition */ public abstract NFATransition Copy(NFAState state); } /** * The special epsilon transition. This transition matches the * empty input, i.e. it is an automatic transition that doesn't * read any input. As such, it returns false in the match method * and is handled specially everywhere. */ internal class NFAEpsilonTransition : NFATransition { /** * Creates a new epsilon transition. * * @param state the target state */ public NFAEpsilonTransition(NFAState state) : base(state) { } /** * Checks if this transition only matches ASCII characters. * I.e. characters with numeric values between 0 and 127. * * @return true if this transition only matches ASCII, or * false otherwise */ public override bool IsAscii() { return false; } /** * Checks if the specified character matches the transition. * * @param ch the character to check * * @return true if the character matches, or * false otherwise */ public override bool Match(char ch) { return false; } /** * Creates a copy of this transition but with another target * state. * * @param state the new target state * * @return an identical copy of this transition */ public override NFATransition Copy(NFAState state) { return new NFAEpsilonTransition(state); } } /** * A single character match transition. */ internal class NFACharTransition : NFATransition { /** * The character to match. */ protected char match; /** * Creates a new character transition. * * @param match the character to match * @param state the target state */ public NFACharTransition(char match, NFAState state) : base(state) { this.match = match; } /** * Checks if this transition only matches ASCII characters. * I.e. characters with numeric values between 0 and 127. * * @return true if this transition only matches ASCII, or * false otherwise */ public override bool IsAscii() { return 0 <= match && match < 128; } /** * Checks if the specified character matches the transition. * * @param ch the character to check * * @return true if the character matches, or * false otherwise */ public override bool Match(char ch) { return this.match == ch; } /** * Creates a copy of this transition but with another target * state. * * @param state the new target state * * @return an identical copy of this transition */ public override NFATransition Copy(NFAState state) { return new NFACharTransition(match, state); } } /** * A character range match transition. Used for user-defined * character sets in regular expressions. */ internal class NFACharRangeTransition : NFATransition { /** * The inverse match flag. */ protected bool inverse; /** * The case-insensitive match flag. */ protected bool ignoreCase; /** * The character set content. This array may contain either * range objects or Character objects. */ private object[] contents = new object[0]; /** * Creates a new character range transition. * * @param inverse the inverse match flag * @param ignoreCase the case-insensitive match flag * @param state the target state */ public NFACharRangeTransition(bool inverse, bool ignoreCase, NFAState state) : base(state) { this.inverse = inverse; this.ignoreCase = ignoreCase; } /** * Checks if this transition only matches ASCII characters. * I.e. characters with numeric values between 0 and 127. * * @return true if this transition only matches ASCII, or * false otherwise */ public override bool IsAscii() { object obj; char c; if (inverse) { return false; } for (int i = 0; i < contents.Length; i++) { obj = contents[i]; if (obj is char) { c = (char) obj; if (c < 0 || 128 <= c) { return false; } } else if (obj is Range) { if (!((Range) obj).IsAscii()) { return false; } } } return true; } /** * Adds a single character to this character set. * * @param c the character to add */ public void AddCharacter(char c) { if (ignoreCase) { c = Char.ToLower(c); } AddContent(c); } /** * Adds a character range to this character set. * * @param min the minimum character value * @param max the maximum character value */ public void AddRange(char min, char max) { if (ignoreCase) { min = Char.ToLower(min); max = Char.ToLower(max); } AddContent(new Range(min, max)); } /** * Adds an object to the character set content array. * * @param obj the object to add */ private void AddContent(Object obj) { Array.Resize(ref contents, contents.Length + 1); contents[contents.Length - 1] = obj; } /** * Checks if the specified character matches the transition. * * @param ch the character to check * * @return true if the character matches, or * false otherwise */ public override bool Match(char ch) { object obj; char c; Range r; if (ignoreCase) { ch = Char.ToLower(ch); } for (int i = 0; i < contents.Length; i++) { obj = contents[i]; if (obj is char) { c = (char) obj; if (c == ch) { return !inverse; } } else if (obj is Range) { r = (Range) obj; if (r.Inside(ch)) { return !inverse; } } } return inverse; } /** * Creates a copy of this transition but with another target * state. * * @param state the new target state * * @return an identical copy of this transition */ public override NFATransition Copy(NFAState state) { NFACharRangeTransition copy; copy = new NFACharRangeTransition(inverse, ignoreCase, state); copy.contents = contents; return copy; } /** * A character range class. */ private class Range { /** * The minimum character value. */ private char min; /** * The maximum character value. */ private char max; /** * Creates a new character range. * * @param min the minimum character value * @param max the maximum character value */ public Range(char min, char max) { this.min = min; this.max = max; } /** * Checks if this range only matches ASCII characters * * @return true if this range only matches ASCII, or * false otherwise */ public bool IsAscii() { return 0 <= min && min < 128 && 0 <= max && max < 128; } /** * Checks if the specified character is inside the range. * * @param c the character to check * * @return true if the character is in the range, or * false otherwise */ public bool Inside(char c) { return min <= c && c <= max; } } } /** * The dot ('.') character set transition. This transition * matches a single character that is not equal to a newline * character. */ internal class NFADotTransition : NFATransition { /** * Creates a new dot character set transition. * * @param state the target state */ public NFADotTransition(NFAState state) : base(state) { } /** * Checks if this transition only matches ASCII characters. * I.e. characters with numeric values between 0 and 127. * * @return true if this transition only matches ASCII, or * false otherwise */ public override bool IsAscii() { return false; } /** * Checks if the specified character matches the transition. * * @param ch the character to check * * @return true if the character matches, or * false otherwise */ public override bool Match(char ch) { switch (ch) { case '\n': case '\r': case '\u0085': case '\u2028': case '\u2029': return false; default: return true; } } /** * Creates a copy of this transition but with another target * state. * * @param state the new target state * * @return an identical copy of this transition */ public override NFATransition Copy(NFAState state) { return new NFADotTransition(state); } } /** * The digit character set transition. This transition matches a * single numeric character. */ internal class NFADigitTransition : NFATransition { /** * Creates a new digit character set transition. * * @param state the target state */ public NFADigitTransition(NFAState state) : base(state) { } /** * Checks if this transition only matches ASCII characters. * I.e. characters with numeric values between 0 and 127. * * @return true if this transition only matches ASCII, or * false otherwise */ public override bool IsAscii() { return true; } /** * Checks if the specified character matches the transition. * * @param ch the character to check * * @return true if the character matches, or * false otherwise */ public override bool Match(char ch) { return '0' <= ch && ch <= '9'; } /** * Creates a copy of this transition but with another target * state. * * @param state the new target state * * @return an identical copy of this transition */ public override NFATransition Copy(NFAState state) { return new NFADigitTransition(state); } } /** * The non-digit character set transition. This transition * matches a single non-numeric character. */ internal class NFANonDigitTransition : NFATransition { /** * Creates a new non-digit character set transition. * * @param state the target state */ public NFANonDigitTransition(NFAState state) : base(state) { } /** * Checks if this transition only matches ASCII characters. * I.e. characters with numeric values between 0 and 127. * * @return true if this transition only matches ASCII, or * false otherwise */ public override bool IsAscii() { return false; } /** * Checks if the specified character matches the transition. * * @param ch the character to check * * @return true if the character matches, or * false otherwise */ public override bool Match(char ch) { return ch < '0' || '9' < ch; } /** * Creates a copy of this transition but with another target * state. * * @param state the new target state * * @return an identical copy of this transition */ public override NFATransition Copy(NFAState state) { return new NFANonDigitTransition(state); } } /** * The whitespace character set transition. This transition * matches a single whitespace character. */ internal class NFAWhitespaceTransition : NFATransition { /** * Creates a new whitespace character set transition. * * @param state the target state */ public NFAWhitespaceTransition(NFAState state) : base(state) { } /** * Checks if this transition only matches ASCII characters. * I.e. characters with numeric values between 0 and 127. * * @return true if this transition only matches ASCII, or * false otherwise */ public override bool IsAscii() { return true; } /** * Checks if the specified character matches the transition. * * @param ch the character to check * * @return true if the character matches, or * false otherwise */ public override bool Match(char ch) { switch (ch) { case ' ': case '\t': case '\n': case '\f': case '\r': case (char) 11: return true; default: return false; } } /** * Creates a copy of this transition but with another target * state. * * @param state the new target state * * @return an identical copy of this transition */ public override NFATransition Copy(NFAState state) { return new NFAWhitespaceTransition(state); } } /** * The non-whitespace character set transition. This transition * matches a single non-whitespace character. */ internal class NFANonWhitespaceTransition : NFATransition { /** * Creates a new non-whitespace character set transition. * * @param state the target state */ public NFANonWhitespaceTransition(NFAState state) : base(state) { } /** * Checks if this transition only matches ASCII characters. * I.e. characters with numeric values between 0 and 127. * * @return true if this transition only matches ASCII, or * false otherwise */ public override bool IsAscii() { return false; } /** * Checks if the specified character matches the transition. * * @param ch the character to check * * @return true if the character matches, or * false otherwise */ public override bool Match(char ch) { switch (ch) { case ' ': case '\t': case '\n': case '\f': case '\r': case (char) 11: return false; default: return true; } } /** * Creates a copy of this transition but with another target * state. * * @param state the new target state * * @return an identical copy of this transition */ public override NFATransition Copy(NFAState state) { return new NFANonWhitespaceTransition(state); } } /** * The word character set transition. This transition matches a * single word character. */ internal class NFAWordTransition : NFATransition { /** * Creates a new word character set transition. * * @param state the target state */ public NFAWordTransition(NFAState state) : base(state) { } /** * Checks if this transition only matches ASCII characters. * I.e. characters with numeric values between 0 and 127. * * @return true if this transition only matches ASCII, or * false otherwise */ public override bool IsAscii() { return true; } /** * Checks if the specified character matches the transition. * * @param ch the character to check * * @return true if the character matches, or * false otherwise */ public override bool Match(char ch) { return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ('0' <= ch && ch <= '9') || ch == '_'; } /** * Creates a copy of this transition but with another target * state. * * @param state the new target state * * @return an identical copy of this transition */ public override NFATransition Copy(NFAState state) { return new NFAWordTransition(state); } } /** * The non-word character set transition. This transition matches * a single non-word character. */ internal class NFANonWordTransition : NFATransition { /** * Creates a new non-word character set transition. * * @param state the target state */ public NFANonWordTransition(NFAState state) : base(state) { } /** * Checks if this transition only matches ASCII characters. * I.e. characters with numeric values between 0 and 127. * * @return true if this transition only matches ASCII, or * false otherwise */ public override bool IsAscii() { return false; } /** * Checks if the specified character matches the transition. * * @param ch the character to check * * @return true if the character matches, or * false otherwise */ public override bool Match(char ch) { bool word = ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ('0' <= ch && ch <= '9') || ch == '_'; return !word; } /** * Creates a copy of this transition but with another target * state. * * @param state the new target state * * @return an identical copy of this transition */ public override NFATransition Copy(NFAState state) { return new NFANonWordTransition(state); } } /** * An NFA state queue. This queue is used during processing to * keep track of the current and subsequent NFA states. The * current state is read from the beginning of the queue, and new * states are added at the end. A marker index is used to * separate the current from the subsequent states.<p> * * The queue implementation is optimized for quick removal at the * beginning and addition at the end. It will attempt to use a * fixed-size array to store the whole queue, and moves the data * in this array only when absolutely needed. The array is also * enlarged automatically if too many states are being processed * at a single time. */ internal class NFAStateQueue { /** * The state queue array. Will be enlarged as needed. */ private NFAState[] queue = new NFAState[2048]; /** * The position of the first entry in the queue (inclusive). */ private int first = 0; /** * The position just after the last entry in the queue * (exclusive). */ private int last = 0; /** * The current queue mark position. */ private int mark = 0; /** * The empty queue property (read-only). */ public bool Empty { get { return (last <= first); } } /** * The marked first entry property (read-only). This is set * to true if the first entry in the queue has been marked. */ public bool Marked { get { return first == mark; } } /** * Clears this queue. This operation is fast, as it just * resets the queue position indices. */ public void Clear() { first = 0; last = 0; mark = 0; } /** * Marks the end of the queue. This means that the next entry * added to the queue will be marked (when it becomes the * first in the queue). This operation is fast. */ public void MarkEnd() { mark = last; } /** * Removes and returns the first entry in the queue. This * operation is fast, since it will only update the index of * the first entry in the queue. * * @return the previous first entry in the queue */ public NFAState RemoveFirst() { if (first < last) { first++; return queue[first - 1]; } else { return null; } } /** * Adds a new entry at the end of the queue. This operation * is mostly fast, unless all the allocated queue space has * already been used. * * @param state the state to add */ public void AddLast(NFAState state) { if (last >= queue.Length) { if (first <= 0) { Array.Resize(ref queue, queue.Length * 2); } else { Array.Copy(queue, first, queue, 0, last - first); last -= first; mark -= first; first = 0; } } queue[last++] = state; } } }
// 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. // // Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused. // namespace System.Text { using System; using System.Runtime.Serialization; using System.Security.Permissions; using System.Diagnostics.Contracts; #if FEATURE_SERIALIZATION [Serializable] #endif [System.Runtime.InteropServices.ComVisible(true)] public class UTF7Encoding : Encoding { private const String base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // 0123456789111111111122222222223333333333444444444455555555556666 // 012345678901234567890123456789012345678901234567890123 // These are the characters that can be directly encoded in UTF7. private const String directChars = "\t\n\r '(),-./0123456789:?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // These are the characters that can be optionally directly encoded in UTF7. private const String optionalChars = "!\"#$%&*;<=>@[]^_`{|}"; // The set of base 64 characters. private byte[] base64Bytes; // The decoded bits for every base64 values. This array has a size of 128 elements. // The index is the code point value of the base 64 characters. The value is -1 if // the code point is not a valid base 64 character. Otherwise, the value is a value // from 0 ~ 63. private sbyte[] base64Values; // The array to decide if a Unicode code point below 0x80 can be directly encoded in UTF7. // This array has a size of 128. private bool[] directEncode; [OptionalField(VersionAdded = 2)] private bool m_allowOptionals; private const int UTF7_CODEPAGE=65000; public UTF7Encoding() : this(false) { } public UTF7Encoding(bool allowOptionals) : base(UTF7_CODEPAGE) //Set the data item. { // Allowing optionals? this.m_allowOptionals = allowOptionals; // Make our tables MakeTables(); } private void MakeTables() { // Build our tables base64Bytes = new byte[64]; for (int i = 0; i < 64; i++) base64Bytes[i] = (byte)base64Chars[i]; base64Values = new sbyte[128]; for (int i = 0; i < 128; i++) base64Values[i] = -1; for (int i = 0; i < 64; i++) base64Values[base64Bytes[i]] = (sbyte)i; directEncode = new bool[128]; int count = directChars.Length; for (int i = 0; i < count; i++) { directEncode[directChars[i]] = true; } if (this.m_allowOptionals) { count = optionalChars.Length; for (int i = 0; i < count; i++) { directEncode[optionalChars[i]] = true; } } } // We go ahead and set this because Encoding expects it, however nothing can fall back in UTF7. internal override void SetDefaultFallbacks() { // UTF7 had an odd decoderFallback behavior, and the Encoder fallback // is irrelevent because we encode surrogates individually and never check for unmatched ones // (so nothing can fallback during encoding) this.encoderFallback = new EncoderReplacementFallback(String.Empty); this.decoderFallback = new DecoderUTF7Fallback(); } #region Serialization [OnDeserializing] private void OnDeserializing(StreamingContext ctx) { // make sure the optional fields initialized correctly. base.OnDeserializing(); } [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { base.OnDeserialized(); if (m_deserializedFromEverett) { // If 1st optional char is encoded we're allowing optionals m_allowOptionals = directEncode[optionalChars[0]]; } MakeTables(); } #endregion Serialization [System.Runtime.InteropServices.ComVisible(false)] public override bool Equals(Object value) { UTF7Encoding that = value as UTF7Encoding; if (that != null) { return (m_allowOptionals == that.m_allowOptionals) && (EncoderFallback.Equals(that.EncoderFallback)) && (DecoderFallback.Equals(that.DecoderFallback)); } return (false); } // Compared to all the other encodings, variations of UTF7 are unlikely [System.Runtime.InteropServices.ComVisible(false)] public override int GetHashCode() { return this.CodePage + this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode(); } // NOTE: Many methods in this class forward to EncodingForwarder for // validating arguments/wrapping the unsafe methods in this class // which do the actual work. That class contains // shared logic for doing this which is used by // ASCIIEncoding, EncodingNLS, UnicodeEncoding, UTF32Encoding, // UTF7Encoding, and UTF8Encoding. // The reason the code is separated out into a static class, rather // than a base class which overrides all of these methods for us // (which is what EncodingNLS is for internal Encodings) is because // that's really more of an implementation detail so it's internal. // At the same time, C# doesn't allow a public class subclassing an // internal/private one, so we end up having to re-override these // methods in all of the public Encodings + EncodingNLS. // Returns the number of bytes required to encode a range of characters in // a character array. public override int GetByteCount(char[] chars, int index, int count) { return EncodingForwarder.GetByteCount(this, chars, index, count); } [System.Runtime.InteropServices.ComVisible(false)] public override int GetByteCount(String s) { return EncodingForwarder.GetByteCount(this, s); } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public override unsafe int GetByteCount(char* chars, int count) { return EncodingForwarder.GetByteCount(this, chars, count); } [System.Runtime.InteropServices.ComVisible(false)] public override int GetBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { return EncodingForwarder.GetBytes(this, s, charIndex, charCount, bytes, byteIndex); } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex); } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { return EncodingForwarder.GetBytes(this, chars, charCount, bytes, byteCount); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. public override int GetCharCount(byte[] bytes, int index, int count) { return EncodingForwarder.GetCharCount(this, bytes, index, count); } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public override unsafe int GetCharCount(byte* bytes, int count) { return EncodingForwarder.GetCharCount(this, bytes, count); } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex); } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { return EncodingForwarder.GetChars(this, bytes, byteCount, chars, charCount); } // Returns a string containing the decoded representation of a range of // bytes in a byte array. [System.Runtime.InteropServices.ComVisible(false)] public override String GetString(byte[] bytes, int index, int count) { return EncodingForwarder.GetString(this, bytes, index, count); } // End of overridden methods which use EncodingForwarder [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder) { Contract.Assert(chars!=null, "[UTF7Encoding.GetByteCount]chars!=null"); Contract.Assert(count >=0, "[UTF7Encoding.GetByteCount]count >=0"); // Just call GetBytes with bytes == null return GetBytes(chars, count, null, 0, baseEncoder); } [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS baseEncoder) { Contract.Assert(byteCount >=0, "[UTF7Encoding.GetBytes]byteCount >=0"); Contract.Assert(chars!=null, "[UTF7Encoding.GetBytes]chars!=null"); Contract.Assert(charCount >=0, "[UTF7Encoding.GetBytes]charCount >=0"); // Get encoder info UTF7Encoding.Encoder encoder = (UTF7Encoding.Encoder)baseEncoder; // Default bits & count int bits = 0; int bitCount = -1; // prepare our helpers Encoding.EncodingByteBuffer buffer = new Encoding.EncodingByteBuffer( this, encoder, bytes, byteCount, chars, charCount); if (encoder != null) { bits = encoder.bits; bitCount = encoder.bitCount; // May have had too many left over while (bitCount >= 6) { bitCount -= 6; // If we fail we'll never really have enough room if (!buffer.AddByte(base64Bytes[(bits >> bitCount) & 0x3F])) ThrowBytesOverflow(encoder, buffer.Count == 0); } } while (buffer.MoreData) { char currentChar = buffer.GetNextChar(); if (currentChar < 0x80 && directEncode[currentChar]) { if (bitCount >= 0) { if (bitCount > 0) { // Try to add the next byte if (!buffer.AddByte(base64Bytes[bits << 6 - bitCount & 0x3F])) break; // Stop here, didn't throw bitCount = 0; } // Need to get emit '-' and our char, 2 bytes total if (!buffer.AddByte((byte)'-')) break; // Stop here, didn't throw bitCount = -1; } // Need to emit our char if (!buffer.AddByte((byte)currentChar)) break; // Stop here, didn't throw } else if (bitCount < 0 && currentChar == '+') { if (!buffer.AddByte((byte)'+', (byte)'-')) break; // Stop here, didn't throw } else { if (bitCount < 0) { // Need to emit a + and 12 bits (3 bytes) // Only 12 of the 16 bits will be emitted this time, the other 4 wait 'til next time if (!buffer.AddByte((byte)'+')) break; // Stop here, didn't throw // We're now in bit mode, but haven't stored data yet bitCount = 0; } // Add our bits bits = bits << 16 | currentChar; bitCount += 16; while (bitCount >= 6) { bitCount -= 6; if (!buffer.AddByte(base64Bytes[(bits >> bitCount) & 0x3F])) { bitCount += 6; // We didn't use these bits currentChar = buffer.GetNextChar(); // We're processing this char still, but AddByte // --'d it when we ran out of space break; // Stop here, not enough room for bytes } } if (bitCount >= 6) break; // Didn't have room to encode enough bits } } // Now if we have bits left over we have to encode them. // MustFlush may have been cleared by encoding.ThrowBytesOverflow earlier if converting if (bitCount >= 0 && (encoder == null || encoder.MustFlush)) { // Do we have bits we have to stick in? if (bitCount > 0) { if (buffer.AddByte(base64Bytes[(bits << (6 - bitCount)) & 0x3F])) { // Emitted spare bits, 0 bits left bitCount = 0; } } // If converting and failed bitCount above, then we'll fail this too if (buffer.AddByte((byte)'-')) { // turned off bit mode'; bits = 0; bitCount = -1; } else // If not successful, convert will maintain state for next time, also // AddByte will have decremented our char count, however we need it to remain the same buffer.GetNextChar(); } // Do we have an encoder we're allowed to use? // bytes == null if counting, so don't use encoder then if (bytes != null && encoder != null) { // We already cleared bits & bitcount for mustflush case encoder.bits = bits; encoder.bitCount = bitCount; encoder.m_charsUsed = buffer.CharsUsed; } return buffer.Count; } [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { Contract.Assert(count >=0, "[UTF7Encoding.GetCharCount]count >=0"); Contract.Assert(bytes!=null, "[UTF7Encoding.GetCharCount]bytes!=null"); // Just call GetChars with null char* to do counting return GetChars(bytes, count, null, 0, baseDecoder); } [System.Security.SecurityCritical] // auto-generated internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { Contract.Assert(byteCount >=0, "[UTF7Encoding.GetChars]byteCount >=0"); Contract.Assert(bytes!=null, "[UTF7Encoding.GetChars]bytes!=null"); Contract.Assert(charCount >=0, "[UTF7Encoding.GetChars]charCount >=0"); // Might use a decoder UTF7Encoding.Decoder decoder = (UTF7Encoding.Decoder) baseDecoder; // Get our output buffer info. Encoding.EncodingCharBuffer buffer = new Encoding.EncodingCharBuffer( this, decoder, chars, charCount, bytes, byteCount); // Get decoder info int bits = 0; int bitCount = -1; bool firstByte = false; if (decoder != null) { bits = decoder.bits; bitCount = decoder.bitCount; firstByte = decoder.firstByte; Contract.Assert(firstByte == false || decoder.bitCount <= 0, "[UTF7Encoding.GetChars]If remembered bits, then first byte flag shouldn't be set"); } // We may have had bits in the decoder that we couldn't output last time, so do so now if (bitCount >= 16) { // Check our decoder buffer if (!buffer.AddChar((char)((bits >> (bitCount - 16)) & 0xFFFF))) ThrowCharsOverflow(decoder, true); // Always throw, they need at least 1 char even in Convert // Used this one, clean up extra bits bitCount -= 16; } // Loop through the input while (buffer.MoreData) { byte currentByte = buffer.GetNextByte(); int c; if (bitCount >= 0) { // // Modified base 64 encoding. // sbyte v; if (currentByte < 0x80 && ((v = base64Values[currentByte]) >=0)) { firstByte = false; bits = (bits << 6) | ((byte)v); bitCount += 6; if (bitCount >= 16) { c = (bits >> (bitCount - 16)) & 0xFFFF; bitCount -= 16; } // If not enough bits just continue else continue; } else { // If it wasn't a base 64 byte, everything's going to turn off base 64 mode bitCount = -1; if (currentByte != '-') { // >= 0x80 (because of 1st if statemtn) // We need this check since the base64Values[b] check below need b <= 0x7f. // This is not a valid base 64 byte. Terminate the shifted-sequence and // emit this byte. // not in base 64 table // According to the RFC 1642 and the example code of UTF-7 // in Unicode 2.0, we should just zero-extend the invalid UTF7 byte // Chars won't be updated unless this works, try to fallback if (!buffer.Fallback(currentByte)) break; // Stop here, didn't throw // Used that byte, we're done with it continue; } // // The encoding for '+' is "+-". // if (firstByte) c = '+'; // We just turn it off if not emitting a +, so we're done. else continue; } // // End of modified base 64 encoding block. // } else if (currentByte == '+') { // // Found the start of a modified base 64 encoding block or a plus sign. // bitCount = 0; firstByte = true; continue; } else { // Normal character if (currentByte >= 0x80) { // Try to fallback if (!buffer.Fallback(currentByte)) break; // Stop here, didn't throw // Done falling back continue; } // Use the normal character c = currentByte; } if (c >= 0) { // Check our buffer if (!buffer.AddChar((char)c)) { // No room. If it was a plain char we'll try again later. // Note, we'll consume this byte and stick it in decoder, even if we can't output it if (bitCount >= 0) // Can we rememmber this byte (char) { buffer.AdjustBytes(+1); // Need to readd the byte that AddChar subtracted when it failed bitCount += 16; // We'll still need that char we have in our bits } break; // didn't throw, stop } } } // Stick stuff in the decoder if we can (chars == null if counting, so don't store decoder) if (chars != null && decoder != null) { // MustFlush? (Could've been cleared by ThrowCharsOverflow if Convert & didn't reach end of buffer) if (decoder.MustFlush) { // RFC doesn't specify what would happen if we have non-0 leftover bits, we just drop them decoder.bits = 0; decoder.bitCount = -1; decoder.firstByte = false; } else { decoder.bits = bits; decoder.bitCount = bitCount; decoder.firstByte = firstByte; } decoder.m_bytesUsed = buffer.BytesUsed; } // else ignore any hanging bits. // Return our count return buffer.Count; } public override System.Text.Decoder GetDecoder() { return new UTF7Encoding.Decoder(this); } public override System.Text.Encoder GetEncoder() { return new UTF7Encoding.Encoder(this); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // Suppose that every char can not be direct-encoded, we know that // a byte can encode 6 bits of the Unicode character. And we will // also need two extra bytes for the shift-in ('+') and shift-out ('-') mark. // Therefore, the max byte should be: // byteCount = 2 + Math.Ceiling((double)charCount * 16 / 6); // That is always <= 2 + 3 * charCount; // Longest case is alternating encoded, direct, encoded data for 5 + 1 + 5... bytes per char. // UTF7 doesn't have left over surrogates, but if no input we may need an output - to turn off // encoding if MustFlush is true. // Its easiest to think of this as 2 bytes to turn on/off the base64 mode, then 3 bytes per char. // 3 bytes is 18 bits of encoding, which is more than we need, but if its direct encoded then 3 // bytes allows us to turn off and then back on base64 mode if necessary. // Note that UTF7 encoded surrogates individually and isn't worried about mismatches, so all // code points are encodable int UTF7. long byteCount = (long)charCount * 3 + 2; // check for overflow if (byteCount > 0x7fffffff) throw new ArgumentOutOfRangeException("charCount", Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); return (int)byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) throw new ArgumentOutOfRangeException("byteCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // Worst case is 1 char per byte. Minimum 1 for left over bits in case decoder is being flushed // Also note that we ignore extra bits (per spec), so UTF7 doesn't have unknown in this direction. int charCount = byteCount; if (charCount == 0) charCount = 1; return charCount; } #if FEATURE_SERIALIZATION [Serializable] #endif // Of all the amazing things... This MUST be Decoder so that our com name // for System.Text.Decoder doesn't change private class Decoder : DecoderNLS #if FEATURE_SERIALIZATION , ISerializable #endif { /*private*/ internal int bits; /*private*/ internal int bitCount; /*private*/ internal bool firstByte; public Decoder(UTF7Encoding encoding) : base (encoding) { // base calls reset } // Constructor called by serialization, have to handle deserializing from Everett internal Decoder(SerializationInfo info, StreamingContext context) { // Any info? if (info==null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); // Get common info this.bits = (int)info.GetValue("bits", typeof(int)); this.bitCount = (int)info.GetValue("bitCount", typeof(int)); this.firstByte = (bool)info.GetValue("firstByte", typeof(bool)); this.m_encoding = (Encoding)info.GetValue("encoding", typeof(Encoding)); } #if FEATURE_SERIALIZATION // ISerializable implementation, get data for this object [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // Any info? if (info==null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); // Save Whidbey data info.AddValue("encoding", this.m_encoding); info.AddValue("bits", this.bits); info.AddValue("bitCount", this.bitCount); info.AddValue("firstByte", this.firstByte); } #endif public override void Reset() { this.bits = 0; this.bitCount = -1; this.firstByte = false; if (m_fallbackBuffer != null) m_fallbackBuffer.Reset(); } // Anything left in our encoder? internal override bool HasState { get { // NOTE: This forces the last -, which some encoder might not encode. If we // don't see it we don't think we're done reading. return (this.bitCount != -1); } } } #if FEATURE_SERIALIZATION [Serializable] #endif // Of all the amazing things... This MUST be Encoder so that our com name // for System.Text.Encoder doesn't change private class Encoder : EncoderNLS #if FEATURE_SERIALIZATION , ISerializable #endif { /*private*/ internal int bits; /*private*/ internal int bitCount; public Encoder(UTF7Encoding encoding) : base(encoding) { // base calls reset } // Constructor called by serialization, have to handle deserializing from Everett internal Encoder(SerializationInfo info, StreamingContext context) { // Any info? if (info==null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); // Get common info this.bits = (int)info.GetValue("bits", typeof(int)); this.bitCount = (int)info.GetValue("bitCount", typeof(int)); this.m_encoding = (Encoding)info.GetValue("encoding", typeof(Encoding)); } #if FEATURE_SERIALIZATION // ISerializable implementation, get data for this object [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // Any info? if (info==null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); // Save Whidbey data info.AddValue("encoding", this.m_encoding); info.AddValue("bits", this.bits); info.AddValue("bitCount", this.bitCount); } #endif public override void Reset() { this.bitCount = -1; this.bits = 0; if (m_fallbackBuffer != null) m_fallbackBuffer.Reset(); } // Anything left in our encoder? internal override bool HasState { get { return (this.bits != 0 || this.bitCount != -1); } } } // Preexisting UTF7 behavior for bad bytes was just to spit out the byte as the next char // and turn off base64 mode if it was in that mode. We still exit the mode, but now we fallback. [Serializable] internal sealed class DecoderUTF7Fallback : DecoderFallback { // Construction. Default replacement fallback uses no best fit and ? replacement string public DecoderUTF7Fallback() { } public override DecoderFallbackBuffer CreateFallbackBuffer() { return new DecoderUTF7FallbackBuffer(this); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { // returns 1 char per bad byte return 1; } } public override bool Equals(Object value) { DecoderUTF7Fallback that = value as DecoderUTF7Fallback; if (that != null) { return true; } return (false); } public override int GetHashCode() { return 984; } } internal sealed class DecoderUTF7FallbackBuffer : DecoderFallbackBuffer { // Store our default string char cFallback = (char)0; int iCount = -1; int iSize; // Construction public DecoderUTF7FallbackBuffer(DecoderUTF7Fallback fallback) { } // Fallback Methods public override bool Fallback(byte[] bytesUnknown, int index) { // We expect no previous fallback in our buffer Contract.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.Fallback] Can't have recursive fallbacks"); Contract.Assert(bytesUnknown.Length == 1, "[DecoderUTF7FallbackBuffer.Fallback] Only possible fallback case should be 1 unknown byte"); // Go ahead and get our fallback cFallback = (char)bytesUnknown[0]; // Any of the fallback characters can be handled except for 0 if (cFallback == 0) { return false; } iCount = iSize = 1; return true; } public override char GetNextChar() { if (iCount-- > 0) return cFallback; // Note: this means that 0 in UTF7 stream will never be emitted. return (char)0; } public override bool MovePrevious() { if (iCount >= 0) { iCount++; } // return true if we were allowed to do this return (iCount >= 0 && iCount <= iSize); } // Return # of chars left in this fallback public override int Remaining { get { return (iCount > 0) ? iCount : 0; } } // Clear the buffer [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe void Reset() { iCount = -1; byteStart = null; } // This version just counts the fallback and doesn't actually copy anything. [System.Security.SecurityCritical] // auto-generated internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes) // Right now this has both bytes and bytes[], since we might have extra bytes, hence the // array, and we might need the index, hence the byte* { // We expect no previous fallback in our buffer Contract.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.InternalFallback] Can't have recursive fallbacks"); if (bytes.Length != 1) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex")); } // Can't fallback a byte 0, so return for that case, 1 otherwise. return bytes[0] == 0 ? 0 : 1; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using System.Windows; #if NTVS_FEATURE_INTERACTIVEWINDOW using Microsoft.NodejsTools.Repl; #elif DEV14_OR_LATER using Microsoft.VisualStudio.InteractiveWindow; #else using Microsoft.VisualStudio.Repl; #endif using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace TestUtilities.Mocks { #if !NTVS_FEATURE_INTERACTIVEWINDOW && DEV14_OR_LATER using IReplEvaluator = IInteractiveEvaluator; using IReplWindow = IInteractiveWindow; #endif public class MockReplWindow : IReplWindow { private readonly StringBuilder _output = new StringBuilder(); private readonly StringBuilder _error = new StringBuilder(); private readonly IReplEvaluator _eval; private readonly MockTextView _view; private readonly string _contentType; #if DEV14_OR_LATER && !NTVS_FEATURE_INTERACTIVEWINDOW public event EventHandler<SubmissionBufferAddedEventArgs> SubmissionBufferAdded { add { } remove { } } #endif public MockReplWindow(IReplEvaluator eval, string contentType = "Python") { _eval = eval; _contentType = contentType; _view = new MockTextView(new MockTextBuffer(String.Empty, contentType, filename: "text")); _eval.Initialize(this); } public bool ShowAnsiCodes { get; set; } public Task<ExecutionResult> Execute(string text) { _view.BufferGraph.AddBuffer( new MockTextBuffer(text, contentType: _contentType) ); return _eval.ExecuteText(text); } public string Output { get { return _output.ToString(); } } public string Error { get { return _error.ToString(); } } #region IReplWindow Members public IWpfTextView TextView { get { return _view; } } public ITextBuffer CurrentLanguageBuffer { get { return _view.TextBuffer; } } public IReplEvaluator Evaluator { get { return _eval; } } public string Title { get { return "Mock Repl Window"; } } #if DEV14_OR_LATER && !NTVS_FEATURE_INTERACTIVEWINDOW public ITextBuffer OutputBuffer { get { throw new NotImplementedException(); } } public TextWriter OutputWriter { get { return new StringWriter(_output); } } public TextWriter ErrorOutputWriter { get { return new StringWriter(_error); } } public bool IsRunning { get { throw new NotImplementedException(); } } public bool IsResetting { get { throw new NotImplementedException(); } } public bool IsInitializing { get { throw new NotImplementedException(); } } public IInteractiveWindowOperations Operations { get { throw new NotImplementedException(); } } public PropertyCollection Properties { get { throw new NotImplementedException(); } } #endif public void ClearScreen() { _output.Clear(); _error.Clear(); } public void ClearHistory() { throw new NotImplementedException(); } public void Focus() { throw new NotImplementedException(); } public void Cancel() { throw new NotImplementedException(); } public void InsertCode(string text) { throw new NotImplementedException(); } #if !DEV14_OR_LATER || NTVS_FEATURE_INTERACTIVEWINDOW public void Submit(IEnumerable<string> inputs) { throw new NotImplementedException(); } #endif public System.Threading.Tasks.Task<ExecutionResult> Reset() { return _eval.Reset(); } #if !DEV14_OR_LATER || NTVS_FEATURE_INTERACTIVEWINDOW public void AbortCommand() { _eval.AbortCommand(); } #endif public Task<ExecutionResult> ExecuteCommand(string command) { var tcs = new TaskCompletionSource<ExecutionResult>(); tcs.SetException(new NotImplementedException()); return tcs.Task; } public void WriteLine(string text) { if (!ShowAnsiCodes && text.IndexOf('\x1b') != -1) { AppendEscapedText(text); } else { _output.AppendLine(text); } } private void AppendEscapedText(string text) { // http://en.wikipedia.org/wiki/ANSI_escape_code // process any ansi color sequences... int escape = text.IndexOf('\x1b'); int start = 0; do { if (escape != start) { // add unescaped text _output.Append(text.Substring(start, escape - start)); } // process the escape sequence if (escape < text.Length - 1 && text[escape + 1] == '[') { // We have the Control Sequence Introducer (CSI) - ESC [ int? value = 0; for (int i = escape + 2; i < text.Length; i++) { // skip esc + [ if (text[i] >= '0' && text[i] <= '9') { // continue parsing the integer... if (value == null) { value = 0; } value = 10 * value.Value + (text[i] - '0'); } else if (text[i] == ';') { if (value != null) { value = null; } else { // CSI ; - invalid or CSI ### ;;, both invalid break; } } else if (text[i] == 'm') { // parsed a valid code start = i + 1; } else { // unknown char, invalid escape break; } } escape = text.IndexOf('\x1b', escape + 1); }// else not an escape sequence, process as text } while (escape != -1); if (start != text.Length - 1) { _output.Append(text.Substring(start)); } } public void WriteOutput(object value) { _output.Append(value.ToString()); } public void WriteError(object value) { _error.Append(value); } #if DEV14_OR_LATER && !NTVS_FEATURE_INTERACTIVEWINDOW public TextReader ReadStandardInput() { throw new NotImplementedException(); } #else public string ReadStandardInput() { throw new NotImplementedException(); } #endif #if !DEV14_OR_LATER || NTVS_FEATURE_INTERACTIVEWINDOW public void SetOptionValue(ReplOptions option, object value) { } public object GetOptionValue(ReplOptions option) { return null; } #endif #if DEV14_OR_LATER && !NTVS_FEATURE_INTERACTIVEWINDOW public Task<ExecutionResult> InitializeAsync() { throw new NotImplementedException(); } public void Close() { throw new NotImplementedException(); } Span IReplWindow.WriteLine(string text) { throw new NotImplementedException(); } public Task SubmitAsync(IEnumerable<string> inputs) { throw new NotImplementedException(); } public Span Write(string text) { throw new NotImplementedException(); } public void Write(UIElement element) { throw new NotImplementedException(); } public void FlushOutput() { throw new NotImplementedException(); } public void AddInput(string input) { throw new NotImplementedException(); } public void Dispose() { throw new NotImplementedException(); } #endif public event Action ReadyForInput { add { } remove { } } #endregion } #if DEV14_OR_LATER && !NTVS_FEATURE_INTERACTIVEWINDOW public static class ReplEvalExtensions { public static Task<ExecutionResult> Initialize(this IReplEvaluator self, IReplWindow window) { self.CurrentWindow = window; return self.InitializeAsync(); } public static Task<ExecutionResult> ExecuteText(this IReplEvaluator self, string text) { return self.ExecuteCodeAsync(text); } public static Task<ExecutionResult> Reset(this IReplEvaluator self) { return self.ResetAsync(); } } #endif }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.CompilerServices; using System.Threading; namespace System.Runtime.InteropServices { // This class allows you to create an opaque, GC handle to any // COM+ object. A GC handle is used when an object reference must be // reachable from unmanaged memory. There are 3 kinds of roots: // Normal - keeps the object from being collected. // Weak - allows object to be collected and handle contents will be zeroed. // Weak references are zeroed before the finalizer runs, so if the // object is resurrected in the finalizer the weak reference is // still zeroed. // WeakTrackResurrection - Same as weak, but stays until after object is // really gone. // Pinned - same as normal, but allows the address of the actual object // to be taken. // [StructLayout(LayoutKind.Sequential)] public struct GCHandle { // IMPORTANT: This must be kept in sync with the GCHandleType enum. private const GCHandleType MaxHandleType = GCHandleType.Pinned; // Allocate a handle storing the object and the type. internal GCHandle(Object value, GCHandleType type) { // Make sure the type parameter is within the valid range for the enum. if ((uint)type > (uint)MaxHandleType) { throw new ArgumentOutOfRangeException(); // "type", SR.ArgumentOutOfRange_Enum; } if (type == GCHandleType.Pinned) GCHandleValidatePinnedObject(value); _handle = RuntimeImports.RhHandleAlloc(value, type); // Record if the handle is pinned. if (type == GCHandleType.Pinned) SetIsPinned(); } // Used in the conversion functions below. internal GCHandle(IntPtr handle) { _handle = handle; } // Creates a new GC handle for an object. // // value - The object that the GC handle is created for. // type - The type of GC handle to create. // // returns a new GC handle that protects the object. public static GCHandle Alloc(Object value) { return new GCHandle(value, GCHandleType.Normal); } public static GCHandle Alloc(Object value, GCHandleType type) { return new GCHandle(value, type); } // Frees a GC handle. [MethodImplAttribute(MethodImplOptions.NoInlining)] public void Free() { // Copy the handle instance member to a local variable. This is required to prevent // race conditions releasing the handle. IntPtr handle = _handle; // Free the handle if it hasn't already been freed. if (handle != default(IntPtr) && Interlocked.CompareExchange(ref _handle, default(IntPtr), handle) == handle) { #if BIT64 RuntimeImports.RhHandleFree((IntPtr)(((long)handle) & ~1L)); #else RuntimeImports.RhHandleFree((IntPtr)(((int)handle) & ~1)); #endif } else { throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotInitialized); } } // Target property - allows getting / updating of the handle's referent. public Object Target { get { // Check if the handle was never initialized or was freed. if (_handle == default(IntPtr)) { throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotInitialized); } return RuntimeImports.RhHandleGet(GetHandleValue()); } set { // Check if the handle was never initialized or was freed. if (_handle == default(IntPtr)) { throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotInitialized); } if (IsPinned()) GCHandleValidatePinnedObject(value); RuntimeImports.RhHandleSet(GetHandleValue(), value); } } // Retrieve the address of an object in a Pinned handle. This throws // an exception if the handle is any type other than Pinned. public IntPtr AddrOfPinnedObject() { // Check if the handle was not a pinned handle. if (!IsPinned()) { // Check if the handle was never initialized for was freed. if (_handle == default(IntPtr)) { throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotInitialized); } // You can only get the address of pinned handles. throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotPinned); } unsafe { // Get the address of the pinned object. // The layout of String and Array is different from Object Object target = this.Target; if (target == null) return default(IntPtr); if (target is String targetAsString) { return (IntPtr)Unsafe.AsPointer(ref targetAsString.GetRawStringData()); } if (target is Array targetAsArray) { return (IntPtr)Unsafe.AsPointer(ref targetAsArray.GetRawArrayData()); } return (IntPtr)Unsafe.AsPointer(ref target.GetRawData()); } } // Determine whether this handle has been allocated or not. public bool IsAllocated { get { return _handle != default(IntPtr); } } // Used to create a GCHandle from an int. This is intended to // be used with the reverse conversion. public static explicit operator GCHandle(IntPtr value) { return FromIntPtr(value); } public static GCHandle FromIntPtr(IntPtr value) { if (value == default(IntPtr)) { throw new InvalidOperationException(); // SR.InvalidOperation_HandleIsNotInitialized); } return new GCHandle(value); } // Used to get the internal integer representation of the handle out. public static explicit operator IntPtr(GCHandle value) { return ToIntPtr(value); } public static IntPtr ToIntPtr(GCHandle value) { return value._handle; } public override int GetHashCode() { return _handle.GetHashCode(); } public override bool Equals(Object o) { GCHandle hnd; // Check that o is a GCHandle first if (o == null || !(o is GCHandle)) return false; else hnd = (GCHandle)o; return _handle == hnd._handle; } public static bool operator ==(GCHandle a, GCHandle b) { return a._handle == b._handle; } public static bool operator !=(GCHandle a, GCHandle b) { return a._handle != b._handle; } internal IntPtr GetHandleValue() { #if BIT64 return new IntPtr(((long)_handle) & ~1L); #else return new IntPtr(((int)_handle) & ~1); #endif } internal bool IsPinned() { #if BIT64 return (((long)_handle) & 1) != 0; #else return (((int)_handle) & 1) != 0; #endif } internal void SetIsPinned() { #if BIT64 _handle = new IntPtr(((long)_handle) | 1L); #else _handle = new IntPtr(((int)_handle) | 1); #endif } private static void GCHandleValidatePinnedObject(Object obj) { if (obj != null && !obj.IsBlittable()) throw new ArgumentException(SR.Argument_NotIsomorphic); } // The actual integer handle value that the EE uses internally. private IntPtr _handle; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Build.Framework; using Microsoft.DotNet.VersionTools.Automation; using Microsoft.DotNet.VersionTools.BuildManifest.Model; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using MSBuild = Microsoft.Build.Utilities; namespace Microsoft.DotNet.Build.Tasks.Feed { public partial class PushToBlobFeed : BuildTask { private static readonly char[] ManifestDataPairSeparators = { ';' }; private const string DisableManifestPushConfigurationBlob = "disable-manifest-push"; private const string AssetsVirtualDir = "assets/"; [Required] public string ExpectedFeedUrl { get; set; } [Required] public string AccountKey { get; set; } [Required] public ITaskItem[] ItemsToPush { get; set; } public bool Overwrite { get; set; } /// <summary> /// Enables idempotency when Overwrite is false. /// /// false: (default) Attempting to upload an item that already exists fails. /// /// true: When an item already exists, download the existing blob to check if it's /// byte-for-byte identical to the one being uploaded. If so, pass. If not, fail. /// </summary> public bool PassIfExistingItemIdentical { get; set; } public bool PublishFlatContainer { get; set; } public int MaxClients { get; set; } = 8; public bool SkipCreateContainer { get; set; } = false; public int UploadTimeoutInMinutes { get; set; } = 5; public bool SkipCreateManifest { get; set; } public string ManifestName { get; set; } = "anonymous"; public string ManifestBuildId { get; set; } = "no build id provided"; public string ManifestBranch { get; set; } public string ManifestCommit { get; set; } public string ManifestBuildData { get; set; } /// <summary> /// If the ExpectedFeedUrl includes an authentication token, this property is ignored. /// </summary> public bool MakeContainerPublic { get; set; } = true; /// <summary> /// When publishing build outputs to an orchestrated blob feed, do not change this property. /// /// The virtual dir to place the manifest XML file in, under the assets/ virtual dir. The /// default value is the well-known location that orchestration searches to find all /// manifest XML files and combine them into the orchestrated build output manifest. /// </summary> public string ManifestAssetOutputDir { get; set; } = "orchestration-metadata/manifests/"; public override bool Execute() { return ExecuteAsync().GetAwaiter().GetResult(); } public async Task<bool> ExecuteAsync() { try { Log.LogMessage(MessageImportance.High, "Performing feed push..."); if (ItemsToPush == null) { Log.LogError($"No items to push. Please check ItemGroup ItemsToPush."); } else { BlobFeedAction blobFeedAction = new BlobFeedAction(ExpectedFeedUrl, AccountKey, Log); IEnumerable<BlobArtifactModel> blobArtifacts = Enumerable.Empty<BlobArtifactModel>(); IEnumerable<PackageArtifactModel> packageArtifacts = Enumerable.Empty<PackageArtifactModel>(); if (!SkipCreateContainer) { await blobFeedAction.CreateContainerAsync(BuildEngine, PublishFlatContainer, MakeContainerPublic); } if (PublishFlatContainer) { await PublishToFlatContainerAsync(ItemsToPush, blobFeedAction); blobArtifacts = ConcatBlobArtifacts(blobArtifacts, ItemsToPush); } else { ITaskItem[] symbolItems = ItemsToPush .Where(i => i.ItemSpec.Contains("symbols.nupkg")) .Select(i => { string fileName = Path.GetFileName(i.ItemSpec); i.SetMetadata("RelativeBlobPath", $"{AssetsVirtualDir}symbols/{fileName}"); return i; }) .ToArray(); ITaskItem[] packageItems = ItemsToPush .Where(i => !symbolItems.Contains(i)) .ToArray(); var packagePaths = packageItems.Select(i => i.ItemSpec); await blobFeedAction.PushToFeedAsync(packagePaths, CreatePushOptions()); await PublishToFlatContainerAsync(symbolItems, blobFeedAction); packageArtifacts = ConcatPackageArtifacts(packageArtifacts, packageItems); blobArtifacts = ConcatBlobArtifacts(blobArtifacts, symbolItems); } if (!SkipCreateManifest) { await PushBuildManifestAsync(blobFeedAction, blobArtifacts, packageArtifacts); } } } catch (Exception e) { Log.LogErrorFromException(e, true); } return !Log.HasLoggedErrors; } private async Task PushBuildManifestAsync( BlobFeedAction blobFeedAction, IEnumerable<BlobArtifactModel> blobArtifacts, IEnumerable<PackageArtifactModel> packageArtifacts) { bool disabledByBlob = await blobFeedAction.feed.CheckIfBlobExistsAsync( $"{blobFeedAction.feed.RelativePath}{DisableManifestPushConfigurationBlob}"); if (disabledByBlob) { Log.LogMessage( MessageImportance.Normal, $"Skipping manifest push: feed has '{DisableManifestPushConfigurationBlob}'."); return; } string blobPath = $"{AssetsVirtualDir}{ManifestAssetOutputDir}{ManifestName}.xml"; string existingStr = await blobFeedAction.feed.DownloadBlobAsStringAsync( $"{blobFeedAction.feed.RelativePath}{blobPath}"); BuildModel buildModel; if (existingStr != null) { buildModel = BuildModel.Parse(XElement.Parse(existingStr)); } else { buildModel = new BuildModel( new BuildIdentity { Attributes = ParseManifestMetadataString(ManifestBuildData), Name = ManifestName, BuildId = ManifestBuildId, Branch = ManifestBranch, Commit = ManifestCommit }); } buildModel.Artifacts.Blobs.AddRange(blobArtifacts); buildModel.Artifacts.Packages.AddRange(packageArtifacts); string tempFile = null; try { tempFile = Path.GetTempFileName(); File.WriteAllText(tempFile, buildModel.ToXml().ToString()); var item = new MSBuild.TaskItem(tempFile, new Dictionary<string, string> { ["RelativeBlobPath"] = blobPath }); using (var clientThrottle = new SemaphoreSlim(MaxClients, MaxClients)) { await blobFeedAction.UploadAssetAsync( item, clientThrottle, UploadTimeoutInMinutes, new PushOptions { AllowOverwrite = true }); } } finally { if (tempFile != null) { File.Delete(tempFile); } } } private async Task PublishToFlatContainerAsync(IEnumerable<ITaskItem> taskItems, BlobFeedAction blobFeedAction) { if (taskItems.Any()) { using (var clientThrottle = new SemaphoreSlim(this.MaxClients, this.MaxClients)) { Log.LogMessage($"Uploading {taskItems.Count()} items..."); await Task.WhenAll(taskItems.Select( item => blobFeedAction.UploadAssetAsync( item, clientThrottle, UploadTimeoutInMinutes, CreatePushOptions()))); } } } private static IEnumerable<PackageArtifactModel> ConcatPackageArtifacts( IEnumerable<PackageArtifactModel> artifacts, IEnumerable<ITaskItem> items) { return artifacts.Concat(items .Select(CreatePackageArtifactModel)); } private static IEnumerable<BlobArtifactModel> ConcatBlobArtifacts( IEnumerable<BlobArtifactModel> artifacts, IEnumerable<ITaskItem> items) { return artifacts.Concat(items .Select(CreateBlobArtifactModel) .Where(blob => blob != null)); } private static PackageArtifactModel CreatePackageArtifactModel(ITaskItem item) { NupkgInfo info = new NupkgInfo(item.ItemSpec); return new PackageArtifactModel { Attributes = ParseCustomAttributes(item), Id = info.Id, Version = info.Version }; } private static BlobArtifactModel CreateBlobArtifactModel(ITaskItem item) { string path = item.GetMetadata("RelativeBlobPath"); // Only include assets in the manifest if they're in "assets/". if (path?.StartsWith(AssetsVirtualDir, StringComparison.Ordinal) == true) { return new BlobArtifactModel { Attributes = ParseCustomAttributes(item), Id = path.Substring(AssetsVirtualDir.Length) }; } return null; } private static Dictionary<string, string> ParseCustomAttributes(ITaskItem item) { return ParseManifestMetadataString(item.GetMetadata("ManifestArtifactData")); } private static Dictionary<string, string> ParseManifestMetadataString(string data) { if (string.IsNullOrEmpty(data)) { return new Dictionary<string, string>(); } return data.Split(ManifestDataPairSeparators, StringSplitOptions.RemoveEmptyEntries) .Select(pair => { int keyValueSeparatorIndex = pair.IndexOf('='); if (keyValueSeparatorIndex > 0) { return new { Key = pair.Substring(0, keyValueSeparatorIndex).Trim(), Value = pair.Substring(keyValueSeparatorIndex + 1).Trim() }; } return null; }) .Where(pair => pair != null) .ToDictionary(pair => pair.Key, pair => pair.Value); } private PushOptions CreatePushOptions() { return new PushOptions { AllowOverwrite = Overwrite, PassIfExistingItemIdentical = PassIfExistingItemIdentical }; } } }
// 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.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; namespace System.Net { internal static partial class NameResolutionPal { private static volatile bool s_initialized; private static readonly object s_initializedLock = new object(); private static readonly unsafe Interop.Winsock.LPLOOKUPSERVICE_COMPLETION_ROUTINE s_getAddrInfoExCallback = GetAddressInfoExCallback; private static bool s_getAddrInfoExSupported; public static void EnsureSocketsAreInitialized() { if (!s_initialized) { InitializeSockets(); } static void InitializeSockets() { lock (s_initializedLock) { if (!s_initialized) { SocketError errorCode = Interop.Winsock.WSAStartup(); if (errorCode != SocketError.Success) { // WSAStartup does not set LastWin32Error throw new SocketException((int)errorCode); } s_getAddrInfoExSupported = GetAddrInfoExSupportsOverlapped(); s_initialized = true; } } } } public static bool SupportsGetAddrInfoAsync { get { EnsureSocketsAreInitialized(); return s_getAddrInfoExSupported; } } public static unsafe SocketError TryGetAddrInfo(string name, bool justAddresses, out string hostName, out string[] aliases, out IPAddress[] addresses, out int nativeErrorCode) { aliases = Array.Empty<string>(); var hints = new Interop.Winsock.AddressInfo { ai_family = AddressFamily.Unspecified }; // Gets all address families if (!justAddresses) { hints.ai_flags = AddressInfoHints.AI_CANONNAME; } Interop.Winsock.AddressInfo* result = null; try { SocketError errorCode = (SocketError)Interop.Winsock.GetAddrInfoW(name, null, &hints, &result); if (errorCode != SocketError.Success) { nativeErrorCode = (int)errorCode; hostName = name; addresses = Array.Empty<IPAddress>(); return errorCode; } addresses = ParseAddressInfo(result, justAddresses, out hostName); nativeErrorCode = 0; return SocketError.Success; } finally { if (result != null) { Interop.Winsock.FreeAddrInfoW(result); } } } public static unsafe string TryGetNameInfo(IPAddress addr, out SocketError errorCode, out int nativeErrorCode) { SocketAddress address = new IPEndPoint(addr, 0).Serialize(); Span<byte> addressBuffer = address.Size <= 64 ? stackalloc byte[64] : new byte[address.Size]; for (int i = 0; i < address.Size; i++) { addressBuffer[i] = address[i]; } const int NI_MAXHOST = 1025; char* hostname = stackalloc char[NI_MAXHOST]; fixed (byte* addressBufferPtr = addressBuffer) { errorCode = Interop.Winsock.GetNameInfoW( addressBufferPtr, address.Size, hostname, NI_MAXHOST, null, // We don't want a service name 0, // so no need for buffer or length (int)Interop.Winsock.NameInfoFlags.NI_NAMEREQD); } if (errorCode == SocketError.Success) { nativeErrorCode = 0; return new string(hostname); } nativeErrorCode = (int)errorCode; return null; } public static unsafe string GetHostName() { // We do not cache the result in case the hostname changes. const int HostNameBufferLength = 256; byte* buffer = stackalloc byte[HostNameBufferLength]; if (Interop.Winsock.gethostname(buffer, HostNameBufferLength) != SocketError.Success) { throw new SocketException(); } return new string((sbyte*)buffer); } public static unsafe Task GetAddrInfoAsync(string hostName, bool justAddresses) { GetAddrInfoExContext* context = GetAddrInfoExContext.AllocateContext(); GetAddrInfoExState state; try { state = new GetAddrInfoExState(hostName, justAddresses); context->QueryStateHandle = state.CreateHandle(); } catch { GetAddrInfoExContext.FreeContext(context); throw; } var hints = new Interop.Winsock.AddressInfoEx { ai_family = AddressFamily.Unspecified }; // Gets all address families if (!justAddresses) { hints.ai_flags = AddressInfoHints.AI_CANONNAME; } SocketError errorCode = (SocketError)Interop.Winsock.GetAddrInfoExW( hostName, null, Interop.Winsock.NS_ALL, IntPtr.Zero, &hints, &context->Result, IntPtr.Zero, &context->Overlapped, s_getAddrInfoExCallback, &context->CancelHandle); if (errorCode != SocketError.IOPending) { ProcessResult(errorCode, context); } return state.Task; } private static unsafe void GetAddressInfoExCallback(int error, int bytes, NativeOverlapped* overlapped) { // Can be casted directly to GetAddrInfoExContext* because the overlapped is its first field GetAddrInfoExContext* context = (GetAddrInfoExContext*)overlapped; ProcessResult((SocketError)error, context); } private static unsafe void ProcessResult(SocketError errorCode, GetAddrInfoExContext* context) { try { GetAddrInfoExState state = GetAddrInfoExState.FromHandleAndFree(context->QueryStateHandle); if (errorCode == SocketError.Success) { IPAddress[] addresses = ParseAddressInfoEx(context->Result, state.JustAddresses, out string hostName); state.SetResult(state.JustAddresses ? (object) addresses : new IPHostEntry { HostName = hostName ?? state.HostName, Aliases = Array.Empty<string>(), AddressList = addresses }); } else { state.SetResult(ExceptionDispatchInfo.SetCurrentStackTrace(new SocketException((int)errorCode))); } } finally { GetAddrInfoExContext.FreeContext(context); } } private static unsafe IPAddress[] ParseAddressInfo(Interop.Winsock.AddressInfo* addressInfoPtr, bool justAddresses, out string hostName) { Debug.Assert(addressInfoPtr != null); // Count how many results we have. int addressCount = 0; for (Interop.Winsock.AddressInfo* result = addressInfoPtr; result != null; result = result->ai_next) { int addressLength = (int)result->ai_addrlen; if (result->ai_family == AddressFamily.InterNetwork) { if (addressLength == SocketAddressPal.IPv4AddressSize) { addressCount++; } } else if (SocketProtocolSupportPal.OSSupportsIPv6 && result->ai_family == AddressFamily.InterNetworkV6) { if (addressLength == SocketAddressPal.IPv6AddressSize) { addressCount++; } } } // Store them into the array. var addresses = new IPAddress[addressCount]; addressCount = 0; string canonicalName = justAddresses ? "NONNULLSENTINEL" : null; for (Interop.Winsock.AddressInfo* result = addressInfoPtr; result != null; result = result->ai_next) { if (canonicalName == null && result->ai_canonname != null) { canonicalName = Marshal.PtrToStringUni((IntPtr)result->ai_canonname); } int addressLength = (int)result->ai_addrlen; var socketAddress = new ReadOnlySpan<byte>(result->ai_addr, addressLength); if (result->ai_family == AddressFamily.InterNetwork) { if (addressLength == SocketAddressPal.IPv4AddressSize) { addresses[addressCount++] = CreateIPv4Address(socketAddress); } } else if (SocketProtocolSupportPal.OSSupportsIPv6 && result->ai_family == AddressFamily.InterNetworkV6) { if (addressLength == SocketAddressPal.IPv6AddressSize) { addresses[addressCount++] = CreateIPv6Address(socketAddress); } } } hostName = justAddresses ? null : canonicalName; return addresses; } private static unsafe IPAddress[] ParseAddressInfoEx(Interop.Winsock.AddressInfoEx* addressInfoExPtr, bool justAddresses, out string hostName) { Debug.Assert(addressInfoExPtr != null); // First count how many address results we have. int addressCount = 0; for (Interop.Winsock.AddressInfoEx* result = addressInfoExPtr; result != null; result = result->ai_next) { int addressLength = (int)result->ai_addrlen; if (result->ai_family == AddressFamily.InterNetwork) { if (addressLength == SocketAddressPal.IPv4AddressSize) { addressCount++; } } else if (SocketProtocolSupportPal.OSSupportsIPv6 && result->ai_family == AddressFamily.InterNetworkV6) { if (addressLength == SocketAddressPal.IPv6AddressSize) { addressCount++; } } } // Then store them into an array. var addresses = new IPAddress[addressCount]; addressCount = 0; string canonicalName = justAddresses ? "NONNULLSENTINEL" : null; for (Interop.Winsock.AddressInfoEx* result = addressInfoExPtr; result != null; result = result->ai_next) { if (canonicalName == null && result->ai_canonname != IntPtr.Zero) { canonicalName = Marshal.PtrToStringUni(result->ai_canonname); } int addressLength = (int)result->ai_addrlen; var socketAddress = new ReadOnlySpan<byte>(result->ai_addr, addressLength); if (result->ai_family == AddressFamily.InterNetwork) { if (addressLength == SocketAddressPal.IPv4AddressSize) { addresses[addressCount++] = CreateIPv4Address(socketAddress); } } else if (SocketProtocolSupportPal.OSSupportsIPv6 && result->ai_family == AddressFamily.InterNetworkV6) { if (addressLength == SocketAddressPal.IPv6AddressSize) { addresses[addressCount++] = CreateIPv6Address(socketAddress); } } } // Return the parsed host name (if we got one) and addresses. hostName = justAddresses ? null : canonicalName; return addresses; } private static unsafe IPAddress CreateIPv4Address(ReadOnlySpan<byte> socketAddress) { long address = (long)SocketAddressPal.GetIPv4Address(socketAddress) & 0x0FFFFFFFF; return new IPAddress(address); } private static unsafe IPAddress CreateIPv6Address(ReadOnlySpan<byte> socketAddress) { Span<byte> address = stackalloc byte[IPAddressParserStatics.IPv6AddressBytes]; SocketAddressPal.GetIPv6Address(socketAddress, address, out uint scope); return new IPAddress(address, scope); } private sealed class GetAddrInfoExState : IThreadPoolWorkItem { private AsyncTaskMethodBuilder<IPHostEntry> IPHostEntryBuilder; private AsyncTaskMethodBuilder<IPAddress[]> IPAddressArrayBuilder; private object _result; public GetAddrInfoExState(string hostName, bool justAddresses) { HostName = hostName; JustAddresses = justAddresses; if (justAddresses) { IPAddressArrayBuilder = AsyncTaskMethodBuilder<IPAddress[]>.Create(); _ = IPAddressArrayBuilder.Task; // force initialization } else { IPHostEntryBuilder = AsyncTaskMethodBuilder<IPHostEntry>.Create(); _ = IPHostEntryBuilder.Task; // force initialization } } public string HostName { get; } public bool JustAddresses { get; } public Task Task => JustAddresses ? (Task)IPAddressArrayBuilder.Task : IPHostEntryBuilder.Task; public void SetResult(object result) { // Store the result and then queue this object to the thread pool to actually complete the Tasks, as we // want to avoid invoking continuations on the Windows callback thread. Effectively we're manually // implementing TaskCreationOptions.RunContinuationsAsynchronously, which we can't use because we're // using AsyncTaskMethodBuilder, which we're using in order to create either a strongly-typed Task<IPHostEntry> // or Task<IPAddress[]> without allocating additional objects. Debug.Assert(result is Exception || result is IPAddress[] || result is IPHostEntry); _result = result; ThreadPool.UnsafeQueueUserWorkItem(this, preferLocal: false); } void IThreadPoolWorkItem.Execute() { if (JustAddresses) { if (_result is Exception e) { IPAddressArrayBuilder.SetException(e); } else { IPAddressArrayBuilder.SetResult((IPAddress[])_result); } } else { if (_result is Exception e) { IPHostEntryBuilder.SetException(e); } else { IPHostEntryBuilder.SetResult((IPHostEntry)_result); } } } public IntPtr CreateHandle() => GCHandle.ToIntPtr(GCHandle.Alloc(this, GCHandleType.Normal)); public static GetAddrInfoExState FromHandleAndFree(IntPtr handle) { GCHandle gcHandle = GCHandle.FromIntPtr(handle); var state = (GetAddrInfoExState)gcHandle.Target; gcHandle.Free(); return state; } } [StructLayout(LayoutKind.Sequential)] private unsafe struct GetAddrInfoExContext { public NativeOverlapped Overlapped; public Interop.Winsock.AddressInfoEx* Result; public IntPtr CancelHandle; public IntPtr QueryStateHandle; public static GetAddrInfoExContext* AllocateContext() { var context = (GetAddrInfoExContext*)Marshal.AllocHGlobal(sizeof(GetAddrInfoExContext)); *context = default; return context; } public static void FreeContext(GetAddrInfoExContext* context) { if (context->Result != null) { Interop.Winsock.FreeAddrInfoExW(context->Result); } Marshal.FreeHGlobal((IntPtr)context); } } } }
using System; using System.Messaging; using System.Text; using System.Text.RegularExpressions; using System.Net.Mail; namespace Codes.October.Tools { public sealed class Email { public static void Send( string server , string from , string[] tos , string subject , string body ) { try { Send(server, from, tos, null, null, subject, body, null, null); } finally { server = null; from = null; tos = null; subject = null; body = null; } } public static void Send( string server , string from , string[] tos , string subject , string body , string html ) { try { Send(server, from, tos, null, null, subject, body, html, null); } finally { server = null; from = null; tos = null; subject = null; body = null; html = null; } } public static void Send( string server , string from , string[] tos , string[] ccs , string[] bccs , string subject , string body , string html , string[] attachments ) { MailMessage mail = null; SmtpClient client = null; try { mail = new MailMessage(); mail.From = new MailAddress(from); foreach(string to in tos) { mail.To.Add(to); } foreach(string cc in ccs) { mail.CC.Add(cc); } foreach(string bcc in bccs) { mail.Bcc.Add(bcc); } foreach(string attachment in attachments) { mail.Attachments.Add(new Attachment(attachment)); } client = new SmtpClient(); client.Port = 25; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; client.Host = server; mail.Subject = subject; mail.Body = (html != null) ? html : body; client.Send(mail); } finally { mail = null; client = null; server = null; from = null; tos = null; ccs = null; bccs = null; subject = null; body = null; html = null; attachments = null; } } public static void SendToMSMQ( string queue , string from , string subject , string body , string[] tos , string[] ccs , string[] bccs ) { MessageQueue mq; Message msg; try { mq = new MessageQueue(queue); msg = new Message(); if (mq.CanWrite) { msg.Label = "Email"; msg.Body = BuildXmlBody(from, subject, body, tos, ccs, bccs, "text"); msg.Priority = MessagePriority.Normal; mq.Send(msg); mq.Close(); } } finally { mq = null; msg = null; queue = null; from = null; subject = null; body = null; tos = null; ccs = null; bccs = null; } } public static string BuildXmlBody ( string from , string subject , string body , string[] tos , string[] ccs , string[] bccs , string format ) { StringBuilder sb; try { sb = new StringBuilder(); sb.Append("<root>"); sb.AppendFormat("<emailformat><![CDATA[{0}]]></emailformat>", format); sb.AppendFormat("<from><![CDATA[{0}]]></from>", from); sb.AppendFormat("<subject><![CDATA[{0}]]></subject>", subject); sb.AppendFormat("<body><![CDATA[{0}]]></body>", body.Replace("<![CDATA[", "").Replace("]]>", "")); if (tos != null) { sb.Append("<tos>"); foreach (string to in tos) { sb.AppendFormat("<to><![CDATA[{0}]]></to>", to); } sb.Append("</tos>"); } if (ccs != null) { sb.Append("<ccs>"); foreach (string cc in ccs) { sb.AppendFormat("<cc><![CDATA[{0}]]></cc>", cc); } sb.Append("</ccs>"); } if (bccs != null) { sb.Append("<bccs>"); foreach (string bcc in bccs) { sb.AppendFormat("<bcc><![CDATA[{0}]]></bcc>", bcc); } sb.Append("</bccs>"); } sb.Append("</root>"); return sb.ToString(); } finally { sb = null; from = null; subject = null; body = null; tos = null; ccs = null; bccs = null; format = null; } } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using Microsoft.VisualStudio.TestTools.UnitTesting; using TestRunnerInterop; namespace PythonToolsUITestsRunner { [Ignore] // https://github.com/microsoft/PTVS/issues/5320 [TestClass] public class RemoveImportTests { #region UI test boilerplate public VsTestInvoker _vs => new VsTestInvoker( VsTestContext.Instance, // Remote container (DLL) name "Microsoft.PythonTools.Tests.PythonToolsUITests", // Remote class name $"PythonToolsUITests.{GetType().Name}" ); public TestContext TestContext { get; set; } [TestInitialize] public void TestInitialize() => VsTestContext.Instance.TestInitialize(TestContext.DeploymentDirectory); [TestCleanup] public void TestCleanup() => VsTestContext.Instance.TestCleanup(); [ClassCleanup] public static void ClassCleanup() => VsTestContext.Instance.Dispose(); #endregion [TestMethod, Priority(UITestPriority.P2)] [TestCategory("Installed")] public void FromImport1() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.FromImport1)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void FromImport2() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.FromImport2)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void FromImportParens1() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.FromImportParens1)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void FromImportParens2() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.FromImportParens2)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void FromImportParensTrailingComma1() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.FromImportParensTrailingComma1)); } [TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)] [TestCategory("Installed")] public void FromImportParensTrailingComma2() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.FromImportParensTrailingComma2)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void Import1() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.Import1)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void Import2() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.Import2)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void Import3() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.Import3)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void Import4() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.Import4)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void Import5() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.Import5)); } [TestMethod, Priority(UITestPriority.P2)] [TestCategory("Installed")] public void Import6() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.Import6)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void ImportComment() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.ImportComment)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void FromImportComment() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.FromImportComment)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void ImportDup() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.ImportDup)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void FromImportDup() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.FromImportDup)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void Import() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.Import)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void FromImport() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.FromImport)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void FutureImport() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.FutureImport)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void LocalScopeDontRemoveGlobal() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.LocalScopeDontRemoveGlobal)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void LocalScopeOnly() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.LocalScopeOnly)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void ImportTrailingWhitespace() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.ImportTrailingWhitespace)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void ClosureReference() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.ClosureReference)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void NameMangledUnmangled() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.NameMangledUnmangled)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void NameMangledMangled() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.NameMangledMangled)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void EmptyFuncDef1() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.EmptyFuncDef1)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void EmptyFuncDef2() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.EmptyFuncDef2)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void EmptyFuncDefWhitespace() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.EmptyFuncDefWhitespace)); } [TestMethod, Priority(UITestPriority.P0)] [TestCategory("Installed")] public void ImportStar() { _vs.RunTest(nameof(PythonToolsUITests.RemoveImportTests.ImportStar)); } } }
// 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.Security; using System.Text; using Internal.Runtime.CompilerServices; namespace System.Globalization { // needs to be kept in sync with CalendarDataType in System.Globalization.Native internal enum CalendarDataType { Uninitialized = 0, NativeName = 1, MonthDay = 2, ShortDates = 3, LongDates = 4, YearMonths = 5, DayNames = 6, AbbrevDayNames = 7, MonthNames = 8, AbbrevMonthNames = 9, SuperShortDayNames = 10, MonthGenitiveNames = 11, AbbrevMonthGenitiveNames = 12, EraNames = 13, AbbrevEraNames = 14, } internal partial class CalendarData { private bool LoadCalendarDataFromSystem(String localeName, CalendarId calendarId) { bool result = true; result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.NativeName, out this.sNativeName); result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.MonthDay, out this.sMonthDay); this.sMonthDay = NormalizeDatePattern(this.sMonthDay); result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.ShortDates, out this.saShortDates); result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.LongDates, out this.saLongDates); result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.YearMonths, out this.saYearMonths); result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.DayNames, out this.saDayNames); result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.AbbrevDayNames, out this.saAbbrevDayNames); result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.SuperShortDayNames, out this.saSuperShortDayNames); result &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthNames, out this.saMonthNames); result &= EnumMonthNames(localeName, calendarId, CalendarDataType.AbbrevMonthNames, out this.saAbbrevMonthNames); result &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthGenitiveNames, out this.saMonthGenitiveNames); result &= EnumMonthNames(localeName, calendarId, CalendarDataType.AbbrevMonthGenitiveNames, out this.saAbbrevMonthGenitiveNames); result &= EnumEraNames(localeName, calendarId, CalendarDataType.EraNames, out this.saEraNames); result &= EnumEraNames(localeName, calendarId, CalendarDataType.AbbrevEraNames, out this.saAbbrevEraNames); return result; } internal static int GetTwoDigitYearMax(CalendarId calendarId) { // There is no user override for this value on Linux or in ICU. // So just return -1 to use the hard-coded defaults. return -1; } // Call native side to figure out which calendars are allowed internal static int GetCalendars(string localeName, bool useUserOverride, CalendarId[] calendars) { Debug.Assert(!GlobalizationMode.Invariant); // NOTE: there are no 'user overrides' on Linux int count = Interop.Globalization.GetCalendars(localeName, calendars, calendars.Length); // ensure there is at least 1 calendar returned if (count == 0 && calendars.Length > 0) { calendars[0] = CalendarId.GREGORIAN; count = 1; } return count; } private static bool SystemSupportsTaiwaneseCalendar() { return true; } // PAL Layer ends here private static bool GetCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string calendarString) { Debug.Assert(!GlobalizationMode.Invariant); return Interop.CallStringMethod( (locale, calId, type, stringBuilder) => Interop.Globalization.GetCalendarInfo( locale, calId, type, stringBuilder, stringBuilder.Capacity), localeName, calendarId, dataType, out calendarString); } private static bool EnumDatePatterns(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] datePatterns) { datePatterns = null; EnumCalendarsData callbackContext = new EnumCalendarsData(); callbackContext.Results = new List<string>(); callbackContext.DisallowDuplicates = true; bool result = EnumCalendarInfo(localeName, calendarId, dataType, ref callbackContext); if (result) { List<string> datePatternsList = callbackContext.Results; datePatterns = new string[datePatternsList.Count]; for (int i = 0; i < datePatternsList.Count; i++) { datePatterns[i] = NormalizeDatePattern(datePatternsList[i]); } } return result; } /// <summary> /// The ICU date format characters are not exactly the same as the .NET date format characters. /// NormalizeDatePattern will take in an ICU date pattern and return the equivalent .NET date pattern. /// </summary> /// <remarks> /// see Date Field Symbol Table in http://userguide.icu-project.org/formatparse/datetime /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx /// </remarks> private static string NormalizeDatePattern(string input) { StringBuilder destination = StringBuilderCache.Acquire(input.Length); int index = 0; while (index < input.Length) { switch (input[index]) { case '\'': // single quotes escape characters, like 'de' in es-SP // so read verbatim until the next single quote destination.Append(input[index++]); while (index < input.Length) { char current = input[index++]; destination.Append(current); if (current == '\'') { break; } } break; case 'E': case 'e': case 'c': // 'E' in ICU is the day of the week, which maps to 3 or 4 'd's in .NET // 'e' in ICU is the local day of the week, which has no representation in .NET, but // maps closest to 3 or 4 'd's in .NET // 'c' in ICU is the stand-alone day of the week, which has no representation in .NET, but // maps closest to 3 or 4 'd's in .NET NormalizeDayOfWeek(input, destination, ref index); break; case 'L': case 'M': // 'L' in ICU is the stand-alone name of the month, // which maps closest to 'M' in .NET since it doesn't support stand-alone month names in patterns // 'M' in both ICU and .NET is the month, // but ICU supports 5 'M's, which is the super short month name int occurrences = CountOccurrences(input, input[index], ref index); if (occurrences > 4) { // 5 'L's or 'M's in ICU is the super short name, which maps closest to MMM in .NET occurrences = 3; } destination.Append('M', occurrences); break; case 'G': // 'G' in ICU is the era, which maps to 'g' in .NET occurrences = CountOccurrences(input, 'G', ref index); // it doesn't matter how many 'G's, since .NET only supports 'g' or 'gg', and they // have the same meaning destination.Append('g'); break; case 'y': // a single 'y' in ICU is the year with no padding or trimming. // a single 'y' in .NET is the year with 1 or 2 digits // so convert any single 'y' to 'yyyy' occurrences = CountOccurrences(input, 'y', ref index); if (occurrences == 1) { occurrences = 4; } destination.Append('y', occurrences); break; default: const string unsupportedDateFieldSymbols = "YuUrQqwWDFg"; Debug.Assert(unsupportedDateFieldSymbols.IndexOf(input[index]) == -1, string.Format(CultureInfo.InvariantCulture, "Encountered an unexpected date field symbol '{0}' from ICU which has no known corresponding .NET equivalent.", input[index])); destination.Append(input[index++]); break; } } return StringBuilderCache.GetStringAndRelease(destination); } private static void NormalizeDayOfWeek(string input, StringBuilder destination, ref int index) { char dayChar = input[index]; int occurrences = CountOccurrences(input, dayChar, ref index); occurrences = Math.Max(occurrences, 3); if (occurrences > 4) { // 5 and 6 E/e/c characters in ICU is the super short names, which maps closest to ddd in .NET occurrences = 3; } destination.Append('d', occurrences); } private static int CountOccurrences(string input, char value, ref int index) { int startIndex = index; while (index < input.Length && input[index] == value) { index++; } return index - startIndex; } private static bool EnumMonthNames(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] monthNames) { monthNames = null; EnumCalendarsData callbackContext = new EnumCalendarsData(); callbackContext.Results = new List<string>(); bool result = EnumCalendarInfo(localeName, calendarId, dataType, ref callbackContext); if (result) { // the month-name arrays are expected to have 13 elements. If ICU only returns 12, add an // extra empty string to fill the array. if (callbackContext.Results.Count == 12) { callbackContext.Results.Add(string.Empty); } monthNames = callbackContext.Results.ToArray(); } return result; } private static bool EnumEraNames(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] eraNames) { bool result = EnumCalendarInfo(localeName, calendarId, dataType, out eraNames); // .NET expects that only the Japanese calendars have more than 1 era. // So for other calendars, only return the latest era. if (calendarId != CalendarId.JAPAN && calendarId != CalendarId.JAPANESELUNISOLAR && eraNames.Length > 0) { string[] latestEraName = new string[] { eraNames[eraNames.Length - 1] }; eraNames = latestEraName; } return result; } internal static bool EnumCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] calendarData) { calendarData = null; EnumCalendarsData callbackContext = new EnumCalendarsData(); callbackContext.Results = new List<string>(); bool result = EnumCalendarInfo(localeName, calendarId, dataType, ref callbackContext); if (result) { calendarData = callbackContext.Results.ToArray(); } return result; } private static unsafe bool EnumCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, ref EnumCalendarsData callbackContext) { return Interop.Globalization.EnumCalendarInfo(EnumCalendarInfoCallback, localeName, calendarId, dataType, (IntPtr)Unsafe.AsPointer(ref callbackContext)); } private static unsafe void EnumCalendarInfoCallback(string calendarString, IntPtr context) { try { ref EnumCalendarsData callbackContext = ref Unsafe.As<byte, EnumCalendarsData>(ref *(byte*)context); if (callbackContext.DisallowDuplicates) { foreach (string existingResult in callbackContext.Results) { if (string.Equals(calendarString, existingResult, StringComparison.Ordinal)) { // the value is already in the results, so don't add it again return; } } } callbackContext.Results.Add(calendarString); } catch (Exception e) { Debug.Fail(e.ToString()); // we ignore the managed exceptions here because EnumCalendarInfoCallback will get called from the native code. // If we don't ignore the exception here that can cause the runtime to fail fast. } } private struct EnumCalendarsData { public List<string> Results; public bool DisallowDuplicates; } } }
using System.Text; namespace BulletML.Equationator { /// <summary> /// This is a single text token from an equation. /// The first step to compiling an equation is breaking it up into a list tokens and determining what is in those tokens. /// </summary> public class Token { #region Members /// <summary> /// Gets the token text. /// </summary> /// <value>The token text.</value> public string TokenText { get; private set; } /// <summary> /// Gets the type of token. /// </summary> /// <value>The type of token.</value> public TokenType TypeOfToken { get; private set; } #endregion Members #region Methods /// <summary> /// Initializes a new instance of the <see cref="Equationator.Token"/> class. /// </summary> public Token() { TypeOfToken = TokenType.Invalid; } /// <summary> /// Pull one token out of a string. /// </summary> /// <returns>int: the new current index in the string. Use this as the start point for parsing the next token</returns> /// <param name="strEquationText">The full text string we are tokenizing</param> /// <param name="iStartIndex">The character index in the string where to start tokenizing</param> public int ParseToken(string strEquationText, int iStartIndex) { //Walk through the text and try to parse it out into an expression while (iStartIndex < strEquationText.Length) { //First check if we are reading in a number if (IsNumberCharacter(strEquationText, iStartIndex)) { //read a number and return the new index return ParseNumberToken(strEquationText, iStartIndex); } else if (IsOperatorCharacter(strEquationText, iStartIndex)) { //We found an operator value... TypeOfToken = TokenType.Operator; TokenText = strEquationText[iStartIndex].ToString(); return ++iStartIndex; } switch (strEquationText[iStartIndex]) { case '$': { //read a function/param and return the new index return ParseFunctionToken(strEquationText, iStartIndex); } case '(': { //we found an open paren! TypeOfToken = TokenType.OpenParen; TokenText = strEquationText[iStartIndex].ToString(); return ++iStartIndex; } case ')': { //we found a close paren! TypeOfToken = TokenType.CloseParen; TokenText = strEquationText[iStartIndex].ToString(); return ++iStartIndex; } case '?': { //We found a random number TypeOfToken = TokenType.Rand; TokenText = strEquationText[iStartIndex].ToString(); return ++iStartIndex; } case 'x': { //We are going to cheat and use 'x' as $1 return ParamCheat("1", iStartIndex); } case 'y': { //We are going to cheat and use 'x' as $2 return ParamCheat("2", iStartIndex); } case 'z': { //We are going to cheat and use 'x' as $3 return ParamCheat("3", iStartIndex); } } //We found some white space iStartIndex++; } return iStartIndex; } /// <summary> /// Our token is a number, parse the full text out of the expression /// </summary> /// <returns>The index in the string after our number</returns> /// <param name="strEquationText">String equation text.</param> /// <param name="iIndex">start index of this token.</param> private int ParseNumberToken(string strEquationText, int iIndex) { //Set this token as a number TypeOfToken = TokenType.Number; //Parse the string into a number StringBuilder word = new StringBuilder(); while (IsNumberCharacter(strEquationText, iIndex)) { //Add the digit/decimal to the end of the number word.Append(strEquationText[iIndex++]); //If we have reached the end of the text, quit reading if (iIndex >= strEquationText.Length) { break; } } //grab the resulting value and return the new string index TokenText = word.ToString(); return iIndex; } private int ParseFunctionToken(string strEquationText, int iIndex) { //first, skip the dollar sign iIndex++; //check if it is a param or a function call StringBuilder word = new StringBuilder(); if (strEquationText[iIndex] >= '0' && strEquationText[iIndex] <= '9') { //We have a param value TypeOfToken = TokenType.Param; //Parse the param until we hit the end while (strEquationText[iIndex] >= '0' && strEquationText[iIndex] <= '9') { word.Append(strEquationText[iIndex++]); //If we have reached the end of the text, quit reading if (iIndex >= strEquationText.Length) { break; } } } else { //TODO: Parse the function call until we hit the next token //Get the function name string funcName = strEquationText.Substring(iIndex, 4); if ("tier" == funcName) { //If the function name is "tier", this is an extra special token TypeOfToken = TokenType.Tier; } else { //We have a function call TypeOfToken = TokenType.Function; } //check if the token is stored in our grammar dictionary word.Append(funcName); iIndex += 4; } //grab the resulting value and return the new string index TokenText = word.ToString(); return iIndex; } private int ParamCheat(string param, int iIndex) { TypeOfToken = TokenType.Param; TokenText = param; return ++iIndex; } /// <summary> /// Check whether the character at an index is a number /// </summary> /// <returns><c>true</c> if this instance is number character the specified strEquationText iIndex; otherwise, <c>false</c>.</returns> /// <param name="strEquationText">String equation text.</param> /// <param name="iIndex">I index.</param> static private bool IsNumberCharacter(string strEquationText, int iIndex) { return (('0' <= strEquationText[iIndex] && strEquationText[iIndex] <= '9') || strEquationText[iIndex] == '.'); } /// <summary> /// Check whether the character at an index is an operator character /// </summary> /// <returns><c>true</c> if this instance is number character the specified strEquationText iIndex; otherwise, <c>false</c>.</returns> /// <param name="strEquationText">String equation text.</param> /// <param name="iIndex">I index.</param> static private bool IsOperatorCharacter(string strEquationText, int iIndex) { switch (strEquationText[iIndex]) { case '*': return true; case '/': return true; case '+': return true; case '-': return true; case '^': return true; case '%': return true; } return false; } #endregion Methods } }
// // AudioSessions.cs: // // Authors: // Miguel de Icaza (miguel@novell.com) // AKIHIRO Uehara (u-akihiro@reinforce-lab.com) // // Copyright 2009, 2010 Novell, Inc // Copyright 2010, Reinforce Lab. // // 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.Text; using System.Collections.Generic; using System.Runtime.InteropServices; using MonoMac.CoreFoundation; namespace MonoMac.AudioToolbox { public enum AudioFormatType { LinearPCM = 0x6c70636d, AC3 = 0x61632d33, CAC3 = 0x63616333, AppleIMA4 = 0x696d6134, MPEG4AAC = 0x61616320, MPEG4CELP = 0x63656c70, MPEG4HVXC = 0x68767863, MPEG4TwinVQ = 0x74777671, MACE3 = 0x4d414333, MACE6 = 0x4d414336, ULaw = 0x756c6177, ALaw = 0x616c6177, QDesign = 0x51444d43, QDesign2 = 0x51444d32, QUALCOMM = 0x51636c70, MPEGLayer1 = 0x2e6d7031, MPEGLayer2 = 0x2e6d7032, MPEGLayer3 = 0x2e6d7033, TimeCode = 0x74696d65, MIDIStream = 0x6d696469, ParameterValueStream = 0x61707673, AppleLossless = 0x616c6163, MPEG4AAC_HE = 0x61616368, MPEG4AAC_LD = 0x6161636c, MPEG4AAC_HE_V2 = 0x61616370, MPEG4AAC_Spatial = 0x61616373, AMR = 0x73616d72, Audible = 0x41554442, iLBC = 0x696c6263, DVIIntelIMA = 0x6d730011, MicrosoftGSM = 0x6d730031, AES3 = 0x61657333, MPEG4AAC_ELD = 0x61616365 } [Flags] public enum AudioFormatFlags { IsFloat = (1 << 0), // 0x1 IsBigEndian = (1 << 1), // 0x2 IsSignedInteger = (1 << 2), // 0x4 IsPacked = (1 << 3), // 0x8 IsAlignedHigh = (1 << 4), // 0x10 IsNonInterleaved = (1 << 5), // 0x20 IsNonMixable = (1 << 6), // 0x40 FlagsAreAllClear = (1 << 31), LinearPCMIsFloat = (1 << 0), // 0x1 LinearPCMIsBigEndian = (1 << 1), // 0x2 LinearPCMIsSignedInteger = (1 << 2), // 0x4 LinearPCMIsPacked = (1 << 3), // 0x8 LinearPCMIsAlignedHigh = (1 << 4), // 0x10 LinearPCMIsNonInterleaved = (1 << 5), // 0x20 LinearPCMIsNonMixable = (1 << 6), // 0x40 LinearPCMSampleFractionShift = 7, LinearPCMSampleFractionMask = (0x3F << LinearPCMSampleFractionShift), LinearPCMFlagsAreAllClear = FlagsAreAllClear, AppleLossless16BitSourceData = 1, AppleLossless20BitSourceData = 2, AppleLossless24BitSourceData = 3, AppleLossless32BitSourceData = 4 } [StructLayout(LayoutKind.Sequential)] public struct AudioStreamBasicDescription { public double SampleRate; [Obsolete ("Use the strongly-typed Format property instead")] public int FormatID { get { return (int) Format; } set { Format = (AudioFormatType) value; } } public AudioFormatType Format; public AudioFormatFlags FormatFlags; public int BytesPerPacket; public int FramesPerPacket; public int BytesPerFrame; public int ChannelsPerFrame; public int BitsPerChannel; public int Reserved; public override string ToString () { return String.Format ("[SampleRate={0} FormatID={1} FormatFlags={2} BytesPerPacket={3} FramesPerPacket={4} BytesPerFrame={5} ChannelsPerFrame={6} BitsPerChannel={7}]", SampleRate, Format, FormatFlags, BytesPerPacket, FramesPerPacket, BytesPerFrame, ChannelsPerFrame, BitsPerChannel); } } [StructLayout(LayoutKind.Sequential)] public struct AudioStreamPacketDescription { public long StartOffset; public int VariableFramesInPacket; public int DataByteSize; public override string ToString () { return String.Format ("StartOffset={0} VariableFramesInPacket={1} DataByteSize={2}", StartOffset, VariableFramesInPacket, DataByteSize); } } [Flags] public enum AudioChannelFlags { AllOff = 0, RectangularCoordinates = 1 << 0, SphericalCoordinates = 1 << 1, Meters = 1 << 2 } public enum AudioChannelLabel { Unknown = -1, Unused = 0, UseCoordinates = 100, Left = 1, Right = 2, Center = 3, LFEScreen = 4, LeftSurround = 5, RightSurround = 6, LeftCenter = 7, RightCenter = 8, CenterSurround = 9, LeftSurroundDirect = 10, RightSurroundDirect = 11, TopCenterSurround = 12, VerticalHeightLeft = 13, VerticalHeightCenter = 14, VerticalHeightRight = 15, TopBackLeft = 16, TopBackCenter = 17, TopBackRight = 18, RearSurroundLeft = 33, RearSurroundRight = 34, LeftWide = 35, RightWide = 36, LFE2 = 37, LeftTotal = 38, RightTotal = 39, HearingImpaired = 40, Narration = 41, Mono = 42, DialogCentricMix = 43, CenterSurroundDirect = 44, Haptic = 45, // first order ambisonic channels Ambisonic_W = 200, Ambisonic_X = 201, Ambisonic_Y = 202, Ambisonic_Z = 203, // Mid/Side Recording MS_Mid = 204, MS_Side = 205, // X-Y Recording XY_X = 206, XY_Y = 207, // other HeadphonesLeft = 301, HeadphonesRight = 302, ClickTrack = 304, ForeignLanguage = 305, // generic discrete channel Discrete = 400, // numbered discrete channel Discrete_0 = (1<<16) | 0, Discrete_1 = (1<<16) | 1, Discrete_2 = (1<<16) | 2, Discrete_3 = (1<<16) | 3, Discrete_4 = (1<<16) | 4, Discrete_5 = (1<<16) | 5, Discrete_6 = (1<<16) | 6, Discrete_7 = (1<<16) | 7, Discrete_8 = (1<<16) | 8, Discrete_9 = (1<<16) | 9, Discrete_10 = (1<<16) | 10, Discrete_11 = (1<<16) | 11, Discrete_12 = (1<<16) | 12, Discrete_13 = (1<<16) | 13, Discrete_14 = (1<<16) | 14, Discrete_15 = (1<<16) | 15, Discrete_65535 = (1<<16) | 65535 } public class AudioChannelDescription { public AudioChannelLabel Label; public AudioChannelFlags Flags; public float [] Coords; public override string ToString () { return String.Format ("[id={0} {1} - {2},{3},{4}", Label, Flags, Coords [0], Coords[1], Coords[2]); } } public enum AudioChannelLayoutTag { UseChannelDescriptions = (0<<16) | 0, UseChannelBitmap = (1<<16) | 0, Mono = (100<<16) | 1, Stereo = (101<<16) | 2, StereoHeadphones = (102<<16) | 2, MatrixStereo = (103<<16) | 2, MidSide = (104<<16) | 2, XY = (105<<16) | 2, Binaural = (106<<16) | 2, Ambisonic_B_Format = (107<<16) | 4, Quadraphonic = (108<<16) | 4, Pentagonal = (109<<16) | 5, Hexagonal = (110<<16) | 6, Octagonal = (111<<16) | 8, Cube = (112<<16) | 8, MPEG_1_0 = Mono, MPEG_2_0 = Stereo, MPEG_3_0_A = (113<<16) | 3, MPEG_3_0_B = (114<<16) | 3, MPEG_4_0_A = (115<<16) | 4, MPEG_4_0_B = (116<<16) | 4, MPEG_5_0_A = (117<<16) | 5, MPEG_5_0_B = (118<<16) | 5, MPEG_5_0_C = (119<<16) | 5, MPEG_5_0_D = (120<<16) | 5, MPEG_5_1_A = (121<<16) | 6, MPEG_5_1_B = (122<<16) | 6, MPEG_5_1_C = (123<<16) | 6, MPEG_5_1_D = (124<<16) | 6, MPEG_6_1_A = (125<<16) | 7, MPEG_7_1_A = (126<<16) | 8, MPEG_7_1_B = (127<<16) | 8, MPEG_7_1_C = (128<<16) | 8, Emagic_Default_7_1 = (129<<16) | 8, SMPTE_DTV = (130<<16) | 8, ITU_1_0 = Mono, ITU_2_0 = Stereo, ITU_2_1 = (131<<16) | 3, ITU_2_2 = (132<<16) | 4, ITU_3_0 = MPEG_3_0_A, ITU_3_1 = MPEG_4_0_A, ITU_3_2 = MPEG_5_0_A, ITU_3_2_1 = MPEG_5_1_A, ITU_3_4_1 = MPEG_7_1_C, DVD_0 = Mono, DVD_1 = Stereo, DVD_2 = ITU_2_1, DVD_3 = ITU_2_2, DVD_4 = (133<<16) | 3, DVD_5 = (134<<16) | 4, DVD_6 = (135<<16) | 5, DVD_7 = MPEG_3_0_A, DVD_8 = MPEG_4_0_A, DVD_9 = MPEG_5_0_A, DVD_10 = (136<<16) | 4, DVD_11 = (137<<16) | 5, DVD_12 = MPEG_5_1_A, DVD_13 = DVD_8, DVD_14 = DVD_9, DVD_15 = DVD_10, DVD_16 = DVD_11, DVD_17 = DVD_12, DVD_18 = (138<<16) | 5, DVD_19 = MPEG_5_0_B, DVD_20 = MPEG_5_1_B, AudioUnit_4 = Quadraphonic, AudioUnit_5 = Pentagonal, AudioUnit_6 = Hexagonal, AudioUnit_8 = Octagonal, AudioUnit_5_0 = MPEG_5_0_B, AudioUnit_6_0 = (139<<16) | 6, AudioUnit_7_0 = (140<<16) | 7, AudioUnit_7_0_Front = (148<<16) | 7, AudioUnit_5_1 = MPEG_5_1_A, AudioUnit_6_1 = MPEG_6_1_A, AudioUnit_7_1 = MPEG_7_1_C, AudioUnit_7_1_Front = MPEG_7_1_A, AAC_3_0 = MPEG_3_0_B, AAC_Quadraphonic = Quadraphonic, AAC_4_0 = MPEG_4_0_B, AAC_5_0 = MPEG_5_0_D, AAC_5_1 = MPEG_5_1_D, AAC_6_0 = (141<<16) | 6, AAC_6_1 = (142<<16) | 7, AAC_7_0 = (143<<16) | 7, AAC_7_1 = MPEG_7_1_B, AAC_Octagonal = (144<<16) | 8, TMH_10_2_std = (145<<16) | 16, TMH_10_2_full = (146<<16) | 21, AC3_1_0_1 = (149<<16) | 2, AC3_3_0 = (150<<16) | 3, AC3_3_1 = (151<<16) | 4, AC3_3_0_1 = (152<<16) | 4, AC3_2_1_1 = (153<<16) | 4, AC3_3_1_1 = (154<<16) | 5, EAC_6_0_A = (155<<16) | 6, EAC_7_0_A = (156<<16) | 7, EAC3_6_1_A = (157<<16) | 7, EAC3_6_1_B = (158<<16) | 7, EAC3_6_1_C = (159<<16) | 7, EAC3_7_1_A = (160<<16) | 8, EAC3_7_1_B = (161<<16) | 8, EAC3_7_1_C = (162<<16) | 8, EAC3_7_1_D = (163<<16) | 8, EAC3_7_1_E = (164<<16) | 8, EAC3_7_1_F = (165<<16) | 8, EAC3_7_1_G = (166<<16) | 8, EAC3_7_1_H = (167<<16) | 8, DTS_3_1 = (168<<16) | 4, DTS_4_1 = (169<<16) | 5, DTS_6_0_A = (170<<16) | 6, DTS_6_0_B = (171<<16) | 6, DTS_6_0_C = (172<<16) | 6, DTS_6_1_A = (173<<16) | 7, DTS_6_1_B = (174<<16) | 7, DTS_6_1_C = (175<<16) | 7, DTS_7_0 = (176<<16) | 7, DTS_7_1 = (177<<16) | 8, DTS_8_0_A = (178<<16) | 8, DTS_8_0_B = (179<<16) | 8, DTS_8_1_A = (180<<16) | 9, DTS_8_1_B = (181<<16) | 9, DTS_6_1_D = (182<<16) | 7, DiscreteInOrder = (147<<16) | 0, // needs to be ORed with the actual number of channels Unknown = unchecked ((int)(0xFFFF0000)) // needs to be ORed with the actual number of channels } public class AudioChannelLayout { [Obsolete ("Use the strongly typed enum AudioTag instead")] public int Tag { get { return (int) AudioTag; } set { AudioTag = (AudioChannelLayoutTag) value; } } public AudioChannelLayoutTag AudioTag; public int Bitmap; public AudioChannelDescription [] Channels ; public override string ToString () { return String.Format ("AudioChannelLayout: Tag={0} Bitmap={1} Channels={2}", AudioTag, Bitmap, Channels.Length); } } [StructLayout(LayoutKind.Sequential)] public struct SmpteTime { public short Subframes; public short SubframeDivisor; public uint Counter; public uint Type; public uint Flags; public short Hours; public short Minutes; public short Seconds; public short Frames; public override string ToString () { return String.Format ("[Subframes={0},Divisor={1},Counter={2},Type={3},Flags={4},Hours={5},Minutes={6},Seconds={7},Frames={8}]", Subframes, SubframeDivisor, Counter, Type, Flags, Hours, Minutes, Seconds, Frames); } } [StructLayout(LayoutKind.Sequential)] public struct AudioTimeStamp { [Flags] public enum AtsFlags { SampleTimeValid = (1 << 0), HostTimeValid = (1 << 1), RateScalarValid = (1 << 2), WordClockTimeValid = (1 << 3), SmpteTimeValid = (1 << 4), SampleHostTimeValid = SampleTimeValid | HostTimeValid } public double SampleTime; public ulong HostTime; public double RateScalar; public ulong WordClockTime; public SmpteTime SMPTETime; public AtsFlags Flags; public uint Reserved; public override string ToString () { var sb = new StringBuilder ("{"); if ((Flags & AtsFlags.SampleTimeValid) != 0) sb.Append ("SampleTime=" + SampleTime.ToString ()); if ((Flags & AtsFlags.HostTimeValid) != 0){ if (sb.Length > 0) sb.Append (','); sb.Append ("HostTime=" + HostTime.ToString ()); } if ((Flags & AtsFlags.RateScalarValid) != 0){ if (sb.Length > 0) sb.Append (','); sb.Append ("RateScalar=" + RateScalar.ToString ()); } if ((Flags & AtsFlags.WordClockTimeValid) != 0){ if (sb.Length > 0) sb.Append (','); sb.Append ("WordClock=" + HostTime.ToString () + ","); } if ((Flags & AtsFlags.SmpteTimeValid) != 0){ if (sb.Length > 0) sb.Append (','); sb.Append ("SmpteTime=" + SMPTETime.ToString ()); } sb.Append ("}"); return sb.ToString (); } } [StructLayout(LayoutKind.Sequential)] public struct AudioBuffer { public int NumberChannels; public int DataByteSize; public IntPtr Data; public override string ToString () { return string.Format ("[channels={0},dataByteSize={1},ptrData=0x{2:x}]", NumberChannels, DataByteSize, Data); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Lab7.Areas.HelpPage.ModelDescriptions; using Lab7.Areas.HelpPage.Models; namespace Lab7.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } if (complexTypeDescription != null) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * 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 ShiftLeftLogicalUInt321() { var test = new SimpleUnaryOpTest__ShiftLeftLogicalUInt321(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.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 (Sse2.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 (Sse2.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__ShiftLeftLogicalUInt321 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(UInt32); private const int RetElementCount = VectorSize / sizeof(UInt32); private static UInt32[] _data = new UInt32[Op1ElementCount]; private static Vector128<UInt32> _clsVar; private Vector128<UInt32> _fld; private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable; static SimpleUnaryOpTest__ShiftLeftLogicalUInt321() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__ShiftLeftLogicalUInt321() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); } _dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.ShiftLeftLogical( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.ShiftLeftLogical( Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.ShiftLeftLogical( Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.ShiftLeftLogical( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr); var result = Sse2.ShiftLeftLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftLeftLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftLeftLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ShiftLeftLogicalUInt321(); var result = Sse2.ShiftLeftLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.ShiftLeftLogical(_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(Vector128<UInt32> firstOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt32[] firstOp, UInt32[] result, [CallerMemberName] string method = "") { if ((uint)(firstOp[0] << 1) != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((uint)(firstOp[i] << 1) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.ShiftLeftLogical)}<UInt32>(Vector128<UInt32><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.IO; namespace PSWinCom.Gateway.Client { /// <summary> /// Delegate for ConnectionReceived event /// </summary> public delegate void ConnectionReceivedHandler(Stream inStream, Stream outStream); /// <summary> /// ServerSocket is a simple asynchronous Socket Server that can be configured to listen for /// incoming connections on a given port. New connections generates an Event suitable for /// use with the SMSClient for handling incoming messages and delivery reports. /// </summary> public class ServerSocket { // State object for reading client data asynchronously private class StateObject { // Client socket. public Socket workSocket = null; // Size of receive buffer. public const int BufferSize = 1024; // Receive buffer. public byte[] buffer = new byte[BufferSize]; // Received data string. public StringBuilder sb = new StringBuilder(); } /// <summary> /// This event is fired whenever a connection is established on the port that the socket server /// is listening on. The event has two parameters, one input stream and one output stream. They /// should be used directly as parameters into the HandleIncomingMessages() method on your /// SMSClient object. /// </summary> public static event ConnectionReceivedHandler ConnectionReceived; private static int _Port = 1112; private static bool _IsListening; private static Socket listener = null; /// <summary> /// Local port to listen on. /// </summary> public int Port { get { return _Port; } set { _Port = value; } } /// <summary> /// Flag indicating wether socket is listening or not. /// </summary> public bool IsListening { get { return _IsListening; } set { _IsListening = value; } } /// <summary> /// Default constructor /// </summary> public ServerSocket() { } /// <summary> /// Initiate listening on chosen local port. This is a non-blocking operation, and the /// socket will keep listening until StopListening() is called. Each new connection will /// generate ConnectionReceived events. /// </summary> public void StartListening() { if(_IsListening) return; // Data buffer for incoming data. byte[] bytes = new Byte[1024]; // Establish the local endpoint for the socket. // The DNS name of the computer // running the listener is "host.contoso.com". IPAddress ipAddress = IPAddress.Any; IPEndPoint localEndPoint = new IPEndPoint(ipAddress, _Port); // Create a TCP/IP socket. listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); // Bind the socket to the local endpoint and listen for incoming connections. try { listener.Bind(localEndPoint); listener.Listen(10); // Start an asynchronous socket to listen for connections. listener.BeginAccept( new AsyncCallback(AcceptCallback), listener ); _IsListening = true; } catch (Exception e) { _IsListening = false; } } /// <summary> /// Terminate the listening. /// </summary> public void StopListening() { if(_IsListening) listener.Close(); _IsListening = false; } private static void AcceptCallback(IAsyncResult ar) { try { // Get the socket that handles the client request. Socket listener = (Socket) ar.AsyncState; Socket handler = listener.EndAccept(ar); // Create the state object. StateObject state = new StateObject(); state.workSocket = handler; handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } catch(Exception e) {} } private static void ReadCallback(IAsyncResult ar) { String content = String.Empty; // Retrieve the state object and the handler socket // from the asynchronous state object. StateObject state = (StateObject) ar.AsyncState; Socket handler = state.workSocket; // Read data from the client socket. int bytesRead = handler.EndReceive(ar); if (bytesRead > 0) { // There might be more data, so store the data received so far. state.sb.Append(Encoding.GetEncoding("ISO-8859-1").GetString(state.buffer, 0, bytesRead)); // Check for end-of-file tag. If it is not there, read // more data. content = state.sb.ToString(); if (content.IndexOf("</MSGLST>") > -1) { // Fire event with in and out stream objects MemoryStream inMS = new MemoryStream(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(content)); MemoryStream outMS = new MemoryStream(); OnConnectionReceived(inMS, outMS); // Write back response byte[] buf = new byte[outMS.Length]; outMS.Read(buf, 0, (int)outMS.Length); Send(handler, System.Text.Encoding.GetEncoding("ISO-8859-1").GetString(buf)); // Done receiving/sending, start next one listener.BeginAccept( new AsyncCallback(AcceptCallback), listener ); } else { // Not all data received. Get more. handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } } } private static void OnConnectionReceived(Stream inStream, Stream outStream) { if(ConnectionReceived != null) ConnectionReceived(inStream, outStream); } private static void Send(Socket handler, String data) { // Convert the string data to byte data using ASCII encoding. byte[] byteData = Encoding.ASCII.GetBytes(data); // Begin sending the data to the remote device. handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler); } private static void SendCallback(IAsyncResult ar) { try { // Retrieve the socket from the state object. Socket handler = (Socket) ar.AsyncState; // Complete sending the data to the remote device. int bytesSent = handler.EndSend(ar); handler.Shutdown(SocketShutdown.Both); handler.Close(); } catch (Exception e) { } } } }
using System; using System.Collections; using System.Text; using System.Threading; using ScanMaster.Acquire.Plugin; using ScanMaster.GUI; namespace ScanMaster { /// <summary> /// This class has its Run method called by the controller in its own thread. /// The class reads input from the command manager window and processes it. /// </summary> public class CommandProcessor { SettingsReflector sr = new SettingsReflector(); ProfileManager manager; public bool groupEditMode = false; public CommandProcessor( ProfileManager manager ) { this.manager = manager; } public void Start() { Thread commandThread = new Thread(new ThreadStart(Run)); commandThread.Name = "Command proccessor"; commandThread.Start(); commandThread.IsBackground = true; } public void Run() { manager.Window.WriteLine("ScanMaster command shell."); for (;;) { String command = manager.Window.GetNextLine(); if (manager.CurrentProfile == null) { manager.Window.WriteLine("No profile selected !"); continue; } if (Controller.GetController().appState != Controller.AppState.stopped) { if (command.StartsWith("tweak")) { manager.Window.WriteLine("Entering tweak mode ..."); TweakMode(command); continue; } manager.Window.WriteLine("Only tweak is available when acquiring."); continue; } // info on the current profile if (command == "i") { manager.Window.WriteLine(manager.CurrentProfile.ToString()); continue; } // update profile set to incorporate any newly introduced settings if (command == "refresh") { manager.UpdateProfiles(); manager.Window.WriteLine("Updated profiles."); continue; } if (command == "g") { if (groupEditMode) { groupEditMode = false; manager.Window.WriteLine("Group edit mode is off"); manager.Window.Prompt = ":> "; manager.Window.OutputColor = System.Drawing.Color.Lime; continue; } else { groupEditMode = true; manager.Window.WriteLine("Group edit mode is on. Current group " + manager.CurrentProfile.Group); manager.Window.Prompt = manager.CurrentProfile.Group + ":> "; manager.Window.OutputColor = System.Drawing.Color.White; continue; } } // anything after here (apart from a syntax error) will change the profiles // so this is an appropriate point to manager.ProfilesChanged = true; if (command.StartsWith("set") && groupEditMode) { manager.Window.WriteLine("You can't set things in group mode."); continue; } // changing plugins if (command == "set out") { String[] plugins = PluginRegistry.GetRegistry().GetOutputPlugins(); int r = ChoosePluginDialog(plugins); if (r != -1) manager.CurrentProfile.AcquisitorConfig.SetOutputPlugin(plugins[r]); continue; } if (command == "set shot") { String[] plugins = PluginRegistry.GetRegistry().GetShotGathererPlugins(); int r = ChoosePluginDialog(plugins); if (r != -1) manager.CurrentProfile.AcquisitorConfig.SetShotGathererPlugin(plugins[r]); continue; } if (command == "set pg") { String[] plugins = PluginRegistry.GetRegistry().GetPatternPlugins(); int r = ChoosePluginDialog(plugins); if (r != -1) manager.CurrentProfile.AcquisitorConfig.SetPatternPlugin(plugins[r]); continue; } if (command == "set yag") { String[] plugins = PluginRegistry.GetRegistry().GetYAGPlugins(); int r = ChoosePluginDialog(plugins); if (r != -1) manager.CurrentProfile.AcquisitorConfig.SetYAGPlugin(plugins[r]); continue; } if (command == "set analog") { String[] plugins = PluginRegistry.GetRegistry().GetAnalogPlugins(); int r = ChoosePluginDialog(plugins); if (r != -1) manager.CurrentProfile.AcquisitorConfig.SetAnalogPlugin(plugins[r]); continue; } if (command == "set switch") { String[] plugins = PluginRegistry.GetRegistry().GetSwitchPlugins(); int r = ChoosePluginDialog(plugins); if (r != -1) manager.CurrentProfile.AcquisitorConfig.SetSwitchPlugin(plugins[r]); continue; } // changing group if (command.StartsWith("set group")) { String[] bits = command.Split(new char[] {' '}); if (bits.Length != 3) { manager.Window.WriteLine("Syntax error."); continue; } manager.CurrentProfile.Group = bits[2]; manager.Window.WriteLine("Group changed"); continue; } // listing plugin settings if (command == "out") { String settings = sr.ListSettings(manager.CurrentProfile.AcquisitorConfig.outputPlugin); manager.Window.WriteLine(settings); continue; } if (command == "analog") { String settings = sr.ListSettings(manager.CurrentProfile.AcquisitorConfig.analogPlugin); manager.Window.WriteLine(settings); continue; } if (command == "switch") { String settings = sr.ListSettings(manager.CurrentProfile.AcquisitorConfig.switchPlugin); manager.Window.WriteLine(settings); continue; } if (command == "pg") { String settings = sr.ListSettings(manager.CurrentProfile.AcquisitorConfig.pgPlugin); manager.Window.WriteLine(settings); continue; } if (command == "yag") { String settings = sr.ListSettings(manager.CurrentProfile.AcquisitorConfig.yagPlugin); manager.Window.WriteLine(settings); continue; } if (command == "shot") { String settings = sr.ListSettings(manager.CurrentProfile.AcquisitorConfig.shotGathererPlugin); manager.Window.WriteLine(settings); continue; } if (command == "gui") { manager.Window.WriteLine("tofUpdate " + manager.CurrentProfile.GUIConfig.updateTOFsEvery); manager.Window.WriteLine("spectraUpdate " + manager.CurrentProfile.GUIConfig.updateSpectraEvery); manager.Window.WriteLine("switch " + manager.CurrentProfile.GUIConfig.displaySwitch); manager.Window.WriteLine("average " + manager.CurrentProfile.GUIConfig.average); continue; } // changing plugin settings if (command.StartsWith("out:") | command.StartsWith("analog:") | command.StartsWith("pg:") | command.StartsWith("yag:") | command.StartsWith("switch:") | command.StartsWith("shot:") | command.StartsWith("gui:")) { String[] bits = command.Split(new char[] {':', ' '}); if (bits.Length != 3) { manager.Window.WriteLine("Syntax error."); continue; } // special case for GUI settings (it's not a plugin) if (bits[0] == "gui") { if (groupEditMode) { manager.Window.WriteLine("Sorry, but, hilariously, there is no " + "group edit mode for GUI settings."); continue; } GUIConfiguration guiConfig = manager.CurrentProfile.GUIConfig; try { if (bits[1] == "tofUpdate") { guiConfig.updateTOFsEvery = Convert.ToInt32(bits[2]); manager.Window.WriteLine("GUI:tofUpdate updated."); continue; } if (bits[1] == "spectraUpdate") { guiConfig.updateSpectraEvery = Convert.ToInt32(bits[2]); manager.Window.WriteLine("GUI:spectraUpdate updated."); continue; } if (bits[1] == "switch") { guiConfig.displaySwitch = Convert.ToBoolean(bits[2]); manager.Window.WriteLine("GUI:switch updated."); continue; } if (bits[1] == "average") { guiConfig.average = Convert.ToBoolean(bits[2]); manager.Window.WriteLine("GUI:average updated."); continue; } manager.Window.WriteLine("Unrecognised parameter"); } catch (Exception) { manager.Window.WriteLine("Error."); } } else { if (groupEditMode) { // first, check to make sure that every profile in the group has such // a setting. ArrayList groupProfiles = manager.ProfilesInGroup(manager.CurrentProfile.Group); bool fieldFlag = true; foreach (Profile p in groupProfiles) { AcquisitorPlugin pl = PluginForString(p, bits[0]); if (!sr.HasField(pl,bits[1])) fieldFlag = false; } if (!fieldFlag) { manager.Window.WriteLine("You can only change the value of a setting in group " + "edit mode if all profiles in the group have that setting."); continue; } // if so, then set them all foreach (Profile p in groupProfiles) { AcquisitorPlugin plugin = PluginForString(p, bits[0]); if (sr.SetField(plugin, bits[1], bits[2])) manager.Window.WriteLine(p.Name + ":" + bits[0] + ":" + bits[1] + " modified."); else manager.Window.WriteLine("Error setting field"); } } else { AcquisitorPlugin plugin = PluginForString(manager.CurrentProfile, bits[0]); if (sr.SetField(plugin, bits[1], bits[2])) manager.Window.WriteLine(bits[0] + ":" + bits[1] + " modified."); else manager.Window.WriteLine("Error setting field"); } } continue; } // tweaking a setting // if we reach here there must be a syntax error manager.Window.WriteLine("Syntax error"); } } public String[] GetCommandSuggestions(String commandStub) { String[] bits = commandStub.Split(new char[] {':'}); // return null if can't help if (bits.Length !=2) return null; ArrayList suggestions = new ArrayList(); AcquisitorPlugin plugin = PluginForString( manager.CurrentProfile, bits[0]); if (plugin == null) return null; String[] fieldNames = sr.ListSettingNames(plugin); if (fieldNames == null) return null; for (int i = 0 ; i < fieldNames.Length ; i++) if (fieldNames[i].StartsWith(bits[1])) suggestions.Add(bits[0] + ":" + fieldNames[i]); String[] r = new String[suggestions.Count]; suggestions.CopyTo(r,0); return r; } public AcquisitorPlugin PluginForString(Profile p, String pluginType) { AcquisitorPlugin plugin = null; switch(pluginType) { case "out": plugin = p.AcquisitorConfig.outputPlugin; break; case "pg": plugin = p.AcquisitorConfig.pgPlugin; break; case "switch": plugin = p.AcquisitorConfig.switchPlugin; break; case "shot": plugin = p.AcquisitorConfig.shotGathererPlugin; break; case "analog": plugin = p.AcquisitorConfig.analogPlugin; break; case "yag": plugin = p.AcquisitorConfig.yagPlugin; break; } return plugin; } private int ChoosePluginDialog(String[] plugins) { StringBuilder sb = new StringBuilder(); for (int i = 0 ; i < plugins.Length ; i++) sb.Append(" " + i + ": " + plugins[i] + Environment.NewLine); sb.Append("Choose a plugin:"); manager.Window.WriteLine(sb.ToString()); String pluginNumber = manager.Window.GetNextLine(); try { int index = Convert.ToInt32(pluginNumber); if (index >= plugins.Length | index < 0) { manager.Window.WriteLine("Invalid input"); return -1; } manager.Window.WriteLine(plugins[index] + " selected."); return index; } catch (System.FormatException) { manager.Window.WriteLine("Invalid input."); } return -1; } private void TweakMode(String command) { String[] bits = command.Split(new char[] {' '}); if (bits.Length != 3) { manager.Window.WriteLine("Syntax error."); return; } // check if this is a valid parameter to tweak PatternPlugin plugin = manager.CurrentProfile.AcquisitorConfig.pgPlugin; if (!sr.HasField(plugin, bits[1])) { manager.Window.WriteLine("The current profile's pg plugin has no field named " + bits[1]); return; } // is the increment valid int increment = 0; try { increment = Convert.ToInt32(bits[2]); } catch (Exception) { manager.Window.WriteLine("Invalid increment"); return; } manager.Window.WriteLine("Tweaking - i for increment, d for decrement, e for exit."); for (;;) { String s = manager.Window.GetNextLine(); // check if the user wants to exit. Also check if acquisition has stopped. // This is not ideal but should stop anything terrible happening. if (s == "e" | Controller.GetController().appState != Controller.AppState.running) { manager.Window.WriteLine("Exiting tweak mode"); return; } if (s == "i") { manager.Window.WriteLine("Incrementing " + bits[1] + " by " + increment + "."); int oldValue = (int)sr.GetField(plugin, bits[1]); int newValue = oldValue + increment; manager.Window.WriteLine("New value: " + newValue); sr.SetField(plugin, bits[1], newValue.ToString()); manager.FireTweak(new TweakEventArgs(bits[1], newValue)); continue; } if (s == "d") { manager.Window.WriteLine("Decrementing " + bits[1] + " by " + increment + "."); int oldValue = (int)sr.GetField(plugin, bits[1]); int newValue = oldValue - increment; manager.Window.WriteLine("New value: " + newValue); sr.SetField(plugin, bits[1], newValue.ToString()); manager.FireTweak(new TweakEventArgs(bits[1], newValue)); continue; } manager.Window.WriteLine("Syntax error"); } } } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Grpc.Core; using Grpc.Core.Internal; using Grpc.Core.Utils; using NUnit.Framework; namespace Grpc.Core.Tests { public class ClientServerTest { const string Host = "127.0.0.1"; MockServiceHelper helper; Server server; Channel channel; [SetUp] public void Init() { helper = new MockServiceHelper(Host); server = helper.GetServer(); server.Start(); channel = helper.GetChannel(); } [TearDown] public void Cleanup() { channel.Dispose(); server.ShutdownAsync().Wait(); } [TestFixtureTearDown] public void CleanupClass() { GrpcEnvironment.Shutdown(); } [Test] public async Task UnaryCall() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { return request; }); Assert.AreEqual("ABC", Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "ABC")); Assert.AreEqual("ABC", await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "ABC")); } [Test] public void UnaryCall_ServerHandlerThrows() { helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) => { throw new Exception("This was thrown on purpose by a test"); }); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unknown, ex.Status.StatusCode); var ex2 = Assert.Throws<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unknown, ex2.Status.StatusCode); } [Test] public void UnaryCall_ServerHandlerThrowsRpcException() { helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) => { throw new RpcException(new Status(StatusCode.Unauthenticated, "")); }); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode); var ex2 = Assert.Throws<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode); } [Test] public void UnaryCall_ServerHandlerSetsStatus() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { context.Status = new Status(StatusCode.Unauthenticated, ""); return ""; }); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode); var ex2 = Assert.Throws<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode); } [Test] public async Task ClientStreamingCall() { helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) => { string result = ""; await requestStream.ForEachAsync(async (request) => { result += request; }); await Task.Delay(100); return result; }); var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall()); await call.RequestStream.WriteAllAsync(new string[] { "A", "B", "C" }); Assert.AreEqual("ABC", await call.ResponseAsync); } [Test] public async Task ClientStreamingCall_CancelAfterBegin() { var barrier = new TaskCompletionSource<object>(); helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) => { barrier.SetResult(null); await requestStream.ToListAsync(); return ""; }); var cts = new CancellationTokenSource(); var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall(new CallOptions(cancellationToken: cts.Token))); await barrier.Task; // make sure the handler has started. cts.Cancel(); var ex = Assert.Throws<RpcException>(async () => await call.ResponseAsync); Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode); } [Test] public async Task AsyncUnaryCall_EchoMetadata() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { foreach (Metadata.Entry metadataEntry in context.RequestHeaders) { if (metadataEntry.Key != "user-agent") { context.ResponseTrailers.Add(metadataEntry); } } return ""; }); var headers = new Metadata { { "ascii-header", "abcdefg" }, { "binary-header-bin", new byte[] { 1, 2, 3, 0, 0xff } } }; var call = Calls.AsyncUnaryCall(helper.CreateUnaryCall(new CallOptions(headers: headers)), "ABC"); await call; Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode); var trailers = call.GetTrailers(); Assert.AreEqual(2, trailers.Count); Assert.AreEqual(headers[0].Key, trailers[0].Key); Assert.AreEqual(headers[0].Value, trailers[0].Value); Assert.AreEqual(headers[1].Key, trailers[1].Key); CollectionAssert.AreEqual(headers[1].ValueBytes, trailers[1].ValueBytes); } [Test] public void UnaryCall_DisposedChannel() { channel.Dispose(); Assert.Throws(typeof(ObjectDisposedException), () => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "ABC")); } [Test] public void UnaryCallPerformance() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { return request; }); var callDetails = helper.CreateUnaryCall(); BenchmarkUtil.RunBenchmark(100, 100, () => { Calls.BlockingUnaryCall(callDetails, "ABC"); }); } [Test] public void UnknownMethodHandler() { var nonexistentMethod = new Method<string, string>( MethodType.Unary, MockServiceHelper.ServiceName, "NonExistentMethod", Marshallers.StringMarshaller, Marshallers.StringMarshaller); var callDetails = new CallInvocationDetails<string, string>(channel, nonexistentMethod, new CallOptions()); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(callDetails, "abc")); Assert.AreEqual(StatusCode.Unimplemented, ex.Status.StatusCode); } [Test] public void UserAgentStringPresent() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { return context.RequestHeaders.Where(entry => entry.Key == "user-agent").Single().Value; }); string userAgent = Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"); Assert.IsTrue(userAgent.StartsWith("grpc-csharp/")); } [Test] public void PeerInfoPresent() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { return context.Peer; }); string peer = Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"); Assert.IsTrue(peer.Contains(Host)); } [Test] public async Task Channel_WaitForStateChangedAsync() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { return request; }); Assert.Throws(typeof(TaskCanceledException), async () => await channel.WaitForStateChangedAsync(channel.State, DateTime.UtcNow.AddMilliseconds(10))); var stateChangedTask = channel.WaitForStateChangedAsync(channel.State); await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc"); await stateChangedTask; Assert.AreEqual(ChannelState.Ready, channel.State); } [Test] public async Task Channel_ConnectAsync() { await channel.ConnectAsync(); Assert.AreEqual(ChannelState.Ready, channel.State); await channel.ConnectAsync(DateTime.UtcNow.AddMilliseconds(1000)); Assert.AreEqual(ChannelState.Ready, channel.State); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: StreamReader ** ** <OWNER>gpaperin</OWNER> ** ** ** Purpose: For reading text from streams in a particular ** encoding. ** ** ===========================================================*/ using System; using System.Text; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Security.Permissions; using System.Threading.Tasks; namespace System.IO { // This class implements a TextReader for reading characters to a Stream. // This is designed for character input in a particular Encoding, // whereas the Stream class is designed for byte input and output. // public class StreamReader : TextReader { // StreamReader.Null is threadsafe. public new static readonly StreamReader Null = new NullStreamReader(); // Using a 1K byte buffer and a 4K FileStream buffer works out pretty well // perf-wise. On even a 40 MB text file, any perf loss by using a 4K // buffer is negated by the win of allocating a smaller byte[], which // saves construction time. This does break adaptive buffering, // but this is slightly faster. internal static int DefaultBufferSize { get { return 1024; } } private const int DefaultFileStreamBufferSize = 4096; private const int MinBufferSize = 128; private Stream stream; private Encoding encoding; private byte[] byteBuffer; private char[] charBuffer; private int charPos; private int charLen; // Record the number of valid bytes in the byteBuffer, for a few checks. private int byteLen; // This is used only for preamble detection private int bytePos; // This is the maximum number of chars we can get from one call to // ReadBuffer. Used so ReadBuffer can tell when to copy data into // a user's char[] directly, instead of our internal char[]. private int _maxCharsPerBuffer; // We will support looking for byte order marks in the stream and trying // to decide what the encoding might be from the byte order marks, IF they // exist. But that's all we'll do. private bool _detectEncoding; // Whether the stream is most likely not going to give us back as much // data as we want the next time we call it. We must do the computation // before we do any byte order mark handling and save the result. Note // that we need this to allow users to handle streams used for an // interactive protocol, where they block waiting for the remote end // to send a response, like logging in on a Unix machine. private bool _isBlocked; // The intent of this field is to leave open the underlying stream when // disposing of this StreamReader. A name like _leaveOpen is better, // but this type is serializable, and this field's name was _closable. private bool _closable; // Whether to close the underlying stream. // StreamReader by default will ignore illegal UTF8 characters. We don't want to // throw here because we want to be able to read ill-formed data without choking. // The high level goal is to be tolerant of encoding errors when we read and very strict // when we write. Hence, default StreamWriter encoding will throw on error. internal StreamReader() { } public StreamReader(Stream stream) : this(stream, true) { } public StreamReader(Stream stream, bool detectEncodingFromByteOrderMarks) : this(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks, DefaultBufferSize, false) { } public StreamReader(Stream stream, Encoding encoding) : this(stream, encoding, true, DefaultBufferSize, false) { } public StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks) : this(stream, encoding, detectEncodingFromByteOrderMarks, DefaultBufferSize, false) { } // Creates a new StreamReader for the given stream. The // character encoding is set by encoding and the buffer size, // in number of 16-bit characters, is set by bufferSize. // // Note that detectEncodingFromByteOrderMarks is a very // loose attempt at detecting the encoding by looking at the first // 3 bytes of the stream. It will recognize UTF-8, little endian // unicode, and big endian unicode text, but that's it. If neither // of those three match, it will use the Encoding you provided. // public StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) : this(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize, false) { } public StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen) { if (stream == null || encoding == null) throw new ArgumentNullException((stream == null ? "stream" : "encoding")); if (!stream.CanRead) throw new ArgumentException(); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize"); Contract.EndContractBlock(); Init(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize, leaveOpen); } public StreamReader(String path) : this(path, true) { } public StreamReader(String path, bool detectEncodingFromByteOrderMarks) : this(path, Encoding.UTF8, detectEncodingFromByteOrderMarks, DefaultBufferSize) { } public StreamReader(String path, Encoding encoding) : this(path, encoding, true, DefaultBufferSize) { } public StreamReader(String path, Encoding encoding, bool detectEncodingFromByteOrderMarks) : this(path, encoding, detectEncodingFromByteOrderMarks, DefaultBufferSize) { } public StreamReader(String path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) : this(path, encoding, detectEncodingFromByteOrderMarks, bufferSize, true) { } internal StreamReader(String path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool checkHost) { // Don't open a Stream before checking for invalid arguments, // or we'll create a FileStream on disk and we won't close it until // the finalizer runs, causing problems for applications. if (path == null || encoding == null) throw new ArgumentNullException((path == null ? "path" : "encoding")); if (path.Length == 0) throw new ArgumentException(); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize"); Contract.EndContractBlock(); Stream stream = new FileStream(path, FileMode.Open); Init(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize, false); } private void Init(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen) { this.stream = stream; this.encoding = encoding; if (bufferSize < MinBufferSize) bufferSize = MinBufferSize; byteBuffer = new byte[bufferSize]; _maxCharsPerBuffer = encoding.GetMaxCharCount(bufferSize); charBuffer = new char[_maxCharsPerBuffer]; byteLen = 0; bytePos = 0; _detectEncoding = detectEncodingFromByteOrderMarks; _isBlocked = false; _closable = !leaveOpen; } // Init used by NullStreamReader, to delay load encoding internal void Init(Stream stream) { this.stream = stream; _closable = true; } public override void Close() { Dispose(true); } protected override void Dispose(bool disposing) { // Dispose of our resources if this StreamReader is closable. // Note that Console.In should be left open. try { // Note that Stream.Close() can potentially throw here. So we need to // ensure cleaning up internal resources, inside the finally block. if (!LeaveOpen && disposing && (stream != null)) stream.Close(); } finally { if (!LeaveOpen && (stream != null)) { stream = null; encoding = null; byteBuffer = null; charBuffer = null; charPos = 0; charLen = 0; base.Dispose(disposing); } } } public virtual Encoding CurrentEncoding { get { return encoding; } } public virtual Stream BaseStream { get { return stream; } } internal bool LeaveOpen { get { return !_closable; } } // DiscardBufferedData tells StreamReader to throw away its internal // buffer contents. This is useful if the user needs to seek on the // underlying stream to a known location then wants the StreamReader // to start reading from this new point. This method should be called // very sparingly, if ever, since it can lead to very poor performance. // However, it may be the only way of handling some scenarios where // users need to re-read the contents of a StreamReader a second time. public void DiscardBufferedData() { byteLen = 0; charLen = 0; charPos = 0; _isBlocked = false; } public bool EndOfStream { get { if (stream == null) __Error.ReaderClosed(); if (charPos < charLen) return false; // This may block on pipes! int numRead = ReadBuffer(); return numRead == 0; } } [Pure] public override int Peek() { if (stream == null) __Error.ReaderClosed(); if (charPos == charLen) { if (_isBlocked || ReadBuffer() == 0) return -1; } return charBuffer[charPos]; } public override int Read() { if (stream == null) __Error.ReaderClosed(); if (charPos == charLen) { if (ReadBuffer() == 0) return -1; } int result = charBuffer[charPos]; charPos++; return result; } public override int Read([In, Out] char[] buffer, int index, int count) { if (buffer == null) throw new ArgumentNullException("buffer"); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count")); if (buffer.Length - index < count) throw new ArgumentException(); Contract.EndContractBlock(); if (stream == null) __Error.ReaderClosed(); int charsRead = 0; // As a perf optimization, if we had exactly one buffer's worth of // data read in, let's try writing directly to the user's buffer. bool readToUserBuffer = false; while (count > 0) { int n = charLen - charPos; if (n == 0) n = ReadBuffer(buffer, index + charsRead, count, out readToUserBuffer); if (n == 0) break; // We're at EOF if (n > count) n = count; if (!readToUserBuffer) { Array.Copy(charBuffer, charPos, buffer, (index + charsRead), n); charPos += n; } charsRead += n; count -= n; // This function shouldn't block for an indefinite amount of time, // or reading from a network stream won't work right. If we got // fewer bytes than we requested, then we want to break right here. if (_isBlocked) break; } return charsRead; } public override async Task<String> ReadToEndAsync() { if (this.stream is FileStream) { await this.stream.As<FileStream>().EnsureBufferAsync(); } return await base.ReadToEndAsync(); } public override String ReadToEnd() { if (stream == null) __Error.ReaderClosed(); // Call ReadBuffer, then pull data out of charBuffer. StringBuilder sb = new StringBuilder(charLen - charPos); do { sb.Append(new string(charBuffer, charPos, charLen - charPos)); charPos = charLen; // Note we consumed these characters ReadBuffer(); } while (charLen > 0); return sb.ToString(); } public override int ReadBlock([In, Out] char[] buffer, int index, int count) { if (buffer == null) throw new ArgumentNullException("buffer"); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count")); if (buffer.Length - index < count) throw new ArgumentException(); Contract.EndContractBlock(); if (stream == null) __Error.ReaderClosed(); return base.ReadBlock(buffer, index, count); } // Trims n bytes from the front of the buffer. private void CompressBuffer(int n) { Contract.Assert(byteLen >= n, "CompressBuffer was called with a number of bytes greater than the current buffer length. Are two threads using this StreamReader at the same time?"); Array.Copy(byteBuffer, n, byteBuffer, 0, byteLen - n); byteLen -= n; } private void DetectEncoding() { if (byteLen < 2) return; _detectEncoding = false; bool changedEncoding = false; if (byteBuffer[0] == 0xFE && byteBuffer[1] == 0xFF) { // Big Endian Unicode encoding = new UnicodeEncoding(true, true); CompressBuffer(2); changedEncoding = true; } else if (byteBuffer[0] == 0xFF && byteBuffer[1] == 0xFE) { // Little Endian Unicode, or possibly little endian UTF32 if (byteLen < 4 || byteBuffer[2] != 0 || byteBuffer[3] != 0) { encoding = new UnicodeEncoding(false, true); CompressBuffer(2); changedEncoding = true; } else { encoding = new UTF32Encoding(false, true); CompressBuffer(4); changedEncoding = true; } } else if (byteLen >= 3 && byteBuffer[0] == 0xEF && byteBuffer[1] == 0xBB && byteBuffer[2] == 0xBF) { // UTF-8 encoding = Encoding.UTF8; CompressBuffer(3); changedEncoding = true; } else if (byteLen >= 4 && byteBuffer[0] == 0 && byteBuffer[1] == 0 && byteBuffer[2] == 0xFE && byteBuffer[3] == 0xFF) { // Big Endian UTF32 encoding = new UTF32Encoding(true, true); CompressBuffer(4); changedEncoding = true; } else if (byteLen == 2) _detectEncoding = true; // Note: in the future, if we change this algorithm significantly, // we can support checking for the preamble of the given encoding. if (changedEncoding) { _maxCharsPerBuffer = encoding.GetMaxCharCount(byteBuffer.Length); charBuffer = new char[_maxCharsPerBuffer]; } } // Trims the preamble bytes from the byteBuffer. This routine can be called multiple times // and we will buffer the bytes read until the preamble is matched or we determine that // there is no match. If there is no match, every byte read previously will be available // for further consumption. If there is a match, we will compress the buffer for the // leading preamble bytes private bool IsPreamble() { return false; } internal virtual int ReadBuffer() { charLen = 0; charPos = 0; byteLen = 0; do { Contract.Assert(bytePos == 0, "bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?"); byteLen = stream.Read(byteBuffer, 0, byteBuffer.Length); Contract.Assert(byteLen >= 0, "Stream.Read returned a negative number! This is a bug in your stream class."); if (byteLen == 0) // We're at EOF return charLen; // _isBlocked == whether we read fewer bytes than we asked for. // Note we must check it here because CompressBuffer or // DetectEncoding will change byteLen. _isBlocked = (byteLen < byteBuffer.Length); // Check for preamble before detect encoding. This is not to override the // user suppplied Encoding for the one we implicitly detect. The user could // customize the encoding which we will loose, such as ThrowOnError on UTF8 if (IsPreamble()) continue; // If we're supposed to detect the encoding and haven't done so yet, // do it. Note this may need to be called more than once. if (_detectEncoding && byteLen >= 2) DetectEncoding(); charLen += encoding.GetChars(byteBuffer, 0, byteLen, charBuffer, charLen); } while (charLen == 0); //Console.WriteLine("ReadBuffer called. chars: "+charLen); return charLen; } // This version has a perf optimization to decode data DIRECTLY into the // user's buffer, bypassing StreamReader's own buffer. // This gives a > 20% perf improvement for our encodings across the board, // but only when asking for at least the number of characters that one // buffer's worth of bytes could produce. // This optimization, if run, will break SwitchEncoding, so we must not do // this on the first call to ReadBuffer. private int ReadBuffer(char[] userBuffer, int userOffset, int desiredChars, out bool readToUserBuffer) { charLen = 0; charPos = 0; byteLen = 0; int charsRead = 0; // As a perf optimization, we can decode characters DIRECTLY into a // user's char[]. We absolutely must not write more characters // into the user's buffer than they asked for. Calculating // encoding.GetMaxCharCount(byteLen) each time is potentially very // expensive - instead, cache the number of chars a full buffer's // worth of data may produce. Yes, this makes the perf optimization // less aggressive, in that all reads that asked for fewer than AND // returned fewer than _maxCharsPerBuffer chars won't get the user // buffer optimization. This affects reads where the end of the // Stream comes in the middle somewhere, and when you ask for // fewer chars than your buffer could produce. readToUserBuffer = desiredChars >= _maxCharsPerBuffer; do { Contract.Assert(charsRead == 0); Contract.Assert(bytePos == 0, "bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?"); byteLen = stream.Read(byteBuffer, 0, byteBuffer.Length); Contract.Assert(byteLen >= 0, "Stream.Read returned a negative number! This is a bug in your stream class."); if (byteLen == 0) // EOF break; // _isBlocked == whether we read fewer bytes than we asked for. // Note we must check it here because CompressBuffer or // DetectEncoding will change byteLen. _isBlocked = (byteLen < byteBuffer.Length); // Check for preamble before detect encoding. This is not to override the // user suppplied Encoding for the one we implicitly detect. The user could // customize the encoding which we will loose, such as ThrowOnError on UTF8 // Note: we don't need to recompute readToUserBuffer optimization as IsPreamble // doesn't change the encoding or affect _maxCharsPerBuffer if (IsPreamble()) continue; // On the first call to ReadBuffer, if we're supposed to detect the encoding, do it. if (_detectEncoding && byteLen >= 2) { DetectEncoding(); // DetectEncoding changes some buffer state. Recompute this. readToUserBuffer = desiredChars >= _maxCharsPerBuffer; } charPos = 0; if (readToUserBuffer) { charsRead += encoding.GetChars(byteBuffer, 0, byteLen, userBuffer, userOffset + charsRead); charLen = 0; // StreamReader's buffer is empty. } else { charsRead = encoding.GetChars(byteBuffer, 0, byteLen, charBuffer, charsRead); charLen += charsRead; // Number of chars in StreamReader's buffer. } } while (charsRead == 0); _isBlocked &= charsRead < desiredChars; //Console.WriteLine("ReadBuffer: charsRead: "+charsRead+" readToUserBuffer: "+readToUserBuffer); return charsRead; } // Reads a line. A line is defined as a sequence of characters followed by // a carriage return ('\r'), a line feed ('\n'), or a carriage return // immediately followed by a line feed. The resulting string does not // contain the terminating carriage return and/or line feed. The returned // value is null if the end of the input stream has been reached. // public override String ReadLine() { if (stream == null) __Error.ReaderClosed(); if (charPos == charLen) { if (ReadBuffer() == 0) return null; } StringBuilder sb = null; do { int i = charPos; do { char ch = charBuffer[i]; // Note the following common line feed chars: // \n - UNIX \r\n - DOS \r - Mac if (ch == '\r' || ch == '\n') { String s; if (sb != null) { sb.Append(new String(charBuffer, charPos, i - charPos)); s = sb.ToString(); } else { s = new String(charBuffer, charPos, i - charPos); } charPos = i + 1; if (ch == '\r' && (charPos < charLen || ReadBuffer() > 0)) { if (charBuffer[charPos] == '\n') charPos++; } return s; } i++; } while (i < charLen); i = charLen - charPos; if (sb == null) sb = new StringBuilder(i + 80); sb.Append(new String(charBuffer, charPos, i)); } while (ReadBuffer() > 0); return sb.ToString(); } // No data, class doesn't need to be serializable. // Note this class is threadsafe. private class NullStreamReader : StreamReader { // Instantiating Encoding causes unnecessary perf hit. internal NullStreamReader() { Init(Stream.Null); } public override Stream BaseStream { get { return Stream.Null; } } public override Encoding CurrentEncoding { get { return Encoding.Unicode; } } protected override void Dispose(bool disposing) { // Do nothing - this is essentially unclosable. } public override int Peek() { return -1; } public override int Read() { return -1; } public override int Read(char[] buffer, int index, int count) { return 0; } public override String ReadLine() { return null; } public override String ReadToEnd() { return String.Empty; } internal override int ReadBuffer() { return 0; } } } }
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using ZXing.Common; using ZXing.Common.ReedSolomon; using ZXing.Core; using ZXing.Writer; namespace ZXing.QRCode.Internal { /// <summary> /// </summary> /// <author>satorux@google.com (Satoru Takabayashi) - creator</author> /// <author>dswitkin@google.com (Daniel Switkin) - ported from C++</author> public static class Encoder { // The original table is defined in the table 5 of JISX0510:2004 (p.19). private static readonly int[] ALPHANUMERIC_TABLE = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x00-0x0f -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x10-0x1f 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, // 0x20-0x2f 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, // 0x30-0x3f -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 0x40-0x4f 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, // 0x50-0x5f }; public static String DEFAULT_BYTE_MODE_ENCODING = "ISO-8859-1"; // The mask penalty calculation is complicated. See Table 21 of JISX0510:2004 (p.45) for details. // Basically it applies four rules and summate all penalties. private static int calculateMaskPenalty(ByteMatrix matrix) { return MaskUtil.applyMaskPenaltyRule1(matrix) + MaskUtil.applyMaskPenaltyRule2(matrix) + MaskUtil.applyMaskPenaltyRule3(matrix) + MaskUtil.applyMaskPenaltyRule4(matrix); } /// <summary> /// Encode "bytes" with the error correction level "ecLevel". The encoding mode will be chosen /// internally by chooseMode(). On success, store the result in "qrCode". /// We recommend you to use QRCode.EC_LEVEL_L (the lowest level) for /// "getECLevel" since our primary use is to show QR code on desktop screens. We don't need very /// strong error correction for this purpose. /// Note that there is no way to encode bytes in MODE_KANJI. We might want to add EncodeWithMode() /// with which clients can specify the encoding mode. For now, we don't need the functionality. /// </summary> /// <param name="content">The content.</param> /// <param name="ecLevel">The ec level.</param> public static QRCode encode(String content, ErrorCorrectionLevel ecLevel) { return encode(content, ecLevel, null); } /// <summary> /// Encodes the specified content. /// </summary> /// <param name="content">The content.</param> /// <param name="ecLevel">The ec level.</param> /// <param name="hints">The hints.</param> /// <returns></returns> public static QRCode encode(String content, ErrorCorrectionLevel ecLevel, IDictionary<EncodeHintType, object> hints) { // Determine what character encoding has been specified by the caller, if any #if !SILVERLIGHT || WINDOWS_PHONE String encoding = hints == null || !hints.ContainsKey(EncodeHintType.CHARACTER_SET) ? null : (String)hints[EncodeHintType.CHARACTER_SET]; if (encoding == null) { encoding = DEFAULT_BYTE_MODE_ENCODING; } bool generateECI = !DEFAULT_BYTE_MODE_ENCODING.Equals(encoding); #else // Silverlight supports only UTF-8 and UTF-16 out-of-the-box const string encoding = "UTF-8"; // caller of the method can only control if the ECI segment should be written // character set is fixed to UTF-8; but some scanners doesn't like the ECI segment bool generateECI = (hints != null && hints.ContainsKey(EncodeHintType.CHARACTER_SET)); #endif // Pick an encoding mode appropriate for the content. Note that this will not attempt to use // multiple modes / segments even if that were more efficient. Twould be nice. Mode mode = chooseMode(content, encoding); // This will store the header information, like mode and // length, as well as "header" segments like an ECI segment. BitArray headerBits = new BitArray(); // Append ECI segment if applicable if (mode == Mode.BYTE && generateECI) { CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding); if (eci != null) { var eciIsExplicitDisabled = (hints != null && hints.ContainsKey(EncodeHintType.DISABLE_ECI) ? (bool)hints[EncodeHintType.DISABLE_ECI] : false); if (!eciIsExplicitDisabled) { appendECI(eci, headerBits); } } } // (With ECI in place,) Write the mode marker appendModeInfo(mode, headerBits); // Collect data within the main segment, separately, to count its size if needed. Don't add it to // main payload yet. BitArray dataBits = new BitArray(); appendBytes(content, mode, dataBits, encoding); // Hard part: need to know version to know how many bits length takes. But need to know how many // bits it takes to know version. First we take a guess at version by assuming version will be // the minimum, 1: int provisionalBitsNeeded = headerBits.Size + mode.getCharacterCountBits(VersionInfo.getVersionForNumber(1)) + dataBits.Size; VersionInfo provisionalVersion = chooseVersion(provisionalBitsNeeded, ecLevel); // Use that guess to calculate the right version. I am still not sure this works in 100% of cases. int bitsNeeded = headerBits.Size + mode.getCharacterCountBits(provisionalVersion) + dataBits.Size; VersionInfo version = chooseVersion(bitsNeeded, ecLevel); BitArray headerAndDataBits = new BitArray(); headerAndDataBits.appendBitArray(headerBits); // Find "length" of main segment and write it int numLetters = mode == Mode.BYTE ? dataBits.SizeInBytes : content.Length; appendLengthInfo(numLetters, version, mode, headerAndDataBits); // Put data together into the overall payload headerAndDataBits.appendBitArray(dataBits); VersionInfo.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); int numDataBytes = version.TotalCodewords - ecBlocks.TotalECCodewords; // Terminate the bits properly. terminateBits(numDataBytes, headerAndDataBits); // Interleave data bits with error correction code. BitArray finalBits = interleaveWithECBytes(headerAndDataBits, version.TotalCodewords, numDataBytes, ecBlocks.NumBlocks); QRCode qrCode = new QRCode { ECLevel = ecLevel, Mode = mode, Version = version }; // Choose the mask pattern and set to "qrCode". int dimension = version.DimensionForVersion; ByteMatrix matrix = new ByteMatrix(dimension, dimension); int maskPattern = chooseMaskPattern(finalBits, ecLevel, version, matrix); qrCode.MaskPattern = maskPattern; // Build the matrix and set it to "qrCode". MatrixUtil.buildMatrix(finalBits, ecLevel, version, maskPattern, matrix); qrCode.Matrix = matrix; return qrCode; } /// <summary> /// Gets the alphanumeric code. /// </summary> /// <param name="code">The code.</param> /// <returns>the code point of the table used in alphanumeric mode or /// -1 if there is no corresponding code in the table.</returns> public static int getAlphanumericCode(int code) { if (code < ALPHANUMERIC_TABLE.Length) { return ALPHANUMERIC_TABLE[code]; } return -1; } /// <summary> /// Chooses the mode. /// </summary> /// <param name="content">The content.</param> /// <returns></returns> public static Mode chooseMode(String content) { return chooseMode(content, null); } /// <summary> /// Choose the best mode by examining the content. Note that 'encoding' is used as a hint; /// if it is Shift_JIS, and the input is only double-byte Kanji, then we return {@link Mode#KANJI}. /// </summary> /// <param name="content">The content.</param> /// <param name="encoding">The encoding.</param> /// <returns></returns> private static Mode chooseMode(String content, String encoding) { if ("Shift_JIS".Equals(encoding)) { // Choose Kanji mode if all input are double-byte characters return isOnlyDoubleByteKanji(content) ? Mode.KANJI : Mode.BYTE; } bool hasNumeric = false; bool hasAlphanumeric = false; for (int i = 0; i < content.Length; ++i) { char c = content[i]; if (c >= '0' && c <= '9') { hasNumeric = true; } else if (getAlphanumericCode(c) != -1) { hasAlphanumeric = true; } else { return Mode.BYTE; } } if (hasAlphanumeric) { return Mode.ALPHANUMERIC; } if (hasNumeric) { return Mode.NUMERIC; } return Mode.BYTE; } private static bool isOnlyDoubleByteKanji(String content) { byte[] bytes; try { bytes = Encoding.GetEncoding("Shift_JIS").GetBytes(content); } catch (Exception ) { return false; } int length = bytes.Length; if (length % 2 != 0) { return false; } for (int i = 0; i < length; i += 2) { int byte1 = bytes[i] & 0xFF; if ((byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB)) { return false; } } return true; } private static int chooseMaskPattern(BitArray bits, ErrorCorrectionLevel ecLevel, VersionInfo version, ByteMatrix matrix) { int minPenalty = Int32.MaxValue; // Lower penalty is better. int bestMaskPattern = -1; // We try all mask patterns to choose the best one. for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) { MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix); int penalty = calculateMaskPenalty(matrix); if (penalty < minPenalty) { minPenalty = penalty; bestMaskPattern = maskPattern; } } return bestMaskPattern; } private static VersionInfo chooseVersion(int numInputBits, ErrorCorrectionLevel ecLevel) { // In the following comments, we use numbers of Version 7-H. for (int versionNum = 1; versionNum <= 40; versionNum++) { VersionInfo version = VersionInfo.getVersionForNumber(versionNum); // numBytes = 196 int numBytes = version.TotalCodewords; // getNumECBytes = 130 VersionInfo.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); int numEcBytes = ecBlocks.TotalECCodewords; // getNumDataBytes = 196 - 130 = 66 int numDataBytes = numBytes - numEcBytes; int totalInputBytes = (numInputBits + 7) / 8; if (numDataBytes >= totalInputBytes) { return version; } } throw new ZXingWriterException("Data too big"); } /// <summary> /// Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24). /// </summary> /// <param name="numDataBytes">The num data bytes.</param> /// <param name="bits">The bits.</param> public static void terminateBits(int numDataBytes, BitArray bits) { int capacity = numDataBytes << 3; if (bits.Size > capacity) { throw new ZXingWriterException("data bits cannot fit in the QR Code" + bits.Size + " > " + capacity); } for (int i = 0; i < 4 && bits.Size < capacity; ++i) { bits.appendBit(false); } // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details. // If the last byte isn't 8-bit aligned, we'll add padding bits. int numBitsInLastByte = bits.Size & 0x07; if (numBitsInLastByte > 0) { for (int i = numBitsInLastByte; i < 8; i++) { bits.appendBit(false); } } // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24). int numPaddingBytes = numDataBytes - bits.SizeInBytes; for (int i = 0; i < numPaddingBytes; ++i) { bits.appendBits((i & 0x01) == 0 ? 0xEC : 0x11, 8); } if (bits.Size != capacity) { throw new ZXingWriterException("Bits size does not equal capacity"); } } /// <summary> /// Get number of data bytes and number of error correction bytes for block id "blockID". Store /// the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of /// JISX0510:2004 (p.30) /// </summary> /// <param name="numTotalBytes">The num total bytes.</param> /// <param name="numDataBytes">The num data bytes.</param> /// <param name="numRSBlocks">The num RS blocks.</param> /// <param name="blockID">The block ID.</param> /// <param name="numDataBytesInBlock">The num data bytes in block.</param> /// <param name="numECBytesInBlock">The num EC bytes in block.</param> public static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, int numDataBytes, int numRSBlocks, int blockID, int[] numDataBytesInBlock, int[] numECBytesInBlock) { if (blockID >= numRSBlocks) { throw new ZXingWriterException("Block ID too large"); } // numRsBlocksInGroup2 = 196 % 5 = 1 int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks; // numRsBlocksInGroup1 = 5 - 1 = 4 int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2; // numTotalBytesInGroup1 = 196 / 5 = 39 int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks; // numTotalBytesInGroup2 = 39 + 1 = 40 int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1; // numDataBytesInGroup1 = 66 / 5 = 13 int numDataBytesInGroup1 = numDataBytes / numRSBlocks; // numDataBytesInGroup2 = 13 + 1 = 14 int numDataBytesInGroup2 = numDataBytesInGroup1 + 1; // numEcBytesInGroup1 = 39 - 13 = 26 int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1; // numEcBytesInGroup2 = 40 - 14 = 26 int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2; // Sanity checks. // 26 = 26 if (numEcBytesInGroup1 != numEcBytesInGroup2) { throw new ZXingWriterException("EC bytes mismatch"); } // 5 = 4 + 1. if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2) { throw new ZXingWriterException("RS blocks mismatch"); } // 196 = (13 + 26) * 4 + (14 + 26) * 1 if (numTotalBytes != ((numDataBytesInGroup1 + numEcBytesInGroup1) * numRsBlocksInGroup1) + ((numDataBytesInGroup2 + numEcBytesInGroup2) * numRsBlocksInGroup2)) { throw new ZXingWriterException("Total bytes mismatch"); } if (blockID < numRsBlocksInGroup1) { numDataBytesInBlock[0] = numDataBytesInGroup1; numECBytesInBlock[0] = numEcBytesInGroup1; } else { numDataBytesInBlock[0] = numDataBytesInGroup2; numECBytesInBlock[0] = numEcBytesInGroup2; } } /// <summary> /// Interleave "bits" with corresponding error correction bytes. On success, store the result in /// "result". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details. /// </summary> /// <param name="bits">The bits.</param> /// <param name="numTotalBytes">The num total bytes.</param> /// <param name="numDataBytes">The num data bytes.</param> /// <param name="numRSBlocks">The num RS blocks.</param> /// <returns></returns> public static BitArray interleaveWithECBytes(BitArray bits, int numTotalBytes, int numDataBytes, int numRSBlocks) { // "bits" must have "getNumDataBytes" bytes of data. if (bits.SizeInBytes != numDataBytes) { throw new ZXingWriterException("Number of bits and data bytes does not match"); } // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll // store the divided data bytes blocks and error correction bytes blocks into "blocks". int dataBytesOffset = 0; int maxNumDataBytes = 0; int maxNumEcBytes = 0; // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number. var blocks = new List<BlockPair>(numRSBlocks); for (int i = 0; i < numRSBlocks; ++i) { int[] numDataBytesInBlock = new int[1]; int[] numEcBytesInBlock = new int[1]; getNumDataBytesAndNumECBytesForBlockID( numTotalBytes, numDataBytes, numRSBlocks, i, numDataBytesInBlock, numEcBytesInBlock); int size = numDataBytesInBlock[0]; byte[] dataBytes = new byte[size]; bits.toBytes(8 * dataBytesOffset, dataBytes, 0, size); byte[] ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]); blocks.Add(new BlockPair(dataBytes, ecBytes)); maxNumDataBytes = Math.Max(maxNumDataBytes, size); maxNumEcBytes = Math.Max(maxNumEcBytes, ecBytes.Length); dataBytesOffset += numDataBytesInBlock[0]; } if (numDataBytes != dataBytesOffset) { throw new ZXingWriterException("Data bytes does not match offset"); } BitArray result = new BitArray(); // First, place data blocks. for (int i = 0; i < maxNumDataBytes; ++i) { foreach (BlockPair block in blocks) { byte[] dataBytes = block.DataBytes; if (i < dataBytes.Length) { result.appendBits(dataBytes[i], 8); } } } // Then, place error correction blocks. for (int i = 0; i < maxNumEcBytes; ++i) { foreach (BlockPair block in blocks) { byte[] ecBytes = block.ErrorCorrectionBytes; if (i < ecBytes.Length) { result.appendBits(ecBytes[i], 8); } } } if (numTotalBytes != result.SizeInBytes) { // Should be same. throw new ZXingWriterException("Interleaving error: " + numTotalBytes + " and " + result.SizeInBytes + " differ."); } return result; } public static byte[] generateECBytes(byte[] dataBytes, int numEcBytesInBlock) { int numDataBytes = dataBytes.Length; int[] toEncode = new int[numDataBytes + numEcBytesInBlock]; for (int i = 0; i < numDataBytes; i++) { toEncode[i] = dataBytes[i] & 0xFF; } new ReedSolomonEncoder(GenericGF.QR_CODE_FIELD_256).encode(toEncode, numEcBytesInBlock); byte[] ecBytes = new byte[numEcBytesInBlock]; for (int i = 0; i < numEcBytesInBlock; i++) { ecBytes[i] = (byte)toEncode[numDataBytes + i]; } return ecBytes; } /// <summary> /// Append mode info. On success, store the result in "bits". /// </summary> /// <param name="mode">The mode.</param> /// <param name="bits">The bits.</param> public static void appendModeInfo(Mode mode, BitArray bits) { bits.appendBits(mode.Bits, 4); } /// <summary> /// Append length info. On success, store the result in "bits". /// </summary> /// <param name="numLetters">The num letters.</param> /// <param name="version">The version.</param> /// <param name="mode">The mode.</param> /// <param name="bits">The bits.</param> public static void appendLengthInfo(int numLetters, VersionInfo version, Mode mode, BitArray bits) { int numBits = mode.getCharacterCountBits(version); if (numLetters >= (1 << numBits)) { throw new ZXingWriterException(numLetters + " is bigger than " + ((1 << numBits) - 1)); } bits.appendBits(numLetters, numBits); } /// <summary> /// Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits". /// </summary> /// <param name="content">The content.</param> /// <param name="mode">The mode.</param> /// <param name="bits">The bits.</param> /// <param name="encoding">The encoding.</param> public static void appendBytes(String content, Mode mode, BitArray bits, String encoding) { if (mode.Equals(Mode.NUMERIC)) appendNumericBytes(content, bits); else if (mode.Equals(Mode.ALPHANUMERIC)) appendAlphanumericBytes(content, bits); else if (mode.Equals(Mode.BYTE)) append8BitBytes(content, bits, encoding); else if (mode.Equals(Mode.KANJI)) appendKanjiBytes(content, bits); else throw new ZXingWriterException("Invalid mode: " + mode); } public static void appendNumericBytes(String content, BitArray bits) { int length = content.Length; int i = 0; while (i < length) { int num1 = content[i] - '0'; if (i + 2 < length) { // Encode three numeric letters in ten bits. int num2 = content[i + 1] - '0'; int num3 = content[i + 2] - '0'; bits.appendBits(num1 * 100 + num2 * 10 + num3, 10); i += 3; } else if (i + 1 < length) { // Encode two numeric letters in seven bits. int num2 = content[i + 1] - '0'; bits.appendBits(num1 * 10 + num2, 7); i += 2; } else { // Encode one numeric letter in four bits. bits.appendBits(num1, 4); i++; } } } public static void appendAlphanumericBytes(String content, BitArray bits) { int length = content.Length; int i = 0; while (i < length) { int code1 = getAlphanumericCode(content[i]); if (code1 == -1) { throw new ZXingWriterException(); } if (i + 1 < length) { int code2 = getAlphanumericCode(content[i + 1]); if (code2 == -1) { throw new ZXingWriterException(); } // Encode two alphanumeric letters in 11 bits. bits.appendBits(code1 * 45 + code2, 11); i += 2; } else { // Encode one alphanumeric letter in six bits. bits.appendBits(code1, 6); i++; } } } public static void append8BitBytes(String content, BitArray bits, String encoding) { byte[] bytes; try { bytes = Encoding.GetEncoding(encoding).GetBytes(content); } #if WindowsCE catch (PlatformNotSupportedException) { try { // WindowsCE doesn't support all encodings. But it is device depended. // So we try here the some different ones if (encoding == "ISO-8859-1") { bytes = Encoding.GetEncoding(1252).GetBytes(content); } else { bytes = Encoding.GetEncoding("UTF-8").GetBytes(content); } } catch (Exception uee) { throw new WriterException(uee.Message, uee); } } #endif catch (Exception uee) { throw new ZXingWriterException(uee.Message, uee); } foreach (byte b in bytes) { bits.appendBits(b, 8); } } public static void appendKanjiBytes(String content, BitArray bits) { byte[] bytes; try { bytes = Encoding.GetEncoding("Shift_JIS").GetBytes(content); } catch (Exception uee) { throw new ZXingWriterException(uee.Message, uee); } int length = bytes.Length; for (int i = 0; i < length; i += 2) { int byte1 = bytes[i] & 0xFF; int byte2 = bytes[i + 1] & 0xFF; int code = (byte1 << 8) | byte2; int subtracted = -1; if (code >= 0x8140 && code <= 0x9ffc) { subtracted = code - 0x8140; } else if (code >= 0xe040 && code <= 0xebbf) { subtracted = code - 0xc140; } if (subtracted == -1) { throw new ZXingWriterException("Invalid byte sequence"); } int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff); bits.appendBits(encoded, 13); } } private static void appendECI(CharacterSetECI eci, BitArray bits) { bits.appendBits(Mode.ECI.Bits, 4); // This is correct for values up to 127, which is all we need now. bits.appendBits(eci.Value, 8); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Serialization { using System; using System.Reflection; using System.Collections; using System.ComponentModel; using System.Linq; using Collections.Generic; internal enum XmlAttributeFlags { Enum = 0x1, Array = 0x2, Text = 0x4, ArrayItems = 0x8, Elements = 0x10, Attribute = 0x20, Root = 0x40, Type = 0x80, AnyElements = 0x100, AnyAttribute = 0x200, ChoiceIdentifier = 0x400, XmlnsDeclarations = 0x800, } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class XmlAttributes { private XmlElementAttributes _xmlElements = new XmlElementAttributes(); private XmlArrayItemAttributes _xmlArrayItems = new XmlArrayItemAttributes(); private XmlAnyElementAttributes _xmlAnyElements = new XmlAnyElementAttributes(); private XmlArrayAttribute _xmlArray; private XmlAttributeAttribute _xmlAttribute; private XmlTextAttribute _xmlText; private XmlEnumAttribute _xmlEnum; private bool _xmlIgnore; private bool _xmlns; private object _xmlDefaultValue = null; private XmlRootAttribute _xmlRoot; private XmlTypeAttribute _xmlType; private XmlAnyAttributeAttribute _xmlAnyAttribute; private XmlChoiceIdentifierAttribute _xmlChoiceIdentifier; private static volatile Type s_ignoreAttributeType; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlAttributes() { } internal XmlAttributeFlags XmlFlags { get { XmlAttributeFlags flags = 0; if (_xmlElements.Count > 0) flags |= XmlAttributeFlags.Elements; if (_xmlArrayItems.Count > 0) flags |= XmlAttributeFlags.ArrayItems; if (_xmlAnyElements.Count > 0) flags |= XmlAttributeFlags.AnyElements; if (_xmlArray != null) flags |= XmlAttributeFlags.Array; if (_xmlAttribute != null) flags |= XmlAttributeFlags.Attribute; if (_xmlText != null) flags |= XmlAttributeFlags.Text; if (_xmlEnum != null) flags |= XmlAttributeFlags.Enum; if (_xmlRoot != null) flags |= XmlAttributeFlags.Root; if (_xmlType != null) flags |= XmlAttributeFlags.Type; if (_xmlAnyAttribute != null) flags |= XmlAttributeFlags.AnyAttribute; if (_xmlChoiceIdentifier != null) flags |= XmlAttributeFlags.ChoiceIdentifier; if (_xmlns) flags |= XmlAttributeFlags.XmlnsDeclarations; return flags; } } private static Type IgnoreAttribute { get { if (s_ignoreAttributeType == null) { s_ignoreAttributeType = typeof(object).Assembly.GetType("System.XmlIgnoreMemberAttribute"); if (s_ignoreAttributeType == null) { s_ignoreAttributeType = typeof(XmlIgnoreAttribute); } } return s_ignoreAttributeType; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlAttributes(ICustomAttributeProvider provider) { object[] attrs = provider.GetCustomAttributes(false); // most generic <any/> matches everything XmlAnyElementAttribute wildcard = null; for (int i = 0; i < attrs.Length; i++) { if (attrs[i] is XmlIgnoreAttribute || attrs[i] is ObsoleteAttribute || attrs[i].GetType() == IgnoreAttribute) { _xmlIgnore = true; break; } else if (attrs[i] is XmlElementAttribute) { _xmlElements.Add((XmlElementAttribute)attrs[i]); } else if (attrs[i] is XmlArrayItemAttribute) { _xmlArrayItems.Add((XmlArrayItemAttribute)attrs[i]); } else if (attrs[i] is XmlAnyElementAttribute) { XmlAnyElementAttribute any = (XmlAnyElementAttribute)attrs[i]; if ((any.Name == null || any.Name.Length == 0) && any.NamespaceSpecified && any.Namespace == null) { // ignore duplicate wildcards wildcard = any; } else { _xmlAnyElements.Add((XmlAnyElementAttribute)attrs[i]); } } else if (attrs[i] is DefaultValueAttribute) { _xmlDefaultValue = ((DefaultValueAttribute)attrs[i]).Value; } else if (attrs[i] is XmlAttributeAttribute) { _xmlAttribute = (XmlAttributeAttribute)attrs[i]; } else if (attrs[i] is XmlArrayAttribute) { _xmlArray = (XmlArrayAttribute)attrs[i]; } else if (attrs[i] is XmlTextAttribute) { _xmlText = (XmlTextAttribute)attrs[i]; } else if (attrs[i] is XmlEnumAttribute) { _xmlEnum = (XmlEnumAttribute)attrs[i]; } else if (attrs[i] is XmlRootAttribute) { _xmlRoot = (XmlRootAttribute)attrs[i]; } else if (attrs[i] is XmlTypeAttribute) { _xmlType = (XmlTypeAttribute)attrs[i]; } else if (attrs[i] is XmlAnyAttributeAttribute) { _xmlAnyAttribute = (XmlAnyAttributeAttribute)attrs[i]; } else if (attrs[i] is XmlChoiceIdentifierAttribute) { _xmlChoiceIdentifier = (XmlChoiceIdentifierAttribute)attrs[i]; } else if (attrs[i] is XmlNamespaceDeclarationsAttribute) { _xmlns = true; } } if (_xmlIgnore) { _xmlElements.Clear(); _xmlArrayItems.Clear(); _xmlAnyElements.Clear(); _xmlDefaultValue = null; _xmlAttribute = null; _xmlArray = null; _xmlText = null; _xmlEnum = null; _xmlType = null; _xmlAnyAttribute = null; _xmlChoiceIdentifier = null; _xmlns = false; } else { if (wildcard != null) { _xmlAnyElements.Add(wildcard); } } } internal static object GetAttr(MemberInfo memberInfo, Type attrType) { object[] attrs = memberInfo.GetCustomAttributes(attrType, false); if (attrs.Length == 0) return null; return attrs[0]; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlElementAttributes XmlElements { get { return _xmlElements; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlAttributeAttribute XmlAttribute { get { return _xmlAttribute; } set { _xmlAttribute = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlEnumAttribute XmlEnum { get { return _xmlEnum; } set { _xmlEnum = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlTextAttribute XmlText { get { return _xmlText; } set { _xmlText = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlArrayAttribute XmlArray { get { return _xmlArray; } set { _xmlArray = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlArrayItemAttributes XmlArrayItems { get { return _xmlArrayItems; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object XmlDefaultValue { get { return _xmlDefaultValue; } set { _xmlDefaultValue = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool XmlIgnore { get { return _xmlIgnore; } set { _xmlIgnore = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlTypeAttribute XmlType { get { return _xmlType; } set { _xmlType = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlRootAttribute XmlRoot { get { return _xmlRoot; } set { _xmlRoot = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlAnyElementAttributes XmlAnyElements { get { return _xmlAnyElements; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlAnyAttributeAttribute XmlAnyAttribute { get { return _xmlAnyAttribute; } set { _xmlAnyAttribute = value; } } public XmlChoiceIdentifierAttribute XmlChoiceIdentifier { get { return _xmlChoiceIdentifier; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool Xmlns { get { return _xmlns; } set { _xmlns = value; } } } }
namespace android.media { [global::MonoJavaBridge.JavaClass()] public partial class ExifInterface : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected ExifInterface(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public virtual global::java.lang.String getAttribute(java.lang.String arg0) { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.media.ExifInterface.staticClass, "getAttribute", "(Ljava/lang/String;)Ljava/lang/String;", ref global::android.media.ExifInterface._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m1; public virtual int getAttributeInt(java.lang.String arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.ExifInterface.staticClass, "getAttributeInt", "(Ljava/lang/String;I)I", ref global::android.media.ExifInterface._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m2; public virtual double getAttributeDouble(java.lang.String arg0, double arg1) { return global::MonoJavaBridge.JavaBridge.CallDoubleMethod(this, global::android.media.ExifInterface.staticClass, "getAttributeDouble", "(Ljava/lang/String;D)D", ref global::android.media.ExifInterface._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m3; public virtual void setAttribute(java.lang.String arg0, java.lang.String arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.ExifInterface.staticClass, "setAttribute", "(Ljava/lang/String;Ljava/lang/String;)V", ref global::android.media.ExifInterface._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m4; public virtual void saveAttributes() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.ExifInterface.staticClass, "saveAttributes", "()V", ref global::android.media.ExifInterface._m4); } private static global::MonoJavaBridge.MethodId _m5; public virtual bool hasThumbnail() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.media.ExifInterface.staticClass, "hasThumbnail", "()Z", ref global::android.media.ExifInterface._m5); } public new byte[] Thumbnail { get { return getThumbnail(); } } private static global::MonoJavaBridge.MethodId _m6; public virtual byte[] getThumbnail() { return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<byte>(this, global::android.media.ExifInterface.staticClass, "getThumbnail", "()[B", ref global::android.media.ExifInterface._m6) as byte[]; } private static global::MonoJavaBridge.MethodId _m7; public virtual bool getLatLong(float[] arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.media.ExifInterface.staticClass, "getLatLong", "([F)Z", ref global::android.media.ExifInterface._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m8; public ExifInterface(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.media.ExifInterface._m8.native == global::System.IntPtr.Zero) global::android.media.ExifInterface._m8 = @__env.GetMethodIDNoThrow(global::android.media.ExifInterface.staticClass, "<init>", "(Ljava/lang/String;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.media.ExifInterface.staticClass, global::android.media.ExifInterface._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } public static global::java.lang.String TAG_ORIENTATION { get { return "Orientation"; } } public static global::java.lang.String TAG_DATETIME { get { return "DateTime"; } } public static global::java.lang.String TAG_MAKE { get { return "Make"; } } public static global::java.lang.String TAG_MODEL { get { return "Model"; } } public static global::java.lang.String TAG_FLASH { get { return "Flash"; } } public static global::java.lang.String TAG_IMAGE_WIDTH { get { return "ImageWidth"; } } public static global::java.lang.String TAG_IMAGE_LENGTH { get { return "ImageLength"; } } public static global::java.lang.String TAG_GPS_LATITUDE { get { return "GPSLatitude"; } } public static global::java.lang.String TAG_GPS_LONGITUDE { get { return "GPSLongitude"; } } public static global::java.lang.String TAG_GPS_LATITUDE_REF { get { return "GPSLatitudeRef"; } } public static global::java.lang.String TAG_GPS_LONGITUDE_REF { get { return "GPSLongitudeRef"; } } public static global::java.lang.String TAG_GPS_TIMESTAMP { get { return "GPSTimeStamp"; } } public static global::java.lang.String TAG_GPS_DATESTAMP { get { return "GPSDateStamp"; } } public static global::java.lang.String TAG_WHITE_BALANCE { get { return "WhiteBalance"; } } public static global::java.lang.String TAG_FOCAL_LENGTH { get { return "FocalLength"; } } public static global::java.lang.String TAG_GPS_PROCESSING_METHOD { get { return "GPSProcessingMethod"; } } public static int ORIENTATION_UNDEFINED { get { return 0; } } public static int ORIENTATION_NORMAL { get { return 1; } } public static int ORIENTATION_FLIP_HORIZONTAL { get { return 2; } } public static int ORIENTATION_ROTATE_180 { get { return 3; } } public static int ORIENTATION_FLIP_VERTICAL { get { return 4; } } public static int ORIENTATION_TRANSPOSE { get { return 5; } } public static int ORIENTATION_ROTATE_90 { get { return 6; } } public static int ORIENTATION_TRANSVERSE { get { return 7; } } public static int ORIENTATION_ROTATE_270 { get { return 8; } } public static int WHITEBALANCE_AUTO { get { return 0; } } public static int WHITEBALANCE_MANUAL { get { return 1; } } static ExifInterface() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.media.ExifInterface.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/media/ExifInterface")); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Baseline; using Marten.Linq; using Marten.Schema; using Marten.Services; using Marten.Services.Events; using Marten.Storage; namespace Marten.Events { public class EventStore : IEventStore { private readonly IDocumentSession _session; private readonly IManagedConnection _connection; private readonly UnitOfWork _unitOfWork; private readonly ITenant _tenant; private readonly EventSelector _selector; private readonly DocumentStore _store; public EventStore(IDocumentSession session, DocumentStore store, IManagedConnection connection, UnitOfWork unitOfWork, ITenant tenant) { _session = session; _store = store; _connection = connection; _unitOfWork = unitOfWork; _tenant = tenant; _selector = new EventSelector(_store.Events, _store.Serializer); } public void Append(Guid stream, params object[] events) { _tenant.EnsureStorageExists(typeof(EventStream)); if (_unitOfWork.HasStream(stream)) { _unitOfWork.StreamFor(stream).AddEvents(events.Select(EventStream.ToEvent)); } else { var eventStream = new EventStream(stream, events.Select(EventStream.ToEvent).ToArray(), false); _unitOfWork.StoreStream(eventStream); } } public void Append(Guid stream, int expectedVersion, params object[] events) { Append(stream, events); var assertion = _unitOfWork.NonDocumentOperationsOf<AssertEventStreamMaxEventId>() .FirstOrDefault(x => x.Stream == stream); if (assertion == null) { _unitOfWork.Add(new AssertEventStreamMaxEventId(stream, expectedVersion, _store.Events.Table.QualifiedName)); } else { assertion.ExpectedVersion = expectedVersion; } } public Guid StartStream<T>(Guid id, params object[] events) where T : class, new() { _tenant.EnsureStorageExists(typeof(EventStream)); var stream = new EventStream(id, events.Select(EventStream.ToEvent).ToArray(), true) { AggregateType = typeof (T) }; _unitOfWork.StoreStream(stream); return id; } public Guid StartStream<TAggregate>(params object[] events) where TAggregate : class, new() { return StartStream<TAggregate>(Guid.NewGuid(), events); } public IList<IEvent> FetchStream(Guid streamId, int version = 0, DateTime? timestamp = null) { _tenant.EnsureStorageExists(typeof(EventStream)); var handler = new EventQueryHandler(_selector, streamId, version, timestamp); return _connection.Fetch(handler, null, null, _tenant); } public Task<IList<IEvent>> FetchStreamAsync(Guid streamId, int version = 0, DateTime? timestamp = null, CancellationToken token = new CancellationToken()) { _tenant.EnsureStorageExists(typeof(EventStream)); var handler = new EventQueryHandler(_selector, streamId, version, timestamp); return _connection.FetchAsync(handler, null, null, _tenant, token); } public T AggregateStream<T>(Guid streamId, int version = 0, DateTime? timestamp = null) where T : class, new() { _tenant.EnsureStorageExists(typeof(EventStream)); var inner = new EventQueryHandler(_selector, streamId, version, timestamp); var aggregator = _store.Events.AggregateFor<T>(); var handler = new AggregationQueryHandler<T>(aggregator, inner, _session); var aggregate = _connection.Fetch(handler, null, null, _tenant); var assignment = _tenant.IdAssignmentFor<T>(); assignment.Assign(_tenant, aggregate, streamId); return aggregate; } public async Task<T> AggregateStreamAsync<T>(Guid streamId, int version = 0, DateTime? timestamp = null, CancellationToken token = new CancellationToken()) where T : class, new() { _tenant.EnsureStorageExists(typeof(EventStream)); var inner = new EventQueryHandler(_selector, streamId, version, timestamp); var aggregator = _store.Events.AggregateFor<T>(); var handler = new AggregationQueryHandler<T>(aggregator, inner, _session); var aggregate = await _connection.FetchAsync(handler, null, null, _tenant, token).ConfigureAwait(false); var assignment = _tenant.IdAssignmentFor<T>(); assignment.Assign(_tenant, aggregate, streamId); return aggregate; } public IMartenQueryable<T> QueryRawEventDataOnly<T>() { _tenant.EnsureStorageExists(typeof(EventStream)); if (_store.Events.AllAggregates().Any(x => x.AggregateType == typeof(T))) { return _session.Query<T>(); } _store.Events.AddEventType(typeof(T)); return _session.Query<T>(); } public IMartenQueryable<IEvent> QueryAllRawEvents() { _tenant.EnsureStorageExists(typeof(EventStream)); return _session.Query<IEvent>(); } public Event<T> Load<T>(Guid id) where T : class { _tenant.EnsureStorageExists(typeof(EventStream)); _store.Events.AddEventType(typeof (T)); return Load(id).As<Event<T>>(); } public async Task<Event<T>> LoadAsync<T>(Guid id, CancellationToken token = default(CancellationToken)) where T : class { _tenant.EnsureStorageExists(typeof(EventStream)); _store.Events.AddEventType(typeof (T)); return (await LoadAsync(id, token).ConfigureAwait(false)).As<Event<T>>(); } public IEvent Load(Guid id) { _tenant.EnsureStorageExists(typeof(EventStream)); var handler = new SingleEventQueryHandler(id, _store.Events, _store.Serializer); return _connection.Fetch(handler, new NulloIdentityMap(_store.Serializer), null, _tenant); } public Task<IEvent> LoadAsync(Guid id, CancellationToken token = default(CancellationToken)) { _tenant.EnsureStorageExists(typeof(EventStream)); var handler = new SingleEventQueryHandler(id, _store.Events, _store.Serializer); return _connection.FetchAsync(handler, new NulloIdentityMap(_store.Serializer), null, _tenant, token); } public StreamState FetchStreamState(Guid streamId) { _tenant.EnsureStorageExists(typeof(EventStream)); var handler = new StreamStateHandler(_store.Events, streamId); return _connection.Fetch(handler, null, null, _tenant); } public Task<StreamState> FetchStreamStateAsync(Guid streamId, CancellationToken token = new CancellationToken()) { _tenant.EnsureStorageExists(typeof(EventStream)); var handler = new StreamStateHandler(_store.Events, streamId); return _connection.FetchAsync(handler, null, null, _tenant, token); } } }
/** * Copyright 2015 Marc Rufer, d-fens GmbH * * 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.Collections.Specialized; using System.Configuration; using System.Data.SqlClient; using System.Linq; using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Web; using biz.dfch.CS.Entity.LifeCycleManager.Contracts.Entity; using biz.dfch.CS.Entity.LifeCycleManager.UserData; using MSTestExtensions; using Telerik.JustMock; namespace biz.dfch.CS.Entity.LifeCycleManager.Tests.UserData { [TestClass] public class CurrentUserDataProviderTest { private const String USERNAME = "User"; private const String TENANT_ID = "aa506000-025b-474d-b747-53b67f50d46d"; private const String CONNECTION_STRING_NAME = "LcmSecurityData"; private const String APPLICATION_NAME_KEY = "Application.Name"; private const String DEFAULT_TENANT_ID_KEY = "TenantId.Default"; private const String CONNECTION_STRING = "Server=.\\SQLEXPRESS;User ID=sa;Password=password;Database=Test;"; private const String DEFAULT_TENANT_ID = "f61907fc-75a0-4303-8ad2-b8079fa2bb89"; private List<String> _permissions = new List<String>{ "XCanRead", "XCanCreate" }; private List<String> _roles = new List<String>{ "RoleX", "RoleY" }; [TestInitialize] public void TestInitialize() { Mock.SetupStatic(typeof(HttpContext)); Mock.SetupStatic(typeof(ConfigurationManager)); var connectionStrings = new ConnectionStringSettingsCollection(); connectionStrings.Add(new ConnectionStringSettings(CONNECTION_STRING_NAME, CONNECTION_STRING)); Mock.Arrange(() => ConfigurationManager.ConnectionStrings) .Returns(connectionStrings) .MustBeCalled(); } [TestMethod] public void GetCurrentUsernameGetsUsernameFromHttpContext() { Mock.Arrange(() => HttpContext.Current.User.Identity.Name) .Returns(USERNAME) .OccursOnce(); CurrentUserDataProvider.GetCurrentUsername(); Mock.Assert(() => HttpContext.Current.User.Identity.Name); } [TestMethod] public void IsEntityOfUserForMatchingTidAndCreatedByReturnsTrue() { Assert.IsTrue(CurrentUserDataProvider.IsEntityOfUser(USERNAME, TENANT_ID, new BaseEntity { CreatedBy = USERNAME, Tid = TENANT_ID })); } [TestMethod] public void IsEntityOfUserForNonMatchingTidAndCreatedByReturnsFalse() { Assert.IsFalse(CurrentUserDataProvider.IsEntityOfUser(USERNAME, TENANT_ID, new BaseEntity { CreatedBy = "Another", Tid = TENANT_ID })); Assert.IsFalse(CurrentUserDataProvider.IsEntityOfUser(USERNAME, TENANT_ID, new BaseEntity { CreatedBy = USERNAME, Tid = Guid.NewGuid().ToString() })); } [TestMethod] public void GetIdentityReturnsIdentityOfCurrentUser() { var sqlConnection = Mock.Create<SqlConnection>(); var sqlCommand = Mock.Create<SqlCommand>(); var sqlDataReader = Mock.Create<SqlDataReader>(); var userId = Guid.NewGuid(); Mock.Arrange(() => HttpContext.Current.User.Identity.Name) .Returns(USERNAME) .OccursOnce(); Mock.Arrange(() => ConfigurationManager.AppSettings) .Returns(new NameValueCollection{{ APPLICATION_NAME_KEY, "Test" }}) .OccursOnce(); Mock.Arrange(() => new SqlConnection(CONNECTION_STRING)) .DoNothing() .Occurs(3); Mock.Arrange(() => sqlConnection.Open()) .IgnoreInstance() .Occurs(3); Mock.Arrange(() => sqlCommand.ExecuteReader()) .IgnoreInstance() .Returns(sqlDataReader); Mock.Arrange(() => sqlDataReader.GetGuid(0)) .Returns(userId) .InSequence() .OccursOnce(); Mock.Arrange(() => sqlConnection.Close()) .IgnoreInstance() .Occurs(3); Mock.Arrange(() => sqlDataReader.Read()) .Returns(true) .InSequence(); Mock.Arrange(() => sqlDataReader.Read()) .Returns(true) .InSequence(); Mock.Arrange(() => sqlDataReader.Read()) .Returns(true) .InSequence(); Mock.Arrange(() => sqlDataReader.Read()) .Returns(false) .InSequence(); Mock.Arrange(() => sqlDataReader.GetString(0)) .Returns(_roles[0]) .InSequence() .OccursOnce(); Mock.Arrange(() => sqlDataReader.GetString(0)) .Returns(_roles[1]) .InSequence() .OccursOnce(); Mock.Arrange(() => sqlDataReader.Read()) .Returns(true) .InSequence(); Mock.Arrange(() => sqlDataReader.Read()) .Returns(true) .InSequence(); Mock.Arrange(() => sqlDataReader.Read()) .Returns(false) .InSequence(); Mock.Arrange(() => sqlDataReader.GetString(0)) .Returns(_permissions[0]) .InSequence() .OccursOnce(); Mock.Arrange(() => sqlDataReader.GetString(0)) .Returns(_permissions[1]) .InSequence() .OccursOnce(); var identity = CurrentUserDataProvider.GetIdentity(TENANT_ID); Assert.AreEqual(TENANT_ID, identity.Tid); Assert.AreEqual(USERNAME, identity.Username); CollectionAssert.AreEqual(_permissions, identity.Permissions.ToList()); CollectionAssert.AreEqual(_roles, identity.Roles.ToList()); Mock.Assert(() => HttpContext.Current.User.Identity.Name); Mock.Assert(() => ConfigurationManager.AppSettings); Mock.Assert(sqlConnection); Mock.Assert(sqlCommand); Mock.Assert(sqlDataReader); } [TestMethod] public void GetIdentityWithNullTenantIdReturnsIdentityOfCurrentUserWithDefaultTenantId() { var sqlConnection = Mock.Create<SqlConnection>(); var sqlCommand = Mock.Create<SqlCommand>(); var sqlDataReader = Mock.Create<SqlDataReader>(); var userId = Guid.NewGuid(); Mock.Arrange(() => HttpContext.Current.User.Identity.Name) .Returns(USERNAME) .OccursOnce(); Mock.Arrange(() => ConfigurationManager.AppSettings) .Returns(new NameValueCollection { { APPLICATION_NAME_KEY, "Test" } }) .OccursOnce(); Mock.Arrange(() => new SqlConnection(CONNECTION_STRING)) .DoNothing() .Occurs(3); Mock.Arrange(() => sqlConnection.Open()) .IgnoreInstance() .Occurs(3); Mock.Arrange(() => sqlCommand.ExecuteReader()) .IgnoreInstance() .Returns(sqlDataReader); Mock.Arrange(() => sqlDataReader.GetGuid(0)) .Returns(userId) .InSequence() .OccursOnce(); Mock.Arrange(() => sqlConnection.Close()) .IgnoreInstance() .Occurs(3); Mock.Arrange(() => sqlDataReader.Read()) .Returns(true) .InSequence(); Mock.Arrange(() => sqlDataReader.Read()) .Returns(true) .InSequence(); Mock.Arrange(() => sqlDataReader.Read()) .Returns(true) .InSequence(); Mock.Arrange(() => sqlDataReader.Read()) .Returns(false) .InSequence(); Mock.Arrange(() => sqlDataReader.GetString(0)) .Returns(_roles[0]) .InSequence() .OccursOnce(); Mock.Arrange(() => sqlDataReader.GetString(0)) .Returns(_roles[1]) .InSequence() .OccursOnce(); Mock.Arrange(() => sqlDataReader.Read()) .Returns(true) .InSequence(); Mock.Arrange(() => sqlDataReader.Read()) .Returns(true) .InSequence(); Mock.Arrange(() => sqlDataReader.Read()) .Returns(false) .InSequence(); Mock.Arrange(() => sqlDataReader.GetString(0)) .Returns(_permissions[0]) .InSequence() .OccursOnce(); Mock.Arrange(() => sqlDataReader.GetString(0)) .Returns(_permissions[1]) .InSequence() .OccursOnce(); var identity = CurrentUserDataProvider.GetIdentity(null); Assert.AreEqual(DEFAULT_TENANT_ID, identity.Tid); Assert.AreEqual(USERNAME, identity.Username); CollectionAssert.AreEqual(_permissions, identity.Permissions.ToList()); CollectionAssert.AreEqual(_roles, identity.Roles.ToList()); Mock.Assert(() => HttpContext.Current.User.Identity.Name); Mock.Assert(() => ConfigurationManager.AppSettings); Mock.Assert(sqlConnection); Mock.Assert(sqlCommand); Mock.Assert(sqlDataReader); } [TestMethod] public void GetIdentityThrowsArgumentNullExceptionIfApplicationNameNotDefined() { Mock.Arrange(() => HttpContext.Current.User.Identity.Name) .Returns(USERNAME) .OccursOnce(); Mock.Arrange(() => ConfigurationManager.AppSettings) .Returns(new NameValueCollection()) .OccursOnce(); ThrowsAssert.Throws<ArgumentNullException>(() => CurrentUserDataProvider.GetIdentity(TENANT_ID)); Mock.Assert(() => HttpContext.Current.User.Identity.Name); Mock.Assert(() => ConfigurationManager.AppSettings); } [TestMethod] public void GetConnectionStringForExistingConnectionStringReturnsConnectionStringFromConfiguration() { MethodInfo method = typeof(CurrentUserDataProvider) .GetMethod("GetConnectionString", BindingFlags.Static | BindingFlags.NonPublic); String connectionString = (String)method.Invoke(null, new object[] { }); Assert.AreEqual(CONNECTION_STRING, connectionString); Mock.Assert(() => ConfigurationManager.ConnectionStrings); } [TestMethod] public void GetConnectionStringForNonExistingConnectionStringThrowsArgumentException() { var connectionStrings = new ConnectionStringSettingsCollection(); connectionStrings.Add(new ConnectionStringSettings("AnotherConnectionString", CONNECTION_STRING)); Mock.Arrange(() => ConfigurationManager.ConnectionStrings) .Returns(connectionStrings) .MustBeCalled(); MethodInfo method = typeof(CurrentUserDataProvider) .GetMethod("GetConnectionString", BindingFlags.Static | BindingFlags.NonPublic); try { method.Invoke(null, new object[] {}); } catch (TargetInvocationException ex) { Assert.IsTrue(ex.GetBaseException().GetType() == typeof(ArgumentException)); } Mock.Assert(() => ConfigurationManager.ConnectionStrings); } } }
// 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.Runtime; using System.Threading; using System.Threading.Tasks; namespace System.ServiceModel.Channels { internal class BufferedConnection : DelegatingConnection { private byte[] _writeBuffer; private int _writeBufferSize; private int _pendingWriteSize; private Exception _pendingWriteException; private Timer _flushTimer; private TimeSpan _flushTimeout; private TimeSpan _pendingTimeout; private const int maxFlushSkew = 100; public BufferedConnection(IConnection connection, TimeSpan flushTimeout, int writeBufferSize) : base(connection) { _flushTimeout = flushTimeout; _writeBufferSize = writeBufferSize; } private object ThisLock { get { return this; } } public override void Close(TimeSpan timeout, bool asyncAndLinger) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); Flush(timeoutHelper.RemainingTime()); base.Close(timeoutHelper.RemainingTime(), asyncAndLinger); } private void CancelFlushTimer() { if (_flushTimer != null) { _flushTimer.Change(TimeSpan.FromMilliseconds(-1), TimeSpan.FromMilliseconds(-1)); _pendingTimeout = TimeSpan.Zero; } } private void Flush(TimeSpan timeout) { ThrowPendingWriteException(); lock (ThisLock) { FlushCore(timeout); } } private void FlushCore(TimeSpan timeout) { if (_pendingWriteSize > 0) { Connection.Write(_writeBuffer, 0, _pendingWriteSize, false, timeout); _pendingWriteSize = 0; } } private void OnFlushTimer(object state) { lock (ThisLock) { try { FlushCore(_pendingTimeout); _pendingTimeout = TimeSpan.Zero; } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } _pendingWriteException = e; CancelFlushTimer(); } } } private void SetFlushTimer() { if (_flushTimer == null) { _flushTimer = new Timer(new TimerCallback(new Action<object>(OnFlushTimer)), null, TimeSpan.FromMilliseconds(-1), TimeSpan.FromMilliseconds(-1)); } _flushTimer.Change(_flushTimeout, TimeSpan.FromMilliseconds(-1)); } public override void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, BufferManager bufferManager) { if (size <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(size), size, SR.ValueMustBePositive)); } ThrowPendingWriteException(); if (immediate || _flushTimeout == TimeSpan.Zero) { WriteNow(buffer, offset, size, timeout, bufferManager); } else { WriteLater(buffer, offset, size, timeout); bufferManager.ReturnBuffer(buffer); } } public override void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout) { if (size <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(size), size, SR.ValueMustBePositive)); } ThrowPendingWriteException(); if (immediate || _flushTimeout == TimeSpan.Zero) { WriteNow(buffer, offset, size, timeout); } else { WriteLater(buffer, offset, size, timeout); } } private void WriteNow(byte[] buffer, int offset, int size, TimeSpan timeout) { WriteNow(buffer, offset, size, timeout, null); } private void WriteNow(byte[] buffer, int offset, int size, TimeSpan timeout, BufferManager bufferManager) { lock (ThisLock) { if (_pendingWriteSize > 0) { int remainingSize = _writeBufferSize - _pendingWriteSize; CancelFlushTimer(); if (size <= remainingSize) { Buffer.BlockCopy(buffer, offset, _writeBuffer, _pendingWriteSize, size); if (bufferManager != null) { bufferManager.ReturnBuffer(buffer); } _pendingWriteSize += size; FlushCore(timeout); return; } else { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); FlushCore(timeoutHelper.RemainingTime()); timeout = timeoutHelper.RemainingTime(); } } if (bufferManager == null) { Connection.Write(buffer, offset, size, true, timeout); } else { Connection.Write(buffer, offset, size, true, timeout, bufferManager); } } } private void WriteLater(byte[] buffer, int offset, int size, TimeSpan timeout) { lock (ThisLock) { bool setTimer = (_pendingWriteSize == 0); TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); while (size > 0) { if (size >= _writeBufferSize && _pendingWriteSize == 0) { Connection.Write(buffer, offset, size, false, timeoutHelper.RemainingTime()); size = 0; } else { if (_writeBuffer == null) { _writeBuffer = Fx.AllocateByteArray(_writeBufferSize); } int remainingSize = _writeBufferSize - _pendingWriteSize; int copySize = size; if (copySize > remainingSize) { copySize = remainingSize; } Buffer.BlockCopy(buffer, offset, _writeBuffer, _pendingWriteSize, copySize); _pendingWriteSize += copySize; if (_pendingWriteSize == _writeBufferSize) { FlushCore(timeoutHelper.RemainingTime()); setTimer = true; } size -= copySize; offset += copySize; } } if (_pendingWriteSize > 0) { if (setTimer) { SetFlushTimer(); _pendingTimeout = TimeoutHelper.Add(_pendingTimeout, timeoutHelper.RemainingTime()); } } else { CancelFlushTimer(); } } } public override AsyncCompletionResult BeginWrite(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, Action<object> callback, object state) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); Flush(timeoutHelper.RemainingTime()); return base.BeginWrite(buffer, offset, size, immediate, timeoutHelper.RemainingTime(), callback, state); } public override void EndWrite() { base.EndWrite(); } private void ThrowPendingWriteException() { if (_pendingWriteException != null) { lock (ThisLock) { if (_pendingWriteException != null) { Exception exceptionTothrow = _pendingWriteException; _pendingWriteException = null; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exceptionTothrow); } } } } } internal class BufferedConnectionInitiator : IConnectionInitiator { private IConnectionInitiator _connectionInitiator; public BufferedConnectionInitiator(IConnectionInitiator connectionInitiator, TimeSpan flushTimeout, int writeBufferSize) { _connectionInitiator = connectionInitiator; FlushTimeout = flushTimeout; WriteBufferSize = writeBufferSize; } protected TimeSpan FlushTimeout { get; } protected int WriteBufferSize { get; } public IConnection Connect(Uri uri, TimeSpan timeout) { return new BufferedConnection(_connectionInitiator.Connect(uri, timeout), FlushTimeout, WriteBufferSize); } public async Task<IConnection> ConnectAsync(Uri uri, TimeSpan timeout) { return new BufferedConnection(await _connectionInitiator.ConnectAsync(uri, timeout), FlushTimeout, WriteBufferSize); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Text.RegularExpressions; using System.Threading; using EnvDTE; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestUtilities; using TestUtilities.SharedProject; using TestUtilities.UI; using MSBuild = Microsoft.Build.Evaluation; using MessageBoxButton = TestUtilities.MessageBoxButton; using Microsoft.VisualStudioTools.VSTestHost; namespace VisualStudioToolsUITests { [TestClass] public class LinkedFileTests : SharedProjectTest { private static ProjectDefinition LinkedFiles(ProjectType projectType) { return new ProjectDefinition( "LinkedFiles", projectType, ItemGroup( Folder("MoveToFolder"), Folder("FolderWithAFile"), Folder("Fob"), Folder("..\\LinkedFilesDir", isExcluded: true), Folder("AlreadyLinkedFolder"), Compile("Program"), Compile("..\\ImplicitLinkedFile"), Compile("..\\ExplicitLinkedFile") .Link("ExplicitDir\\ExplicitLinkedFile"), Compile("..\\ExplicitLinkedFileWrongFilename") .Link("ExplicitDir\\Blah"), Compile("..\\MovedLinkedFile"), Compile("..\\MovedLinkedFileOpen"), Compile("..\\MovedLinkedFileOpenEdit"), Compile("..\\FileNotInProject"), Compile("..\\DeletedLinkedFile"), Compile("LinkedInModule") .Link("Fob\\LinkedInModule"), Compile("SaveAsCreateLink"), Compile("..\\SaveAsCreateFile"), Compile("..\\SaveAsCreateFileNewDirectory"), Compile("FolderWithAFile\\ExistsOnDiskAndInProject"), Compile("FolderWithAFile\\ExistsInProjectButNotOnDisk", isMissing: true), Compile("FolderWithAFile\\ExistsOnDiskButNotInProject"), Compile("..\\LinkedFilesDir\\SomeLinkedFile") .Link("Oar\\SomeLinkedFile"), Compile("..\\RenamedLinkFile") .Link("Fob\\NewNameForLinkFile"), Compile("..\\BadLinkPath") .Link("..\\BadLinkPathFolder\\BadLinkPath"), Compile("..\\RootedLinkIgnored") .Link("C:\\RootedLinkIgnored"), Compile("C:\\RootedIncludeIgnored", isMissing: true) .Link("RootedIncludeIgnored"), Compile("Fob\\AddExistingInProjectDirButNotInProject"), Compile("..\\ExistingItem", isExcluded: true), Compile("..\\ExistsInProjectButNotOnDisk", isExcluded: true), Compile("..\\ExistsOnDiskAndInProject", isExcluded: true), Compile("..\\ExistsOnDiskButNotInProject", isExcluded: true) ) ); } private static SolutionFile MultiProjectLinkedFiles(ProjectType projectType) { return SolutionFile.Generate( "MultiProjectLinkedFiles", new ProjectDefinition( "LinkedFiles1", projectType, ItemGroup( Compile("..\\FileNotInProject1"), Compile("..\\FileNotInProject2") ) ), new ProjectDefinition( "LinkedFiles2", projectType, ItemGroup( Compile("..\\FileNotInProject2", isMissing: true) ) ) ); } [ClassInitialize] public static void DoDeployment(TestContext context) { AssertListener.Initialize(); } [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void RenameLinkedNode() { foreach (var projectType in ProjectTypes) { using (var solution = LinkedFiles(projectType).Generate().ToVs()) { // implicitly linked node var projectNode = solution.FindItem("LinkedFiles", "ImplicitLinkedFile" + projectType.CodeExtension); Assert.IsNotNull(projectNode, "projectNode"); AutomationWrapper.Select(projectNode); try { solution.ExecuteCommand("File.Rename"); Assert.Fail("Should have failed to rename"); } catch (Exception e) { Debug.WriteLine(e.ToString()); } // explicitly linked node var explicitLinkedFile = solution.FindItem("LinkedFiles", "ExplicitDir", "ExplicitLinkedFile" + projectType.CodeExtension); Assert.IsNotNull(explicitLinkedFile, "explicitLinkedFile"); AutomationWrapper.Select(explicitLinkedFile); try { solution.ExecuteCommand("File.Rename"); Assert.Fail("Should have failed to rename"); } catch (Exception e) { Debug.WriteLine(e.ToString()); } var autoItem = solution.GetProject("LinkedFiles").ProjectItems.Item("ImplicitLinkedFile" + projectType.CodeExtension); try { autoItem.Properties.Item("FileName").Value = "Fob"; Assert.Fail("Should have failed to rename"); } catch (InvalidOperationException) { } autoItem = solution.GetProject("LinkedFiles").ProjectItems.Item("ExplicitDir").ProjectItems.Item("ExplicitLinkedFile" + projectType.CodeExtension); try { autoItem.Properties.Item("FileName").Value = "Fob"; Assert.Fail("Should have failed to rename"); } catch (InvalidOperationException) { } } } } [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void MoveLinkedNode() { foreach (var projectType in ProjectTypes) { using (var solution = LinkedFiles(projectType).Generate().ToVs()) { var projectNode = solution.FindItem("LinkedFiles", "MovedLinkedFile" + projectType.CodeExtension); Assert.IsNotNull(projectNode, "projectNode"); AutomationWrapper.Select(projectNode); solution.ExecuteCommand("Edit.Cut"); var folderNode = solution.FindItem("LinkedFiles", "MoveToFolder"); AutomationWrapper.Select(folderNode); solution.ExecuteCommand("Edit.Paste"); // item should have moved var movedLinkedFile = solution.WaitForItem("LinkedFiles", "MoveToFolder", "MovedLinkedFile" + projectType.CodeExtension); Assert.IsNotNull(movedLinkedFile, "movedLinkedFile"); // file should be at the same location Assert.IsTrue(File.Exists(Path.Combine(solution.SolutionDirectory, "MovedLinkedFile" + projectType.CodeExtension))); Assert.IsFalse(File.Exists(Path.Combine(solution.SolutionDirectory, "MoveToFolder\\MovedLinkedFile" + projectType.CodeExtension))); // now move it back AutomationWrapper.Select(movedLinkedFile); solution.ExecuteCommand("Edit.Cut"); var originalFolder = solution.FindItem("LinkedFiles"); AutomationWrapper.Select(originalFolder); solution.ExecuteCommand("Edit.Paste"); var movedLinkedFilePaste = solution.WaitForItem("LinkedFiles", "MovedLinkedFile" + projectType.CodeExtension); Assert.IsNotNull(movedLinkedFilePaste, "movedLinkedFilePaste"); // and make sure we didn't mess up the path in the project file MSBuild.Project buildProject = new MSBuild.Project(solution.GetProject("LinkedFiles").FullName); bool found = false; foreach (var item in buildProject.GetItems("Compile")) { if (item.UnevaluatedInclude == "..\\MovedLinkedFile" + projectType.CodeExtension) { found = true; break; } } Assert.IsTrue(found); } } } [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void MultiProjectMove() { foreach (var projectType in ProjectTypes) { using (var solution = MultiProjectLinkedFiles(projectType).ToVs()) { var fileNode = solution.FindItem("LinkedFiles1", "FileNotInProject1" + projectType.CodeExtension); Assert.IsNotNull(fileNode, "projectNode"); AutomationWrapper.Select(fileNode); solution.ExecuteCommand("Edit.Copy"); var folderNode = solution.FindItem("LinkedFiles2"); AutomationWrapper.Select(folderNode); solution.ExecuteCommand("Edit.Paste"); // item should have moved var copiedFile = solution.WaitForItem("LinkedFiles2", "FileNotInProject1" + projectType.CodeExtension); Assert.IsNotNull(copiedFile, "movedLinkedFile"); Assert.AreEqual( true, solution.GetProject("LinkedFiles2").ProjectItems.Item("FileNotInProject1" + projectType.CodeExtension).Properties.Item("IsLinkFile").Value ); } } } [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void MultiProjectMoveExists2() { foreach (var projectType in ProjectTypes) { using (var solution = MultiProjectLinkedFiles(projectType).ToVs()) { var fileNode = solution.FindItem("LinkedFiles1", "FileNotInProject2" + projectType.CodeExtension); Assert.IsNotNull(fileNode, "projectNode"); AutomationWrapper.Select(fileNode); solution.ExecuteCommand("Edit.Copy"); var folderNode = solution.FindItem("LinkedFiles2"); AutomationWrapper.Select(folderNode); ThreadPool.QueueUserWorkItem(x => solution.ExecuteCommand("Edit.Paste")); string path = Path.Combine(solution.SolutionDirectory, "FileNotInProject2" + projectType.CodeExtension); VisualStudioApp.CheckMessageBox(String.Format("There is already a link to '{0}'. You cannot have more than one link to the same file in a project.", path)); solution.WaitForDialogDismissed(); } } } [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void MoveLinkedNodeOpen() { foreach (var projectType in ProjectTypes) { using (var solution = LinkedFiles(projectType).Generate().ToVs()) { var openWindow = solution.GetProject("LinkedFiles").ProjectItems.Item("MovedLinkedFileOpen" + projectType.CodeExtension).Open(); Assert.IsNotNull(openWindow, "openWindow"); var projectNode = solution.FindItem("LinkedFiles", "MovedLinkedFileOpen" + projectType.CodeExtension); Assert.IsNotNull(projectNode, "projectNode"); AutomationWrapper.Select(projectNode); solution.ExecuteCommand("Edit.Cut"); var folderNode = solution.FindItem("LinkedFiles", "MoveToFolder"); AutomationWrapper.Select(folderNode); solution.ExecuteCommand("Edit.Paste"); var movedLinkedFileOpen = solution.WaitForItem("LinkedFiles", "MoveToFolder", "MovedLinkedFileOpen" + projectType.CodeExtension); Assert.IsNotNull(movedLinkedFileOpen, "movedLinkedFileOpen"); Assert.IsTrue(File.Exists(Path.Combine(solution.SolutionDirectory, Path.Combine(solution.SolutionDirectory, "MovedLinkedFileOpen" + projectType.CodeExtension)))); Assert.IsFalse(File.Exists(Path.Combine(solution.SolutionDirectory, "MoveToFolder\\MovedLinkedFileOpen" + projectType.CodeExtension))); // window sholudn't have changed. Assert.AreEqual(VSTestContext.DTE.Windows.Item("MovedLinkedFileOpen" + projectType.CodeExtension), openWindow); } } } [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void MoveLinkedNodeOpenEdited() { foreach (var projectType in ProjectTypes) { using (var solution = LinkedFiles(projectType).Generate().ToVs()) { var openWindow = solution.GetProject("LinkedFiles").ProjectItems.Item("MovedLinkedFileOpenEdit" + projectType.CodeExtension).Open(); Assert.IsNotNull(openWindow, "openWindow"); var selection = ((TextSelection)openWindow.Selection); selection.SelectAll(); selection.Delete(); var projectNode = solution.FindItem("LinkedFiles", "MovedLinkedFileOpenEdit" + projectType.CodeExtension); Assert.IsNotNull(projectNode, "projectNode"); AutomationWrapper.Select(projectNode); solution.ExecuteCommand("Edit.Cut"); var folderNode = solution.FindItem("LinkedFiles", "MoveToFolder"); AutomationWrapper.Select(folderNode); solution.ExecuteCommand("Edit.Paste"); var movedLinkedFileOpenEdit = solution.WaitForItem("LinkedFiles", "MoveToFolder", "MovedLinkedFileOpenEdit" + projectType.CodeExtension); Assert.IsNotNull(movedLinkedFileOpenEdit, "movedLinkedFileOpenEdit"); Assert.IsTrue(File.Exists(Path.Combine(solution.SolutionDirectory, "MovedLinkedFileOpenEdit" + projectType.CodeExtension))); Assert.IsFalse(File.Exists(Path.Combine(solution.SolutionDirectory, "MoveToFolder\\MovedLinkedFileOpenEdit" + projectType.CodeExtension))); // window sholudn't have changed. Assert.AreEqual(VSTestContext.DTE.Windows.Item("MovedLinkedFileOpenEdit" + projectType.CodeExtension), openWindow); Assert.AreEqual(openWindow.Document.Saved, false); openWindow.Document.Save(); Assert.AreEqual(new FileInfo(Path.Combine(solution.SolutionDirectory, "MovedLinkedFileOpenEdit" + projectType.CodeExtension)).Length, (long)0); } } } [Ignore] [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void MoveLinkedNodeFileExistsButNotInProject() { foreach (var projectType in ProjectTypes) { using (var solution = LinkedFiles(projectType).Generate().ToVs()) { var fileNode = solution.FindItem("LinkedFiles", "FileNotInProject" + projectType.CodeExtension); Assert.IsNotNull(fileNode, "projectNode"); AutomationWrapper.Select(fileNode); solution.ExecuteCommand("Edit.Cut"); var folderNode = solution.FindItem("LinkedFiles", "FolderWithAFile"); AutomationWrapper.Select(folderNode); solution.ExecuteCommand("Edit.Paste"); // item should have moved var fileNotInProject = solution.WaitForItem("LinkedFiles", "FolderWithAFile", "FileNotInProject" + projectType.CodeExtension); Assert.IsNotNull(fileNotInProject, "fileNotInProject"); // but it should be the linked file on disk outside of our project, not the file that exists on disk at the same location. var autoItem = solution.GetProject("LinkedFiles").ProjectItems.Item("FolderWithAFile").ProjectItems.Item("FileNotInProject" + projectType.CodeExtension); Assert.AreEqual(Path.Combine(solution.SolutionDirectory, "FileNotInProject" + projectType.CodeExtension), autoItem.Properties.Item("FullPath").Value); } } } [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void DeleteLinkedNode() { foreach (var projectType in ProjectTypes) { using (var solution = LinkedFiles(projectType).Generate().ToVs()) { var projectNode = solution.FindItem("LinkedFiles", "DeletedLinkedFile" + projectType.CodeExtension); Assert.IsNotNull(projectNode, "projectNode"); AutomationWrapper.Select(projectNode); solution.ExecuteCommand("Edit.Delete"); projectNode = solution.FindItem("LinkedFiles", "DeletedLinkedFile" + projectType.CodeExtension); Assert.AreEqual(null, projectNode); Assert.IsTrue(File.Exists(Path.Combine(solution.SolutionDirectory, "DeletedLinkedFile" + projectType.CodeExtension))); } } } [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void LinkedFileInProjectIgnored() { foreach (var projectType in ProjectTypes) { using (var solution = LinkedFiles(projectType).Generate().ToVs()) { var projectNode = solution.FindItem("LinkedFiles", "Fob", "LinkedInModule" + projectType.CodeExtension); Assert.IsNull(projectNode); } } } [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void SaveAsCreateLink() { foreach (var projectType in ProjectTypes) { using (var solution = LinkedFiles(projectType).Generate().ToVs()) { var autoItem = solution.GetProject("LinkedFiles").ProjectItems.Item("SaveAsCreateLink" + projectType.CodeExtension); var isLinkFile = autoItem.Properties.Item("IsLinkFile").Value; Assert.AreEqual(isLinkFile, false); var itemWindow = autoItem.Open(); autoItem.SaveAs("..\\SaveAsCreateLink" + projectType.CodeExtension); autoItem = solution.GetProject("LinkedFiles").ProjectItems.Item("SaveAsCreateLink" + projectType.CodeExtension); isLinkFile = autoItem.Properties.Item("IsLinkFile").Value; Assert.AreEqual(isLinkFile, true); } } } [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void SaveAsCreateFile() { foreach (var projectType in ProjectTypes) { using (var solution = LinkedFiles(projectType).Generate().ToVs()) { var autoItem = solution.GetProject("LinkedFiles").ProjectItems.Item("SaveAsCreateFile" + projectType.CodeExtension); var isLinkFile = autoItem.Properties.Item("IsLinkFile").Value; Assert.AreEqual(isLinkFile, true); var itemWindow = autoItem.Open(); autoItem.SaveAs(Path.Combine(solution.SolutionDirectory, "LinkedFiles\\SaveAsCreateFile" + projectType.CodeExtension)); autoItem = solution.GetProject("LinkedFiles").ProjectItems.Item("SaveAsCreateFile" + projectType.CodeExtension); isLinkFile = autoItem.Properties.Item("IsLinkFile").Value; Assert.AreEqual(isLinkFile, false); } } } [Ignore] [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void SaveAsCreateFileNewDirectory() { foreach (var projectType in ProjectTypes) { using (var solution = LinkedFiles(projectType).Generate().ToVs()) { var autoItem = solution.GetProject("LinkedFiles").ProjectItems.Item("SaveAsCreateFileNewDirectory" + projectType.CodeExtension); var isLinkFile = autoItem.Properties.Item("IsLinkFile").Value; Assert.AreEqual(isLinkFile, true); var itemWindow = autoItem.Open(); Directory.CreateDirectory(Path.Combine(solution.SolutionDirectory, "LinkedFiles\\CreatedDirectory")); autoItem.SaveAs(Path.Combine(solution.SolutionDirectory, "LinkedFiles\\CreatedDirectory\\SaveAsCreateFileNewDirectory" + projectType.CodeExtension)); autoItem = solution.GetProject("LinkedFiles").ProjectItems.Item("CreatedDirectory").ProjectItems.Item("SaveAsCreateFileNewDirectory" + projectType.CodeExtension); isLinkFile = autoItem.Properties.Item("IsLinkFile").Value; Assert.AreEqual(isLinkFile, false); } } } /// <summary> /// Adding a duplicate link to the same item /// </summary> [Ignore] [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void AddExistingItem() { foreach (var projectType in ProjectTypes) { using (var solution = LinkedFiles(projectType).Generate().ToVs()) { var projectNode = solution.FindItem("LinkedFiles", "FolderWithAFile"); Assert.IsNotNull(projectNode, "projectNode"); AutomationWrapper.Select(projectNode); using (var addExistingDlg = solution.AddExistingItem()) { addExistingDlg.FileName = Path.Combine(solution.SolutionDirectory, "ExistingItem" + projectType.CodeExtension); addExistingDlg.AddLink(); } var existingItem = solution.WaitForItem("LinkedFiles", "FolderWithAFile", "ExistingItem" + projectType.CodeExtension); Assert.IsNotNull(existingItem, "existingItem"); } } } /// <summary> /// Adding a link to a folder which is already linked in somewhere else. /// </summary> [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void AddExistingItemAndItemIsAlreadyLinked() { foreach (var projectType in ProjectTypes) { using (var solution = LinkedFiles(projectType).Generate().ToVs()) { var projectNode = solution.FindItem("LinkedFiles", "AlreadyLinkedFolder"); Assert.IsNotNull(projectNode, "projectNode"); AutomationWrapper.Select(projectNode); using (var addExistingDlg = solution.AddExistingItem()) { addExistingDlg.FileName = Path.Combine(solution.SolutionDirectory, "FileNotInProject" + projectType.CodeExtension); addExistingDlg.AddLink(); } solution.WaitForDialog(); solution.CheckMessageBox(MessageBoxButton.Ok, "There is already a link to", "A project cannot have more than one link to the same file.", "FileNotInProject" + projectType.CodeExtension); } } } /// <summary> /// Adding a duplicate link to the same item. /// /// Also because the linked file dir is "LinkedFilesDir" which is a substring of "LinkedFiles" (our project name) /// this verifies we deal with the project name string comparison correctly (including a \ at the end of the /// path). /// </summary> [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void AddExistingItemAndLinkAlreadyExists() { foreach (var projectType in ProjectTypes) { using (var solution = LinkedFiles(projectType).Generate().ToVs()) { var projectNode = solution.FindItem("LinkedFiles", "Oar"); Assert.IsNotNull(projectNode, "projectNode"); AutomationWrapper.Select(projectNode); using (var addExistingDlg = solution.AddExistingItem()) { addExistingDlg.FileName = Path.Combine(solution.SolutionDirectory, "LinkedFilesDir\\SomeLinkedFile" + projectType.CodeExtension); addExistingDlg.AddLink(); } solution.WaitForDialog(); solution.CheckMessageBox(MessageBoxButton.Ok, "There is already a link to", "SomeLinkedFile" + projectType.CodeExtension); } } } /// <summary> /// Adding new linked item when file of same name exists (when the file only exists on disk) /// </summary> [Ignore] [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void AddExistingItemAndFileByNameExistsOnDiskButNotInProject() { foreach (var projectType in ProjectTypes) { using (var solution = LinkedFiles(projectType).Generate().ToVs()) { var projectNode = solution.FindItem("LinkedFiles", "FolderWithAFile"); Assert.IsNotNull(projectNode, "projectNode"); AutomationWrapper.Select(projectNode); using (var addExistingDlg = solution.AddExistingItem()) { addExistingDlg.FileName = Path.Combine(solution.SolutionDirectory, "ExistsOnDiskButNotInProject" + projectType.CodeExtension); addExistingDlg.AddLink(); } solution.WaitForDialog(); solution.CheckMessageBox(MessageBoxButton.Ok, "There is already a file of the same name in this folder."); } } } /// <summary> /// Adding new linked item when file of same name exists (both in the project and on disk) /// </summary> [Ignore] [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void AddExistingItemAndFileByNameExistsOnDiskAndInProject() { foreach (var projectType in ProjectTypes) { using (var solution = LinkedFiles(projectType).Generate().ToVs()) { var projectNode = solution.FindItem("LinkedFiles", "FolderWithAFile"); Assert.IsNotNull(projectNode, "projectNode"); AutomationWrapper.Select(projectNode); using (var addExistingDlg = solution.AddExistingItem()) { addExistingDlg.FileName = Path.Combine(solution.SolutionDirectory, "ExistsOnDiskAndInProject" + projectType.CodeExtension); addExistingDlg.AddLink(); } solution.WaitForDialog(); solution.CheckMessageBox(MessageBoxButton.Ok, "There is already a file of the same name in this folder."); } } } /// <summary> /// Adding new linked item when file of same name exists (in the project, but not on disk) /// </summary> [Ignore] [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void AddExistingItemAndFileByNameExistsInProjectButNotOnDisk() { foreach (var projectType in ProjectTypes) { using (var solution = LinkedFiles(projectType).Generate().ToVs()) { var projectNode = solution.FindItem("LinkedFiles", "FolderWithAFile"); Assert.IsNotNull(projectNode, "projectNode"); AutomationWrapper.Select(projectNode); using (var addExistingDlg = solution.AddExistingItem()) { addExistingDlg.FileName = Path.Combine(solution.SolutionDirectory, "ExistsInProjectButNotOnDisk" + projectType.CodeExtension); addExistingDlg.AddLink(); } solution.WaitForDialog(); solution.CheckMessageBox(MessageBoxButton.Ok, "There is already a file of the same name in this folder."); } } } /// <summary> /// Adding new linked item when the file lives in the project dir but not in the directory we selected /// Add Existing Item from. We should add the file to the directory where it lives. /// </summary> [Ignore] [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void AddExistingItemAsLinkButFileExistsInProjectDirectory() { foreach (var projectType in ProjectTypes) { using (var solution = LinkedFiles(projectType).Generate().ToVs()) { var projectNode = solution.FindItem("LinkedFiles", "Fob"); Assert.IsNotNull(projectNode, "projectNode"); AutomationWrapper.Select(projectNode); using (var addExistingDlg = solution.AddExistingItem()) { addExistingDlg.FileName = Path.Combine(solution.SolutionDirectory, "LinkedFiles\\Fob\\AddExistingInProjectDirButNotInProject" + projectType.CodeExtension); addExistingDlg.AddLink(); } var addExistingInProjectDirButNotInProject = solution.WaitForItem("LinkedFiles", "Fob", "AddExistingInProjectDirButNotInProject" + projectType.CodeExtension); Assert.IsNotNull(addExistingInProjectDirButNotInProject, "addExistingInProjectDirButNotInProject"); } } } /// <summary> /// Reaming the file name in the Link attribute is ignored. /// </summary> [Ignore] [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void RenamedLinkedFile() { foreach (var projectType in ProjectTypes) { using (var solution = LinkedFiles(projectType).Generate().ToVs()) { var projectNode = solution.FindItem("LinkedFiles", "Fob", "NewNameForLinkFile" + projectType.CodeExtension); Assert.IsNull(projectNode); var renamedLinkFile = solution.FindItem("LinkedFiles", "Fob", "RenamedLinkFile" + projectType.CodeExtension); Assert.IsNotNull(renamedLinkFile, "renamedLinkFile"); } } } /// <summary> /// A link path outside of our project dir will result in the link being ignored. /// </summary> [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void BadLinkPath() { foreach (var projectType in ProjectTypes) { using (var solution = LinkedFiles(projectType).Generate().ToVs()) { var projectNode = solution.FindItem("LinkedFiles", ".."); Assert.IsNull(projectNode); projectNode = solution.FindItem("LinkedFiles", "BadLinkPathFolder"); Assert.IsNull(projectNode); } } } /// <summary> /// A rooted link path is ignored. /// </summary> [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void RootedLinkIgnored() { foreach (var projectType in ProjectTypes) { using (var solution = LinkedFiles(projectType).Generate().ToVs()) { var projectNode = solution.FindItem("LinkedFiles", "RootedLinkIgnored" + projectType.CodeExtension); Assert.IsNull(projectNode); } } } /// <summary> /// A rooted link path is ignored. /// </summary> [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void RootedIncludeIgnored() { foreach (var projectType in ProjectTypes) { using (var solution = LinkedFiles(projectType).Generate().ToVs()) { var rootedIncludeIgnored = solution.FindItem("LinkedFiles", "RootedIncludeIgnored" + projectType.CodeExtension); Assert.IsNotNull(rootedIncludeIgnored, "rootedIncludeIgnored"); } } } /// <summary> /// Test linked files with a project home set (done by save as in this test) /// https://nodejstools.codeplex.com/workitem/1511 /// </summary> [Ignore] [TestMethod, Priority(0), TestCategory("Core")] [HostType("VSTestHost")] public void TestLinkedWithProjectHome() { foreach (var projectType in ProjectTypes) { using (var solution = MultiProjectLinkedFiles(projectType).ToVs()) { var project = (solution as VisualStudioInstance).Project; // save the project to an odd location. This will result in project home being set. var newProjName = "TempFile"; try { project.SaveAs(Path.GetTempPath() + newProjName + projectType.ProjectExtension); } catch (UnauthorizedAccessException) { Assert.Inconclusive("Couldn't save the file"); } // create a temporary file and add a link to it in the project solution.FindItem(newProjName).Select(); var tempFile = Path.GetTempFileName(); using (var addExistingDlg = AddExistingItemDialog.FromDte((solution as VisualStudioInstance).App)) { addExistingDlg.FileName = tempFile; addExistingDlg.AddLink(); } // Save the project to commit that link to the project file project.Save(); // verify that the project file contains the correct text for Link var fileText = File.ReadAllText(project.FullName); var pattern = string.Format( @"<Content Include=""{0}"">\s*<Link>{1}</Link>\s*</Content>", Regex.Escape(tempFile), Regex.Escape(Path.GetFileName(tempFile))); AssertUtil.AreEqual(new Regex(pattern), fileText); } } } } }
// 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 System.Collections.Generic; using Xamarin.Forms; using Sensus.Probes.Location; namespace Sensus.UI { /// <summary> /// Allows the user to add a proximity trigger to a proximity probe. /// </summary> public class AddProximityTriggerPage : ContentPage { private IPointsOfInterestProximityProbe _proximityProbe; private string _pointOfInterestName; private string _pointOfInterestType; private double _distanceThresholdMeters; private ProximityThresholdDirection _thresholdDirection; /// <summary> /// Initializes a new instance of the <see cref="AddProximityTriggerPage"/> class. /// </summary> /// <param name="proximityProbe">Proximity probe to add trigger to.</param> public AddProximityTriggerPage(IPointsOfInterestProximityProbe proximityProbe) { _proximityProbe = proximityProbe; Title = "Add Trigger"; List<PointOfInterest> pointsOfInterest = SensusServiceHelper.Get().PointsOfInterest.Union(_proximityProbe.Protocol.PointsOfInterest).ToList(); if (pointsOfInterest.Count == 0) { Content = new Label { Text = "No points of interest defined. Please define one or more before creating triggers.", FontSize = 20 }; return; } StackLayout contentLayout = new StackLayout { Orientation = StackOrientation.Vertical, VerticalOptions = LayoutOptions.FillAndExpand }; #region point of interest Label pointOfInterestLabel = new Label { Text = "POI:", FontSize = 20 }; Picker pointOfInterestPicker = new Picker { Title = "Select POI", HorizontalOptions = LayoutOptions.FillAndExpand }; foreach (string poiDesc in pointsOfInterest.Select(poi => poi.ToString())) { pointOfInterestPicker.Items.Add(poiDesc); } pointOfInterestPicker.SelectedIndexChanged += (o, e) => { if (pointOfInterestPicker.SelectedIndex < 0) { _pointOfInterestName = _pointOfInterestType = null; } else { PointOfInterest poi = pointsOfInterest[pointOfInterestPicker.SelectedIndex]; _pointOfInterestName = poi.Name; _pointOfInterestType = poi.Type; } }; contentLayout.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { pointOfInterestLabel, pointOfInterestPicker } }); #endregion #region distance threshold Label distanceThresholdLabel = new Label { Text = "Distance Threshold (Meters):", FontSize = 20 }; Entry distanceThresholdEntry = new Entry { HorizontalOptions = LayoutOptions.FillAndExpand, Keyboard = Keyboard.Numeric }; distanceThresholdEntry.TextChanged += (o, e) => { if (!double.TryParse(distanceThresholdEntry.Text, out _distanceThresholdMeters)) { _distanceThresholdMeters = -1; } else if (_distanceThresholdMeters < GpsReceiver.Get().MinimumDistanceThreshold) { SensusServiceHelper.Get().FlashNotificationAsync("Distance threshold must be at least " + GpsReceiver.Get().MinimumDistanceThreshold + "."); } }; contentLayout.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { distanceThresholdLabel, distanceThresholdEntry } }); #endregion #region threshold direction Label thresholdDirectionLabel = new Label { Text = "Threshold Direction:", FontSize = 20 }; ProximityThresholdDirection[] thresholdDirections = new ProximityThresholdDirection[]{ ProximityThresholdDirection.Within, ProximityThresholdDirection.Outside }; Picker thresholdDirectionPicker = new Picker { Title = "Select Threshold Direction", HorizontalOptions = LayoutOptions.FillAndExpand }; foreach (ProximityThresholdDirection thresholdDirection in thresholdDirections) { thresholdDirectionPicker.Items.Add(thresholdDirection.ToString()); } thresholdDirectionPicker.SelectedIndexChanged += (o, e) => { if (thresholdDirectionPicker.SelectedIndex < 0) { _thresholdDirection = ProximityThresholdDirection.Within; } else { _thresholdDirection = thresholdDirections[thresholdDirectionPicker.SelectedIndex]; } }; contentLayout.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { thresholdDirectionLabel, thresholdDirectionPicker } }); #endregion Button okButton = new Button { Text = "OK", FontSize = 20 }; okButton.Clicked += async (o, e) => { try { _proximityProbe.Triggers.Add(new PointOfInterestProximityTrigger(_pointOfInterestName, _pointOfInterestType, _distanceThresholdMeters, _thresholdDirection)); await Navigation.PopAsync(); } catch (Exception ex) { string message = "Failed to add trigger: " + ex.Message; await SensusServiceHelper.Get().FlashNotificationAsync(message); SensusServiceHelper.Get().Logger.Log(message, LoggingLevel.Normal, GetType()); } }; contentLayout.Children.Add(okButton); Content = new ScrollView { Content = contentLayout }; } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Web.UI; using System.Web.UI.WebControls; using Adxstudio.Xrm.Globalization; using Adxstudio.Xrm.Resources; using Adxstudio.Xrm.Web.UI.WebControls; using Microsoft.Xrm.Client; using Microsoft.Xrm.Portal.Web.UI.CrmEntityFormView; using Microsoft.Xrm.Sdk; namespace Adxstudio.Xrm.Web.UI.CrmEntityFormView { /// <summary> /// Template used when rendering a Two Option field. /// </summary> public class BooleanControlTemplate : CellTemplate, ICustomFieldControlTemplate { /// <summary> /// BooleanControlTemplate class initialization. /// </summary> /// <param name="field"></param> /// <param name="metadata"></param> /// <param name="validationGroup"></param> /// <param name="bindings"></param> public BooleanControlTemplate(CrmEntityFormViewField field, FormXmlCellMetadata metadata, string validationGroup, IDictionary<string, CellBinding> bindings) : base(metadata, validationGroup, bindings) { Field = field; } public override string CssClass { get { if (Metadata != null) { if (Metadata.ClassID == DropDownClassID) { return "boolean-dropdown"; } if (Metadata.ClassID == RadioButtonClassID) { return "boolean-radio"; } } return "checkbox"; } } /// <summary> /// Form field. /// </summary> public CrmEntityFormViewField Field { get; private set; } //NOTE: this hack is neccessary until we know some other way of determining the display option for boolean fields. Class ID in formXml determines control type /// <summary> /// Class ID used in CRM to specify format type checkbox. /// </summary> public Guid CheckBoxClassID { get { return new Guid("B0C6723A-8503-4fd7-BB28-C8A06AC933C2"); } } /// <summary> /// Class ID used in CRM to specify format type dropdown. /// </summary> public Guid DropDownClassID { get { return new Guid("3EF39988-22BB-4f0b-BBBE-64B5A3748AEE"); } } /// <summary> /// Class ID used in CRM to specify format type radio. /// </summary> public Guid RadioButtonClassID { get { return new Guid("67FAC785-CD58-4f9f-ABB3-4B7DDC6ED5ED"); } } private string ValidationText { get { return Metadata.ValidationText; } } private ValidatorDisplay ValidatorDisplay { get { return string.IsNullOrWhiteSpace(ValidationText) ? ValidatorDisplay.None : ValidatorDisplay.Dynamic; } } protected override bool LabelIsAssociated { get { return Metadata.ClassID != RadioButtonClassID; } } protected override void InstantiateControlIn(Control container) { //NOTE: this hack is neccessary until we know some other way of determining the display option for boolean fields. Class ID in formXml determines control type //get classid of control if (Metadata.ClassID == CheckBoxClassID) { InstantiateCheckboxControlIn(container); return; } ListControl listControl; if (Metadata.ClassID == RadioButtonClassID) { listControl = new RadioButtonList { RepeatLayout = RepeatLayout.Flow, RepeatDirection = RepeatDirection.Horizontal, CssClass = string.Join(" ", CssClass, Metadata.CssClass) }; } else if (Metadata.ClassID == DropDownClassID) { listControl = new DropDownList { CssClass = string.Join(" ", "form-control", CssClass, Metadata.CssClass) }; } else { throw new ArgumentNullException(Metadata.ClassID.ToString(), "Class ID doesn't match any known Boolean control."); } listControl.ID = ControlID; listControl.ToolTip = Metadata.ToolTip; listControl.Attributes.Add("onchange", "setIsDirty(this.id);"); if (Metadata.IsRequired || Metadata.WebFormForceFieldIsRequired) { if (listControl is DropDownList) { listControl.Attributes.Add("required", string.Empty); } else { listControl.Attributes.Add("data-required", "true"); } } InstantiateListControlIn(container, listControl); } protected override void InstantiateValidatorsIn(Control container) { if ((Metadata.ClassID == CheckBoxClassID) && (Metadata.IsRequired || Metadata.WebFormForceFieldIsRequired)) { container.Controls.Add(new CheckboxValidator { ID = string.Format("RequiredFieldValidator{0}", ControlID), ControlToValidate = ControlID, ValidationGroup = ValidationGroup, Display = ValidatorDisplay, ErrorMessage = ValidationSummaryMarkup((string.IsNullOrWhiteSpace(Metadata.RequiredFieldValidationErrorMessage) ? (Metadata.Messages == null || !Metadata.Messages.ContainsKey("boolean")) ? ResourceManager.GetString("Check_The_Box_Labeled").FormatWith(Metadata.Label) : Metadata.Messages["boolean"].FormatWith(Metadata.Label) : Metadata.RequiredFieldValidationErrorMessage)), Text = ValidationText, }); } else if (Metadata.IsRequired || Metadata.WebFormForceFieldIsRequired) { container.Controls.Add(new RequiredFieldValidator { ID = string.Format("RequiredFieldValidator{0}", ControlID), ControlToValidate = ControlID, ValidationGroup = ValidationGroup, Display = ValidatorDisplay, ErrorMessage = ValidationSummaryMarkup((string.IsNullOrWhiteSpace(Metadata.RequiredFieldValidationErrorMessage) ? (Metadata.Messages == null || !Metadata.Messages.ContainsKey("required")) ? ResourceManager.GetString("Required_Field_Error").FormatWith(Metadata.Label) : Metadata.Messages["required"].FormatWith(Metadata.Label) : Metadata.RequiredFieldValidationErrorMessage)), Text = ValidationText, }); } this.InstantiateCustomValidatorsIn(container); } private void AddSpecialBindingAndHiddenFieldsToPersistDisabledCheckBox(Control container, CheckBox checkBox) { checkBox.InputAttributes["class"] = "{0} readonly".FormatWith(CssClass); checkBox.InputAttributes["disabled"] = "disabled"; checkBox.InputAttributes["aria-disabled"] = "true"; var hiddenValue = new HiddenField { ID = "{0}_Value".FormatWith(ControlID), Value = checkBox.Checked.ToString(CultureInfo.InvariantCulture) }; container.Controls.Add(hiddenValue); RegisterClientSideDependencies(container); Bindings[Metadata.DataFieldName] = new CellBinding { Get = () => { bool value; return bool.TryParse(hiddenValue.Value, out value) ? new bool?(value) : null; }, Set = obj => { var value = Convert.ToBoolean(obj); checkBox.Checked = value; hiddenValue.Value = value.ToString(CultureInfo.InvariantCulture); } }; } private void AddSpecialBindingAndHiddenFieldsToPersistDisabledRadioButtons(Control container, ListControl radioButtonList) { radioButtonList.CssClass = "{0} readonly".FormatWith(CssClass); radioButtonList.Enabled = false; var hiddenValue = new HiddenField { ID = "{0}_Value".FormatWith(ControlID), Value = radioButtonList.SelectedValue }; container.Controls.Add(hiddenValue); RegisterClientSideDependencies(container); Bindings[Metadata.DataFieldName] = new CellBinding { Get = () => { int value; return int.TryParse(hiddenValue.Value, out value) ? (object)(value == 1) : null; }, Set = obj => { var value = new OptionSetValue(Convert.ToInt32(obj)).Value; radioButtonList.SelectedValue = "{0}".FormatWith(value); hiddenValue.Value = radioButtonList.SelectedValue; } }; } private void AddSpecialBindingAndHiddenFieldsToPersistDisabledSelect(Control container, ListControl dropDown) { dropDown.CssClass = string.Join(" ", "readonly", dropDown.CssClass); dropDown.Attributes["disabled"] = "disabled"; var hiddenValue = new HiddenField { ID = "{0}_Value".FormatWith(ControlID), Value = dropDown.SelectedValue }; container.Controls.Add(hiddenValue); var hiddenSelectedIndex = new HiddenField { ID = "{0}_SelectedIndex".FormatWith(ControlID), Value = dropDown.SelectedIndex.ToString(CultureInfo.InvariantCulture) }; container.Controls.Add(hiddenSelectedIndex); RegisterClientSideDependencies(container); Bindings[Metadata.DataFieldName] = new CellBinding { Get = () => { int value; return int.TryParse(hiddenValue.Value, out value) ? (object)(value == 1) : null; }, Set = obj => { var value = new OptionSetValue(Convert.ToInt32(obj)).Value; dropDown.SelectedValue = "{0}".FormatWith(value); hiddenValue.Value = dropDown.SelectedValue; hiddenSelectedIndex.Value = dropDown.SelectedIndex.ToString(CultureInfo.InvariantCulture); } }; } private void InstantiateCheckboxControlIn(Control container) { var checkbox = new CheckBox { ID = ControlID, CssClass = string.Join(" ", CssClass, Metadata.CssClass), ToolTip = Metadata.ToolTip }; checkbox.Attributes.Add("onclick", "setIsDirty(this.id);"); container.Controls.Add(checkbox); if (!container.Page.IsPostBack) { checkbox.Checked = Convert.ToBoolean(Metadata.DefaultValue); } if (Metadata.ReadOnly) { AddSpecialBindingAndHiddenFieldsToPersistDisabledCheckBox(container, checkbox); } else { Bindings[Metadata.DataFieldName] = new CellBinding { Get = () => checkbox.Checked, Set = obj => { checkbox.Checked = Convert.ToBoolean(obj); } }; } } private void InstantiateListControlIn(Control container, ListControl listControl) { container.Controls.Add(listControl); PopulateListControlIfFirstLoad(listControl); if (Metadata.ReadOnly) { if (listControl is DropDownList) { AddSpecialBindingAndHiddenFieldsToPersistDisabledSelect(container, listControl); } else if (listControl is RadioButtonList) { AddSpecialBindingAndHiddenFieldsToPersistDisabledRadioButtons(container, listControl); } } else { Bindings[Metadata.DataFieldName] = new CellBinding { Get = () => { int value; return int.TryParse(listControl.SelectedValue, out value) ? (object)(value == 1) : null; }, Set = obj => { var value = new OptionSetValue(Convert.ToInt32(obj)).Value; listControl.SelectedValue = "{0}".FormatWith(value); } }; } } private void PopulateListControlIfFirstLoad(ListControl listControl) { if (listControl.Items.Count > 0) { return; } if (Metadata.IgnoreDefaultValue && listControl is DropDownList) { var empty = new ListItem(string.Empty, string.Empty); empty.Attributes["label"] = " "; listControl.Items.Add(empty); } if (Metadata.BooleanOptionSetMetadata.FalseOption.Value != null) { var label = Metadata.BooleanOptionSetMetadata.FalseOption.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == Metadata.LanguageCode); listControl.Items.Add(new ListItem { Value = Metadata.BooleanOptionSetMetadata.FalseOption.Value.Value.ToString(CultureInfo.InvariantCulture), Text = (listControl is RadioButtonList ? "<span class='sr-only'>" + Metadata.Label + " </span>" : string.Empty) + (label == null ? Metadata.BooleanOptionSetMetadata.FalseOption.Label.GetLocalizedLabelString() : label.Label) }); } else { listControl.Items.Add(new ListItem { Value = "0", Text = "False", }); } if (Metadata.BooleanOptionSetMetadata.TrueOption.Value != null) { var label = Metadata.BooleanOptionSetMetadata.TrueOption.Label.LocalizedLabels.FirstOrDefault(l => l.LanguageCode == Metadata.LanguageCode); listControl.Items.Add(new ListItem { Value = Metadata.BooleanOptionSetMetadata.TrueOption.Value.Value.ToString(CultureInfo.InvariantCulture), Text = (listControl is RadioButtonList ? "<span class='sr-only'>" + Metadata.Label + " </span>" : string.Empty) + (label == null ? Metadata.BooleanOptionSetMetadata.TrueOption.Label.GetLocalizedLabelString() : label.Label) }); } else { listControl.Items.Add(new ListItem { Value = "1", Text = "True", }); } if (Metadata.IgnoreDefaultValue || Metadata.DefaultValue == null) { return; } if (Convert.ToBoolean(Metadata.DefaultValue)) { if (Metadata.BooleanOptionSetMetadata.TrueOption.Value.HasValue) { listControl.SelectedValue = Metadata.BooleanOptionSetMetadata.TrueOption.Value.Value.ToString(CultureInfo.InvariantCulture); } } else { if (Metadata.BooleanOptionSetMetadata.FalseOption.Value.HasValue) { listControl.SelectedValue = Metadata.BooleanOptionSetMetadata.FalseOption.Value.Value.ToString(CultureInfo.InvariantCulture); } } } } }
using System; using System.Xml; using System.Data; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using WeifenLuo.WinFormsUI.Docking; using MyMeta; namespace MyGeneration { /// <summary> /// Summary description for DbTargetMappings. /// </summary> public class DbTargetMappings : DockContent, IMyGenContent { private IMyGenerationMDI mdi; GridLayoutHelper gridLayoutHelper; private System.ComponentModel.IContainer components; private System.Windows.Forms.ComboBox cboxDbTarget; private System.Windows.Forms.DataGrid XmlEditor; private System.Windows.Forms.ImageList imageList1; private System.Windows.Forms.ToolBar toolBar1; private System.Windows.Forms.ToolBarButton toolBarButton_Save; private System.Windows.Forms.ToolBarButton toolBarButton_New; private System.Windows.Forms.ToolBarButton toolBarButton1; private System.Windows.Forms.ToolBarButton toolBarButton_Delete; private System.Windows.Forms.DataGridTextBoxColumn col_From; private System.Windows.Forms.DataGridTextBoxColumn col_To; private System.Windows.Forms.DataGridTableStyle MyXmlStyle; public DbTargetMappings(IMyGenerationMDI mdi) { InitializeComponent(); this.mdi = mdi; this.ShowHint = DockState.DockRight; } protected override string GetPersistString() { return this.GetType().FullName; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DbTargetMappings)); this.XmlEditor = new System.Windows.Forms.DataGrid(); this.MyXmlStyle = new System.Windows.Forms.DataGridTableStyle(); this.col_From = new System.Windows.Forms.DataGridTextBoxColumn(); this.col_To = new System.Windows.Forms.DataGridTextBoxColumn(); this.cboxDbTarget = new System.Windows.Forms.ComboBox(); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.toolBar1 = new System.Windows.Forms.ToolBar(); this.toolBarButton_Save = new System.Windows.Forms.ToolBarButton(); this.toolBarButton_New = new System.Windows.Forms.ToolBarButton(); this.toolBarButton1 = new System.Windows.Forms.ToolBarButton(); this.toolBarButton_Delete = new System.Windows.Forms.ToolBarButton(); ((System.ComponentModel.ISupportInitialize)(this.XmlEditor)).BeginInit(); this.SuspendLayout(); // // XmlEditor // this.XmlEditor.AlternatingBackColor = System.Drawing.Color.Moccasin; this.XmlEditor.BackColor = System.Drawing.Color.LightGray; this.XmlEditor.BackgroundColor = System.Drawing.Color.LightGray; this.XmlEditor.CaptionVisible = false; this.XmlEditor.DataMember = ""; this.XmlEditor.Dock = System.Windows.Forms.DockStyle.Fill; this.XmlEditor.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold); this.XmlEditor.GridLineColor = System.Drawing.Color.BurlyWood; this.XmlEditor.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.XmlEditor.Location = new System.Drawing.Point(2, 49); this.XmlEditor.Name = "XmlEditor"; this.XmlEditor.Size = new System.Drawing.Size(476, 951); this.XmlEditor.TabIndex = 7; this.XmlEditor.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] { this.MyXmlStyle}); // // MyXmlStyle // this.MyXmlStyle.AlternatingBackColor = System.Drawing.Color.LightGray; this.MyXmlStyle.BackColor = System.Drawing.Color.LightSteelBlue; this.MyXmlStyle.DataGrid = this.XmlEditor; this.MyXmlStyle.GridColumnStyles.AddRange(new System.Windows.Forms.DataGridColumnStyle[] { this.col_From, this.col_To}); this.MyXmlStyle.GridLineColor = System.Drawing.Color.DarkGray; this.MyXmlStyle.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.MyXmlStyle.MappingName = "DbTarget"; // // col_From // this.col_From.Format = ""; this.col_From.FormatInfo = null; this.col_From.HeaderText = "From"; this.col_From.MappingName = "From"; this.col_From.NullText = ""; this.col_From.Width = 75; // // col_To // this.col_To.Format = ""; this.col_To.FormatInfo = null; this.col_To.HeaderText = "To"; this.col_To.MappingName = "To"; this.col_To.NullText = ""; this.col_To.Width = 75; // // cboxDbTarget // this.cboxDbTarget.Dock = System.Windows.Forms.DockStyle.Top; this.cboxDbTarget.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboxDbTarget.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cboxDbTarget.Location = new System.Drawing.Point(2, 2); this.cboxDbTarget.Name = "cboxDbTarget"; this.cboxDbTarget.Size = new System.Drawing.Size(476, 21); this.cboxDbTarget.TabIndex = 12; this.cboxDbTarget.SelectionChangeCommitted += new System.EventHandler(this.cboxLanguage_SelectionChangeCommitted); // // imageList1 // this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Magenta; this.imageList1.Images.SetKeyName(0, ""); this.imageList1.Images.SetKeyName(1, ""); this.imageList1.Images.SetKeyName(2, ""); // // toolBar1 // this.toolBar1.Appearance = System.Windows.Forms.ToolBarAppearance.Flat; this.toolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] { this.toolBarButton_Save, this.toolBarButton_New, this.toolBarButton1, this.toolBarButton_Delete}); this.toolBar1.Divider = false; this.toolBar1.DropDownArrows = true; this.toolBar1.ImageList = this.imageList1; this.toolBar1.Location = new System.Drawing.Point(2, 23); this.toolBar1.Name = "toolBar1"; this.toolBar1.ShowToolTips = true; this.toolBar1.Size = new System.Drawing.Size(476, 26); this.toolBar1.TabIndex = 14; this.toolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick); // // toolBarButton_Save // this.toolBarButton_Save.ImageIndex = 0; this.toolBarButton_Save.Name = "toolBarButton_Save"; this.toolBarButton_Save.Tag = "save"; this.toolBarButton_Save.ToolTipText = "Save DbTarget Mappings"; // // toolBarButton_New // this.toolBarButton_New.ImageIndex = 2; this.toolBarButton_New.Name = "toolBarButton_New"; this.toolBarButton_New.Tag = "new"; this.toolBarButton_New.ToolTipText = "Create New DbTarget Mapping"; // // toolBarButton1 // this.toolBarButton1.Name = "toolBarButton1"; this.toolBarButton1.Style = System.Windows.Forms.ToolBarButtonStyle.Separator; // // toolBarButton_Delete // this.toolBarButton_Delete.ImageIndex = 1; this.toolBarButton_Delete.Name = "toolBarButton_Delete"; this.toolBarButton_Delete.Tag = "delete"; this.toolBarButton_Delete.ToolTipText = "Delete DbTarget Mappings"; // // DbTargetMappings // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.AutoScroll = true; this.ClientSize = new System.Drawing.Size(480, 1002); this.Controls.Add(this.XmlEditor); this.Controls.Add(this.toolBar1); this.Controls.Add(this.cboxDbTarget); this.HideOnClose = true; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "DbTargetMappings"; this.Padding = new System.Windows.Forms.Padding(2); this.TabText = "DbTarget Mappings"; this.Text = "DbTarget Mappings"; this.Load += new System.EventHandler(this.DbTargetMappings_Load); ((System.ComponentModel.ISupportInitialize)(this.XmlEditor)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion public void DefaultSettingsChanged(DefaultSettings settings) { } public bool CanClose(bool allowPrevent) { return PromptForSave(allowPrevent); } private bool PromptForSave(bool allowPrevent) { bool canClose = true; if(this.isDirty) { DialogResult result; if(allowPrevent) { result = MessageBox.Show("The DbTarget Mappings have been Modified, Do you wish to save them?", "DbTarget Mappings", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); } else { result = MessageBox.Show("The DbTarget Mappings have been Modified, Do you wish to save them?", "DbTarget Mappings", MessageBoxButtons.YesNo, MessageBoxIcon.Question); } switch(result) { case DialogResult.Yes: { DefaultSettings settings = DefaultSettings.Instance; xml.Save(settings.DbTargetMappingFile); MarkAsDirty(false); } break; case DialogResult.Cancel: canClose = false; break; } } return canClose; } private void MarkAsDirty(bool isDirty) { this.isDirty = isDirty; this.toolBarButton_Save.Visible = isDirty; } public new void Show(DockPanel dockManager) { DefaultSettings settings = DefaultSettings.Instance; if (!System.IO.File.Exists(settings.DbTargetMappingFile)) { MessageBox.Show(this, "Database Target Mapping File does not exist at: " + settings.DbTargetMappingFile + "\r\nPlease fix this in DefaultSettings."); } else { base.Show(dockManager); } } private void DbTargetMappings_Load(object sender, System.EventArgs e) { this.col_From.TextBox.BorderStyle = BorderStyle.None; this.col_To.TextBox.BorderStyle = BorderStyle.None; this.col_From.TextBox.Move += new System.EventHandler(this.ColorTextBox); this.col_To.TextBox.Move += new System.EventHandler(this.ColorTextBox); DefaultSettings settings = DefaultSettings.Instance; this.dbDriver = settings.DbDriver; this.xml.Load(settings.DbTargetMappingFile); PopulateComboBox(settings); PopulateGrid(this.dbDriver); MarkAsDirty(false); gridLayoutHelper = new GridLayoutHelper(XmlEditor, MyXmlStyle, new decimal[] { 0.50M, 0.50M }, new int[] { 100, 100 }); } private void cboxLanguage_SelectionChangeCommitted(object sender, System.EventArgs e) { DefaultSettings settings = DefaultSettings.Instance; PopulateGrid(this.dbDriver); } private void PopulateComboBox(DefaultSettings settings) { this.cboxDbTarget.Items.Clear(); // Populate the ComboBox dbRoot myMeta = new dbRoot(); myMeta.DbTargetMappingFileName = settings.DbTargetMappingFile; myMeta.DbTarget = settings.DbTarget; string[] targets = myMeta.GetDbTargetMappings(settings.DbDriver); if(null != targets) { for(int i = 0; i < targets.Length; i++) { this.cboxDbTarget.Items.Add(targets[i]); } this.cboxDbTarget.SelectedItem = myMeta.DbTarget; if(this.cboxDbTarget.SelectedIndex == -1) { // The default doesn't exist, set it to the first in the list this.cboxDbTarget.SelectedIndex = 0; } } } private void PopulateGrid(string dbDriver) { string target; if(this.cboxDbTarget.SelectedItem != null) { XmlEditor.Enabled = true; target = this.cboxDbTarget.SelectedItem as String; } else { XmlEditor.Enabled = false; target = ""; } this.Text = "DbTarget Mappings for " + dbDriver; langNode = this.xml.SelectSingleNode(@"//DbTargets/DbTarget[@From='" + dbDriver + "' and @To='" + target + "']"); DataSet ds = new DataSet(); DataTable dt = new DataTable("this"); dt.Columns.Add("this", Type.GetType("System.Object")); ds.Tables.Add(dt); dt.Rows.Add(new object[] { this }); dt = new DataTable("DbTarget"); DataColumn from = dt.Columns.Add("From", Type.GetType("System.String")); from.AllowDBNull = false; DataColumn to = dt.Columns.Add("To", Type.GetType("System.String")); to.AllowDBNull = false; ds.Tables.Add(dt); UniqueConstraint pk = new UniqueConstraint(from, false); dt.Constraints.Add(pk); ds.EnforceConstraints = true; if(null != langNode) { foreach(XmlNode mappingpNode in langNode.ChildNodes) { XmlAttributeCollection attrs = mappingpNode.Attributes; string sFrom = attrs["From"].Value; string sTo = attrs["To"].Value; dt.Rows.Add( new object[] { sFrom, sTo } ); } dt.AcceptChanges(); } XmlEditor.DataSource = dt; dt.RowChanged += new DataRowChangeEventHandler(GridRowChanged); dt.RowDeleting += new DataRowChangeEventHandler(GridRowDeleting); dt.RowDeleted += new DataRowChangeEventHandler(GridRowDeleted); } private static void GridRowChanged(object sender, DataRowChangeEventArgs e) { DbTargetMappings This = e.Row.Table.DataSet.Tables["this"].Rows[0]["this"] as DbTargetMappings; This.MarkAsDirty(true); This.GridRowChangedEvent(sender, e); } private static void GridRowDeleting(object sender, DataRowChangeEventArgs e) { DbTargetMappings This = e.Row.Table.DataSet.Tables["this"].Rows[0]["this"] as DbTargetMappings; This.MarkAsDirty(true); This.GridRowDeletingEvent(sender, e); } private static void GridRowDeleted(object sender, DataRowChangeEventArgs e) { DbTargetMappings This = e.Row.Table.DataSet.Tables["this"].Rows[0]["this"] as DbTargetMappings; This.MarkAsDirty(true); This.GridRowDeletedEvent(sender, e); } private void GridRowChangedEvent(object sender, DataRowChangeEventArgs e) { try { string sFrom = e.Row["From"] as string; string sTo = e.Row["To"] as string; string xPath; XmlNode typeNode; switch(e.Row.RowState) { case DataRowState.Added: { typeNode = langNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Type", null); langNode.AppendChild(typeNode); XmlAttribute attr; attr = langNode.OwnerDocument.CreateAttribute("From"); attr.Value = sFrom; typeNode.Attributes.Append(attr); attr = langNode.OwnerDocument.CreateAttribute("To"); attr.Value = sTo; typeNode.Attributes.Append(attr); } break; case DataRowState.Modified: { xPath = @"./Type[@From='" + sFrom + "']"; typeNode = langNode.SelectSingleNode(xPath); typeNode.Attributes["To"].Value = sTo; } break; } } catch{} } private void GridRowDeletingEvent(object sender, DataRowChangeEventArgs e) { string xPath = @"./Type[@From='" + e.Row["From"] + "' and @To='" + e.Row["To"] + "']"; XmlNode node = langNode.SelectSingleNode(xPath); if(node != null) { node.ParentNode.RemoveChild(node); } } private void GridRowDeletedEvent(object sender, DataRowChangeEventArgs e) { DataTable dt = e.Row.Table; dt.RowChanged -= new DataRowChangeEventHandler(GridRowChanged); dt.RowDeleting -= new DataRowChangeEventHandler(GridRowDeleting); dt.RowDeleted -= new DataRowChangeEventHandler(GridRowDeleted); dt.AcceptChanges(); dt.RowChanged += new DataRowChangeEventHandler(GridRowChanged); dt.RowDeleting += new DataRowChangeEventHandler(GridRowDeleting); dt.RowDeleted += new DataRowChangeEventHandler(GridRowDeleted); } private void ColorTextBox(object sender, System.EventArgs e) { TextBox txtBox = (TextBox)sender; // Bail if we're in la la land Size size = txtBox.Size; if(size.Width == 0 && size.Height == 0) { return; } int row = this.XmlEditor.CurrentCell.RowNumber; int col = this.XmlEditor.CurrentCell.ColumnNumber; if(isEven(row)) txtBox.BackColor = Color.LightSteelBlue; else txtBox.BackColor = Color.LightGray; if(col == 0) { if(txtBox.Text == string.Empty) txtBox.ReadOnly = false; else txtBox.ReadOnly = true; } } private bool isEven(int x) { return (x & 1) == 0; } private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e) { DefaultSettings settings = DefaultSettings.Instance; switch(e.Button.Tag as string) { case "save": xml.Save(settings.DbTargetMappingFile); MarkAsDirty(false); break; case "new": { int count = this.cboxDbTarget.Items.Count; string[] dbTargets = new string[count]; for(int i = 0; i < this.cboxDbTarget.Items.Count; i++) { dbTargets[i] = this.cboxDbTarget.Items[i] as string; } AddDbTargetMappingDialog dialog = new AddDbTargetMappingDialog(dbTargets, this.dbDriver); if(dialog.ShowDialog() == DialogResult.OK) { if(dialog.BasedUpon != string.Empty) { string xPath = @"//DbTargets/DbTarget[@From='" + this.dbDriver + "' and @To='" + dialog.BasedUpon + "']"; XmlNode node = xml.SelectSingleNode(xPath); XmlNode newNode = node.CloneNode(true); newNode.Attributes["To"].Value = dialog.NewDbTarget; node.ParentNode.AppendChild(newNode); } else { XmlNode parentNode = xml.SelectSingleNode(@"//DbTargets"); XmlAttribute attr; // Language Node langNode = xml.CreateNode(XmlNodeType.Element, "DbTarget", null); parentNode.AppendChild(langNode); attr = xml.CreateAttribute("From"); attr.Value = settings.DbDriver; langNode.Attributes.Append(attr); attr = xml.CreateAttribute("To"); attr.Value = dialog.NewDbTarget; langNode.Attributes.Append(attr); } this.cboxDbTarget.Items.Add(dialog.NewDbTarget); this.cboxDbTarget.SelectedItem = dialog.NewDbTarget; PopulateGrid(this.dbDriver); MarkAsDirty(true); } } break; case "delete": if(this.cboxDbTarget.SelectedItem != null) { string target = this.cboxDbTarget.SelectedItem as String; DialogResult result = MessageBox.Show("Delete '" + target + "' Mappings. Are you sure?", "Delete DbTarget Mappings", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning); if(result == DialogResult.Yes) { string xPath = @"//DbTargets/DbTarget[@From='" + this.dbDriver + "' and @To='" + target + "']"; XmlNode node = xml.SelectSingleNode(xPath); node.ParentNode.RemoveChild(node); this.cboxDbTarget.Items.Remove(target); if(this.cboxDbTarget.Items.Count > 0) { this.cboxDbTarget.SelectedItem = this.cboxDbTarget.SelectedIndex = 0; } PopulateGrid(this.dbDriver); MarkAsDirty(true); } } break; } } private XmlDocument xml = new XmlDocument(); private XmlNode langNode = null; private string dbDriver = ""; private bool isDirty = false; #region IMyGenContent Members public ToolStrip ToolStrip { get { return null; } } public void ProcessAlert(IMyGenContent sender, string command, params object[] args) { if (command.Equals("UpdateDefaultSettings", StringComparison.CurrentCultureIgnoreCase)) { PromptForSave(false); DefaultSettings settings = DefaultSettings.Instance; this.dbDriver = settings.DbDriver; PopulateComboBox(settings); PopulateGrid(this.dbDriver); MarkAsDirty(false); } } public DockContent DockContent { get { return this; } } #endregion } }
// 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 gcdv = Google.Cloud.DataLabeling.V1Beta1; using sys = System; namespace Google.Cloud.DataLabeling.V1Beta1 { /// <summary>Resource name for the <c>Evaluation</c> resource.</summary> public sealed partial class EvaluationName : gax::IResourceName, sys::IEquatable<EvaluationName> { /// <summary>The possible contents of <see cref="EvaluationName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/datasets/{dataset}/evaluations/{evaluation}</c>. /// </summary> ProjectDatasetEvaluation = 1, } private static gax::PathTemplate s_projectDatasetEvaluation = new gax::PathTemplate("projects/{project}/datasets/{dataset}/evaluations/{evaluation}"); /// <summary>Creates a <see cref="EvaluationName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="EvaluationName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static EvaluationName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new EvaluationName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="EvaluationName"/> with the pattern /// <c>projects/{project}/datasets/{dataset}/evaluations/{evaluation}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="evaluationId">The <c>Evaluation</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="EvaluationName"/> constructed from the provided ids.</returns> public static EvaluationName FromProjectDatasetEvaluation(string projectId, string datasetId, string evaluationId) => new EvaluationName(ResourceNameType.ProjectDatasetEvaluation, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), datasetId: gax::GaxPreconditions.CheckNotNullOrEmpty(datasetId, nameof(datasetId)), evaluationId: gax::GaxPreconditions.CheckNotNullOrEmpty(evaluationId, nameof(evaluationId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="EvaluationName"/> with pattern /// <c>projects/{project}/datasets/{dataset}/evaluations/{evaluation}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="evaluationId">The <c>Evaluation</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="EvaluationName"/> with pattern /// <c>projects/{project}/datasets/{dataset}/evaluations/{evaluation}</c>. /// </returns> public static string Format(string projectId, string datasetId, string evaluationId) => FormatProjectDatasetEvaluation(projectId, datasetId, evaluationId); /// <summary> /// Formats the IDs into the string representation of this <see cref="EvaluationName"/> with pattern /// <c>projects/{project}/datasets/{dataset}/evaluations/{evaluation}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="evaluationId">The <c>Evaluation</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="EvaluationName"/> with pattern /// <c>projects/{project}/datasets/{dataset}/evaluations/{evaluation}</c>. /// </returns> public static string FormatProjectDatasetEvaluation(string projectId, string datasetId, string evaluationId) => s_projectDatasetEvaluation.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(datasetId, nameof(datasetId)), gax::GaxPreconditions.CheckNotNullOrEmpty(evaluationId, nameof(evaluationId))); /// <summary>Parses the given resource name string into a new <see cref="EvaluationName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/datasets/{dataset}/evaluations/{evaluation}</c></description> /// </item> /// </list> /// </remarks> /// <param name="evaluationName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="EvaluationName"/> if successful.</returns> public static EvaluationName Parse(string evaluationName) => Parse(evaluationName, false); /// <summary> /// Parses the given resource name string into a new <see cref="EvaluationName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/datasets/{dataset}/evaluations/{evaluation}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="evaluationName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="EvaluationName"/> if successful.</returns> public static EvaluationName Parse(string evaluationName, bool allowUnparsed) => TryParse(evaluationName, allowUnparsed, out EvaluationName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="EvaluationName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/datasets/{dataset}/evaluations/{evaluation}</c></description> /// </item> /// </list> /// </remarks> /// <param name="evaluationName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="EvaluationName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string evaluationName, out EvaluationName result) => TryParse(evaluationName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="EvaluationName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/datasets/{dataset}/evaluations/{evaluation}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="evaluationName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="EvaluationName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string evaluationName, bool allowUnparsed, out EvaluationName result) { gax::GaxPreconditions.CheckNotNull(evaluationName, nameof(evaluationName)); gax::TemplatedResourceName resourceName; if (s_projectDatasetEvaluation.TryParseName(evaluationName, out resourceName)) { result = FromProjectDatasetEvaluation(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(evaluationName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private EvaluationName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string datasetId = null, string evaluationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; DatasetId = datasetId; EvaluationId = evaluationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="EvaluationName"/> class from the component parts of pattern /// <c>projects/{project}/datasets/{dataset}/evaluations/{evaluation}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="evaluationId">The <c>Evaluation</c> ID. Must not be <c>null</c> or empty.</param> public EvaluationName(string projectId, string datasetId, string evaluationId) : this(ResourceNameType.ProjectDatasetEvaluation, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), datasetId: gax::GaxPreconditions.CheckNotNullOrEmpty(datasetId, nameof(datasetId)), evaluationId: gax::GaxPreconditions.CheckNotNullOrEmpty(evaluationId, nameof(evaluationId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Dataset</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string DatasetId { get; } /// <summary> /// The <c>Evaluation</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string EvaluationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectDatasetEvaluation: return s_projectDatasetEvaluation.Expand(ProjectId, DatasetId, EvaluationId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as EvaluationName); /// <inheritdoc/> public bool Equals(EvaluationName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(EvaluationName a, EvaluationName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(EvaluationName a, EvaluationName b) => !(a == b); } public partial class Evaluation { /// <summary> /// <see cref="gcdv::EvaluationName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::EvaluationName EvaluationName { get => string.IsNullOrEmpty(Name) ? null : gcdv::EvaluationName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
/* * Copyright (C) 2012, 2013 OUYA, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using UnityEngine; using Object = UnityEngine.Object; using Random = UnityEngine.Random; public class OuyaShowMeshPerformance : MonoBehaviour, OuyaSDK.IPauseListener, OuyaSDK.IResumeListener, OuyaSDK.IMenuButtonUpListener, OuyaSDK.IMenuAppearingListener { private DateTime m_timerChange = DateTime.MinValue; public UILabel RendererLabel = null; public UILabel PolysLabel = null; private List<MeshFilter> m_items = new List<MeshFilter>(); public Material SharedMaterial = null; public MeshFilter PrefabCube = null; public List<Action> m_deferList = new List<Action>(); private void Awake() { OuyaSDK.registerMenuButtonUpListener(this); OuyaSDK.registerMenuAppearingListener(this); OuyaSDK.registerPauseListener(this); OuyaSDK.registerResumeListener(this); } private void OnDestroy() { OuyaSDK.unregisterMenuButtonUpListener(this); OuyaSDK.unregisterMenuAppearingListener(this); OuyaSDK.unregisterPauseListener(this); OuyaSDK.unregisterResumeListener(this); } private void Start() { Input.ResetInputAxes(); } public void OuyaMenuButtonUp() { Debug.Log(System.Reflection.MethodBase.GetCurrentMethod().ToString()); } public void OuyaMenuAppearing() { Debug.Log(System.Reflection.MethodBase.GetCurrentMethod().ToString()); } public void OuyaOnPause() { Debug.Log(System.Reflection.MethodBase.GetCurrentMethod().ToString()); } public void OuyaOnResume() { Debug.Log(System.Reflection.MethodBase.GetCurrentMethod().ToString()); } #region Presentation private void OnGUI() { #if UNITY_EDITOR if (GUILayout.Button("DPAD LEFT", GUILayout.MinHeight(40))) { DecreaseGeometry(1f); } if (GUILayout.Button("DPAD RIGHT", GUILayout.MinHeight(40))) { IncreaseGeometry(1f); } if (GUILayout.Button("DPAD UP", GUILayout.MinHeight(40))) { CombineGeometry(); } if (GUILayout.Button("O BUTTON", GUILayout.MinHeight(40))) { IncreaseGeometry(0.1f); } if (GUILayout.Button("A BUTTON", GUILayout.MinHeight(40))) { DecreaseGeometry(0.1f); } #endif } void Update() { if (m_deferList.Count > 0) { m_deferList[0].Invoke(); m_deferList.RemoveAt(0); } } private void FixedUpdate() { if (RendererLabel) { RendererLabel.text = m_items.Count.ToString(); } if (PolysLabel) { int count = 0; foreach (MeshFilter mf in m_items) { if (mf.mesh) { count += mf.mesh.vertexCount; } } PolysLabel.text = count.ToString(); } if (m_timerChange < DateTime.Now) { m_timerChange = DateTime.Now + TimeSpan.FromMilliseconds(200); if (OuyaExampleCommon.GetButton(OuyaSDK.KeyEnum.BUTTON_DPAD_LEFT, OuyaSDK.OuyaPlayer.player1)) { DecreaseGeometry(1f); } if (OuyaExampleCommon.GetButton(OuyaSDK.KeyEnum.BUTTON_DPAD_RIGHT, OuyaSDK.OuyaPlayer.player1)) { IncreaseGeometry(1f); } if (OuyaExampleCommon.GetButton(OuyaSDK.KeyEnum.BUTTON_DPAD_UP, OuyaSDK.OuyaPlayer.player1)) { CombineGeometry(); } if (OuyaExampleCommon.GetButton(OuyaSDK.KeyEnum.BUTTON_O, OuyaSDK.OuyaPlayer.player1)) { IncreaseGeometry(0.1f); } if (OuyaExampleCommon.GetButton(OuyaSDK.KeyEnum.BUTTON_A, OuyaSDK.OuyaPlayer.player1)) { DecreaseGeometry(0.1f); } } float x = OuyaExampleCommon.GetAxis("LY", OuyaSDK.OuyaPlayer.player1); float y = OuyaExampleCommon.GetAxis("LX", OuyaSDK.OuyaPlayer.player1); Camera.main.transform.RotateAround(new Vector3(0, 0, 3), Camera.main.transform.rotation * Vector3.right, x * 45 * Time.fixedDeltaTime); Camera.main.transform.RotateAround(new Vector3(0, 0, 3), Camera.main.transform.rotation * Vector3.up, y * 45 * Time.fixedDeltaTime); } private void IncreaseGeometry(float size) { m_deferList.Clear(); if (m_items.Count > 0) { int count = m_items.Count; for (int index = 0; index < count; ++index) { Action action = () => { SpawnPolys(size); }; m_deferList.Add(action); } } else { SpawnPolys(size); } } private void DecreaseGeometry(float size) { m_deferList.Clear(); int count = m_items.Count/2; while (m_items.Count != 0 && count < m_items.Count) { MeshFilter mf = m_items[m_items.Count - 1]; m_items.Remove(mf); mf.mesh.Clear(); Object.DestroyImmediate(mf.gameObject, true); } } private void CombineGeometry(int index) { if (index >= m_items.Count) { return; } int combineIndex = index + 1; if (combineIndex >= m_items.Count) { return; } MeshFilter mf = m_items[index]; MeshFilter mf2 = m_items[combineIndex]; if (mf.mesh && mf2.mesh) { int trianglesCount = mf.mesh.triangles.Length + mf2.mesh.triangles.Length; int vertCount = mf.mesh.vertices.Length + mf2.mesh.vertices.Length; if (65000 < trianglesCount && 65000 < vertCount) { return; } CombineInstance[] combine = { new CombineInstance() { mesh = mf.mesh, transform = Matrix4x4.identity, subMeshIndex = 0}, new CombineInstance() { mesh = mf2.mesh, transform = Matrix4x4.identity, subMeshIndex = 0}, }; Mesh newMesh = new Mesh(); newMesh.CombineMeshes(combine); mf.mesh = newMesh; m_items.Remove(mf2); Object.DestroyImmediate(mf2.gameObject, true); } } private void CombineGeometry() { m_deferList.Clear(); for (int index = 0; index < (m_items.Count / 2); ++index) { int indexCopy = index; Action action = () => { CombineGeometry(indexCopy); }; m_deferList.Add(action); } } private void SpawnPolys(float size) { Vector3 position = new Vector3( Random.Range(-5f, 5f), Random.Range(-3f, 3f), Random.Range(5f, 1f)); GameObject go = (GameObject)Object.Instantiate(PrefabCube.gameObject, Vector3.zero, Quaternion.identity); go.transform.localScale = Vector3.one; go.name = "polys"; go.transform.parent = transform; MeshRenderer mr = go.GetComponent<MeshRenderer>(); MeshFilter mf = go.GetComponent<MeshFilter>(); m_items.Add(mf); //scale the verts Vector3[] verts = mf.mesh.vertices; for (int v = 0; v < mf.mesh.vertexCount; ++v) { verts[v] = position + verts[v] * size; } mf.mesh.vertices = verts; mr.sharedMaterial = SharedMaterial; } #endregion }
using GitVersion.Configuration; using GitVersion.Core.Tests.Helpers; using GitVersion.Extensions; using GitVersion.Helpers; using GitVersion.Logging; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using NUnit.Framework; using Shouldly; namespace GitVersion.Core.Tests; [TestFixture] public class ConfigFileLocatorTests { public class DefaultConfigFileLocatorTests : TestBase { private const string DefaultRepoPath = @"c:\MyGitRepo"; private const string DefaultWorkingPath = @"c:\MyGitRepo\Working"; private string repoPath; private string workingPath; private IFileSystem fileSystem; private IConfigProvider configurationProvider; private IConfigFileLocator configFileLocator; [SetUp] public void Setup() { this.repoPath = DefaultRepoPath; this.workingPath = DefaultWorkingPath; var options = Options.Create(new GitVersionOptions { WorkingDirectory = repoPath }); var sp = ConfigureServices(services => services.AddSingleton(options)); this.fileSystem = sp.GetRequiredService<IFileSystem>(); this.configurationProvider = sp.GetRequiredService<IConfigProvider>(); this.configFileLocator = sp.GetRequiredService<IConfigFileLocator>(); ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute<TestAttribute>(); } [TestCase(ConfigFileLocator.DefaultFileName, ConfigFileLocator.DefaultFileName)] public void ThrowsExceptionOnAmbiguousConfigFileLocation(string repoConfigFile, string workingConfigFile) { var repositoryConfigFilePath = SetupConfigFileContent(string.Empty, repoConfigFile, this.repoPath); var workingDirectoryConfigFilePath = SetupConfigFileContent(string.Empty, workingConfigFile, this.workingPath); var exception = Should.Throw<WarningException>(() => this.configFileLocator.Verify(this.workingPath, this.repoPath)); var expectedMessage = $"Ambiguous config file selection from '{workingDirectoryConfigFilePath}' and '{repositoryConfigFilePath}'"; exception.Message.ShouldBe(expectedMessage); } [Test] public void NoWarnOnGitVersionYmlFile() { SetupConfigFileContent(string.Empty, ConfigFileLocator.DefaultFileName, this.repoPath); Should.NotThrow(() => this.configurationProvider.Provide(this.repoPath)); } [Test] public void NoWarnOnNoGitVersionYmlFile() => Should.NotThrow(() => this.configurationProvider.Provide(this.repoPath)); private string SetupConfigFileContent(string text, string fileName, string path) { var fullPath = PathHelper.Combine(path, fileName); this.fileSystem.WriteAllText(fullPath, text); return fullPath; } } public class NamedConfigFileLocatorTests : TestBase { private const string DefaultRepoPath = @"c:\MyGitRepo"; private const string DefaultWorkingPath = @"c:\MyGitRepo\Working"; private string repoPath; private string workingPath; private IFileSystem fileSystem; private IConfigFileLocator configFileLocator; private GitVersionOptions gitVersionOptions; [SetUp] public void Setup() { this.gitVersionOptions = new GitVersionOptions { ConfigInfo = { ConfigFile = "my-config.yaml" } }; this.repoPath = DefaultRepoPath; this.workingPath = DefaultWorkingPath; ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute<TestAttribute>(); } [Test] public void ThrowsExceptionOnAmbiguousConfigFileLocation() { var sp = GetServiceProvider(this.gitVersionOptions); this.configFileLocator = sp.GetRequiredService<IConfigFileLocator>(); this.fileSystem = sp.GetRequiredService<IFileSystem>(); var repositoryConfigFilePath = SetupConfigFileContent(string.Empty, path: this.repoPath); var workingDirectoryConfigFilePath = SetupConfigFileContent(string.Empty, path: this.workingPath); var exception = Should.Throw<WarningException>(() => this.configFileLocator.Verify(this.workingPath, this.repoPath)); var expectedMessage = $"Ambiguous config file selection from '{workingDirectoryConfigFilePath}' and '{repositoryConfigFilePath}'"; exception.Message.ShouldBe(expectedMessage); } [Test] public void DoNotThrowWhenWorkingAndRepoPathsAreSame() { this.workingPath = DefaultRepoPath; var sp = GetServiceProvider(this.gitVersionOptions); this.configFileLocator = sp.GetRequiredService<IConfigFileLocator>(); this.fileSystem = sp.GetRequiredService<IFileSystem>(); SetupConfigFileContent(string.Empty, path: this.workingPath); Should.NotThrow(() => this.configFileLocator.Verify(this.workingPath, this.repoPath)); } [Test] public void DoNotThrowWhenWorkingAndRepoPathsAreSame_WithDifferentCasing() { this.workingPath = DefaultRepoPath.ToLower(); var sp = GetServiceProvider(this.gitVersionOptions); this.configFileLocator = sp.GetRequiredService<IConfigFileLocator>(); this.fileSystem = sp.GetRequiredService<IFileSystem>(); SetupConfigFileContent(string.Empty, path: this.workingPath); Should.NotThrow(() => this.configFileLocator.Verify(this.workingPath, this.repoPath)); } [Test] public void DoNotThrowWhenConfigFileIsInSubDirectoryOfRepoPath() { this.workingPath = DefaultRepoPath; this.gitVersionOptions = new GitVersionOptions { ConfigInfo = { ConfigFile = "./src/my-config.yaml" } }; var sp = GetServiceProvider(this.gitVersionOptions); this.configFileLocator = sp.GetRequiredService<IConfigFileLocator>(); this.fileSystem = sp.GetRequiredService<IFileSystem>(); SetupConfigFileContent(string.Empty, path: this.workingPath); Should.NotThrow(() => this.configFileLocator.Verify(this.workingPath, this.repoPath)); } [Test] public void NoWarnOnCustomYmlFile() { var stringLogger = string.Empty; void Action(string info) => stringLogger = info; var logAppender = new TestLogAppender(Action); var log = new Log(logAppender); var sp = GetServiceProvider(this.gitVersionOptions, log); this.configFileLocator = sp.GetRequiredService<IConfigFileLocator>(); this.fileSystem = sp.GetRequiredService<IFileSystem>(); SetupConfigFileContent(string.Empty); var configurationProvider = sp.GetRequiredService<IConfigProvider>(); configurationProvider.Provide(this.repoPath); stringLogger.Length.ShouldBe(0); } [Test] public void NoWarnOnCustomYmlFileOutsideRepoPath() { var stringLogger = string.Empty; void Action(string info) => stringLogger = info; var logAppender = new TestLogAppender(Action); var log = new Log(logAppender); var sp = GetServiceProvider(this.gitVersionOptions, log); this.configFileLocator = sp.GetRequiredService<IConfigFileLocator>(); this.fileSystem = sp.GetRequiredService<IFileSystem>(); SetupConfigFileContent(string.Empty, path: @"c:\\Unrelated\\path"); var configurationProvider = sp.GetRequiredService<IConfigProvider>(); configurationProvider.Provide(this.repoPath); stringLogger.Length.ShouldBe(0); } [Test] public void ThrowsExceptionOnCustomYmlFileDoesNotExist() { var sp = GetServiceProvider(this.gitVersionOptions); this.configFileLocator = sp.GetRequiredService<IConfigFileLocator>(); var exception = Should.Throw<WarningException>(() => this.configFileLocator.Verify(this.workingPath, this.repoPath)); var workingPathFileConfig = PathHelper.Combine(this.workingPath, this.gitVersionOptions.ConfigInfo.ConfigFile); var repoPathFileConfig = PathHelper.Combine(this.repoPath, this.gitVersionOptions.ConfigInfo.ConfigFile); var expectedMessage = $"The configuration file was not found at '{workingPathFileConfig}' or '{repoPathFileConfig}'"; exception.Message.ShouldBe(expectedMessage); } private string SetupConfigFileContent(string text, string? fileName = null, string? path = null) { if (fileName.IsNullOrEmpty()) fileName = this.configFileLocator.FilePath; var filePath = fileName; if (!path.IsNullOrEmpty()) filePath = PathHelper.Combine(path, filePath); this.fileSystem.WriteAllText(filePath, text); return filePath; } private static IServiceProvider GetServiceProvider(GitVersionOptions gitVersionOptions, ILog? log = null) => ConfigureServices(services => { if (log != null) services.AddSingleton(log); services.AddSingleton(Options.Create(gitVersionOptions)); }); } }
//--------------------------------------------------------------------------- // // <copyright file="ScrollPattern" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: Client-side wrapper for Scroll Pattern // // History: // 06/23/2003 : BrendanM Ported to WCP // //--------------------------------------------------------------------------- using System; using System.Windows.Automation.Provider; using MS.Internal.Automation; namespace System.Windows.Automation { /// <summary> /// Represents UI elements that are expressing a value /// </summary> #if (INTERNAL_COMPILE) internal class ScrollPattern: BasePattern #else public class ScrollPattern: BasePattern #endif { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors private ScrollPattern(AutomationElement el, SafePatternHandle hPattern, bool cached) : base(el, hPattern) { _hPattern = hPattern; _cached = cached; } #endregion Constructors //------------------------------------------------------ // // Public Constants / Readonly Fields // //------------------------------------------------------ #region Public Constants and Readonly Fields /// <summary>Value used by SetSCrollPercent to indicate that no scrolling should take place in the specified direction</summary> public const double NoScroll = -1.0; /// <summary>Scroll pattern</summary> public static readonly AutomationPattern Pattern = ScrollPatternIdentifiers.Pattern; /// <summary>Property ID: HorizontalScrollPercent - Current horizontal scroll position</summary> public static readonly AutomationProperty HorizontalScrollPercentProperty = ScrollPatternIdentifiers.HorizontalScrollPercentProperty; /// <summary>Property ID: HorizontalViewSize - Minimum possible horizontal scroll position</summary> public static readonly AutomationProperty HorizontalViewSizeProperty = ScrollPatternIdentifiers.HorizontalViewSizeProperty; /// <summary>Property ID: VerticalScrollPercent - Current vertical scroll position</summary> public static readonly AutomationProperty VerticalScrollPercentProperty = ScrollPatternIdentifiers.VerticalScrollPercentProperty; /// <summary>Property ID: VerticalViewSize </summary> public static readonly AutomationProperty VerticalViewSizeProperty = ScrollPatternIdentifiers.VerticalViewSizeProperty; /// <summary>Property ID: HorizontallyScrollable</summary> public static readonly AutomationProperty HorizontallyScrollableProperty = ScrollPatternIdentifiers.HorizontallyScrollableProperty; /// <summary>Property ID: VerticallyScrollable</summary> public static readonly AutomationProperty VerticallyScrollableProperty = ScrollPatternIdentifiers.VerticallyScrollableProperty; #endregion Public Constants and Readonly Fields //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> Request to set the current horizontal and Vertical scroll position /// by percent (0-100). Passing in the value of "-1" will indicate that /// scrolling in that direction should be ignored. /// The ability to call this method and simultaneously scroll horizontally and /// vertically provides simple panning support.</summary> /// <param name="horizontalPercent">Amount to scroll by horizontally</param> /// <param name="verticalPercent">Amount to scroll by vertically </param> /// /// <outside_see conditional="false"> /// This API does not work inside the secure execution environment. /// <exception cref="System.Security.Permissions.SecurityPermission"/> /// </outside_see> public void SetScrollPercent( double horizontalPercent, double verticalPercent ) { UiaCoreApi.ScrollPattern_SetScrollPercent(_hPattern, horizontalPercent, verticalPercent); } /// <summary> Request to scroll horizontally and vertically by the specified amount. /// The ability to call this method and simultaneously scroll horizontally /// and vertically provides simple panning support. If only horizontal or vertical percent /// needs to be changed the constant SetScrollPercentUnchanged can be used for /// either parameter and that axis wil be unchanged.</summary> /// /// <param name="horizontalAmount">amount to scroll by horizontally</param> /// <param name="verticalAmount">amount to scroll by vertically </param> /// /// <outside_see conditional="false"> /// This API does not work inside the secure execution environment. /// <exception cref="System.Security.Permissions.SecurityPermission"/> /// </outside_see> public void Scroll( ScrollAmount horizontalAmount, ScrollAmount verticalAmount ) { UiaCoreApi.ScrollPattern_Scroll(_hPattern, horizontalAmount, verticalAmount); } /// <summary> /// Request to scroll horizontally by the specified amount /// </summary> /// <param name="amount">Amount to scroll by</param> /// /// <outside_see conditional="false"> /// This API does not work inside the secure execution environment. /// <exception cref="System.Security.Permissions.SecurityPermission"/> /// </outside_see> public void ScrollHorizontal( ScrollAmount amount ) { UiaCoreApi.ScrollPattern_Scroll(_hPattern, amount, ScrollAmount.NoAmount); } /// <summary> /// Request to scroll vertically by the specified amount /// </summary> /// <param name="amount">Amount to scroll by</param> /// /// <outside_see conditional="false"> /// This API does not work inside the secure execution environment. /// <exception cref="System.Security.Permissions.SecurityPermission"/> /// </outside_see> public void ScrollVertical( ScrollAmount amount ) { UiaCoreApi.ScrollPattern_Scroll(_hPattern, ScrollAmount.NoAmount, amount); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties /// <summary> /// This member allows access to previously requested /// cached properties for this element. The returned object /// has accessors for each property defined for this pattern. /// </summary> /// <remarks> /// Cached property values must have been previously requested /// using a CacheRequest. If you try to access a cached /// property that was not previously requested, an InvalidOperation /// Exception will be thrown. /// /// To get the value of a property at the current point in time, /// access the property via the Current accessor instead of /// Cached. /// </remarks> public ScrollPatternInformation Cached { get { Misc.ValidateCached(_cached); return new ScrollPatternInformation(_el, true); } } /// <summary> /// This member allows access to current property values /// for this element. The returned object has accessors for /// each property defined for this pattern. /// </summary> /// <remarks> /// This pattern must be from an AutomationElement with a /// Full reference in order to get current values. If the /// AutomationElement was obtained using AutomationElementMode.None, /// then it contains only cached data, and attempting to get /// the current value of any property will throw an InvalidOperationException. /// /// To get the cached value of a property that was previously /// specified using a CacheRequest, access the property via the /// Cached accessor instead of Current. /// </remarks> public ScrollPatternInformation Current { get { Misc.ValidateCurrent(_hPattern); return new ScrollPatternInformation(_el, false); } } #endregion Public Properties //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods static internal object Wrap(AutomationElement el, SafePatternHandle hPattern, bool cached) { return new ScrollPattern(el, hPattern, cached); } #endregion Internal Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields SafePatternHandle _hPattern; bool _cached; #endregion Private Fields //------------------------------------------------------ // // Nested Classes // //------------------------------------------------------ #region Nested Classes /// <summary> /// This class provides access to either Cached or Current /// properties on a pattern via the pattern's .Cached or /// .Current accessors. /// </summary> public struct ScrollPatternInformation { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors internal ScrollPatternInformation(AutomationElement el, bool useCache) { _el = el; _useCache = useCache; } #endregion Constructors //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties /// <summary> /// Get the current horizontal scroll position /// </summary> /// /// <outside_see conditional="false"> /// This API does not work inside the secure execution environment. /// <exception cref="System.Security.Permissions.SecurityPermission"/> /// </outside_see> public double HorizontalScrollPercent { get { return (double)_el.GetPatternPropertyValue(HorizontalScrollPercentProperty, _useCache); } } /// <summary> /// Get the current vertical scroll position /// </summary> /// /// <outside_see conditional="false"> /// This API does not work inside the secure execution environment. /// <exception cref="System.Security.Permissions.SecurityPermission"/> /// </outside_see> public double VerticalScrollPercent { get { return (double)_el.GetPatternPropertyValue(VerticalScrollPercentProperty, _useCache); } } /// <summary> /// Equal to the horizontal percentage of the entire control that is currently viewable. /// </summary> /// /// <outside_see conditional="false"> /// This API does not work inside the secure execution environment. /// <exception cref="System.Security.Permissions.SecurityPermission"/> /// </outside_see> public double HorizontalViewSize { get { return (double)_el.GetPatternPropertyValue(HorizontalViewSizeProperty, _useCache); } } /// <summary> /// Equal to the horizontal percentage of the entire control that is currently viewable. /// </summary> /// /// <outside_see conditional="false"> /// This API does not work inside the secure execution environment. /// <exception cref="System.Security.Permissions.SecurityPermission"/> /// </outside_see> public double VerticalViewSize { get { return (double)_el.GetPatternPropertyValue(VerticalViewSizeProperty, _useCache); } } /// <summary> /// True if control can scroll horizontally /// </summary> /// /// <outside_see conditional="false"> /// This API does not work inside the secure execution environment. /// <exception cref="System.Security.Permissions.SecurityPermission"/> /// </outside_see> public bool HorizontallyScrollable { get { return (bool)_el.GetPatternPropertyValue(HorizontallyScrollableProperty, _useCache); } } /// <summary> /// True if control can scroll vertically /// </summary> /// /// <outside_see conditional="false"> /// This API does not work inside the secure execution environment. /// <exception cref="System.Security.Permissions.SecurityPermission"/> /// </outside_see> public bool VerticallyScrollable { get { return (bool)_el.GetPatternPropertyValue(VerticallyScrollableProperty, _useCache); } } #endregion Public Properties //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields private AutomationElement _el; // AutomationElement that contains the cache or live reference private bool _useCache; // true to use cache, false to use live reference to get current values #endregion Private Fields } #endregion Nested Classes } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedInterconnectsClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<Interconnects.InterconnectsClient> mockGrpcClient = new moq::Mock<Interconnects.InterconnectsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInterconnectRequest request = new GetInterconnectRequest { Interconnect = "interconnect253e8bf5", Project = "projectaa6ff846", }; Interconnect expectedResponse = new Interconnect { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CustomerName = "customer_name2ace137a", NocContactEmail = "noc_contact_email1d95c1b6", CreationTimestamp = "creation_timestamp235e59a1", RequestedLinkCount = 2020560861, State = "state2e9ed39e", CircuitInfos = { new InterconnectCircuitInfo(), }, OperationalStatus = "operational_status14a476d9", PeerIpAddress = "peer_ip_address07617b81", ExpectedOutages = { new InterconnectOutageNotification(), }, Location = "locatione09d18d5", ProvisionedLinkCount = 1441690745, Description = "description2cf9da67", InterconnectAttachments = { "interconnect_attachmentsdc10a889", }, GoogleIpAddress = "google_ip_address246d4427", AdminEnabled = true, SelfLink = "self_link7e87f12d", SatisfiesPzs = false, InterconnectType = "interconnect_type87ba691d", LinkType = "link_type65f7baf6", GoogleReferenceId = "google_reference_id815b6ab4", }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InterconnectsClient client = new InterconnectsClientImpl(mockGrpcClient.Object, null); Interconnect response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<Interconnects.InterconnectsClient> mockGrpcClient = new moq::Mock<Interconnects.InterconnectsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInterconnectRequest request = new GetInterconnectRequest { Interconnect = "interconnect253e8bf5", Project = "projectaa6ff846", }; Interconnect expectedResponse = new Interconnect { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CustomerName = "customer_name2ace137a", NocContactEmail = "noc_contact_email1d95c1b6", CreationTimestamp = "creation_timestamp235e59a1", RequestedLinkCount = 2020560861, State = "state2e9ed39e", CircuitInfos = { new InterconnectCircuitInfo(), }, OperationalStatus = "operational_status14a476d9", PeerIpAddress = "peer_ip_address07617b81", ExpectedOutages = { new InterconnectOutageNotification(), }, Location = "locatione09d18d5", ProvisionedLinkCount = 1441690745, Description = "description2cf9da67", InterconnectAttachments = { "interconnect_attachmentsdc10a889", }, GoogleIpAddress = "google_ip_address246d4427", AdminEnabled = true, SelfLink = "self_link7e87f12d", SatisfiesPzs = false, InterconnectType = "interconnect_type87ba691d", LinkType = "link_type65f7baf6", GoogleReferenceId = "google_reference_id815b6ab4", }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Interconnect>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InterconnectsClient client = new InterconnectsClientImpl(mockGrpcClient.Object, null); Interconnect responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Interconnect responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<Interconnects.InterconnectsClient> mockGrpcClient = new moq::Mock<Interconnects.InterconnectsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInterconnectRequest request = new GetInterconnectRequest { Interconnect = "interconnect253e8bf5", Project = "projectaa6ff846", }; Interconnect expectedResponse = new Interconnect { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CustomerName = "customer_name2ace137a", NocContactEmail = "noc_contact_email1d95c1b6", CreationTimestamp = "creation_timestamp235e59a1", RequestedLinkCount = 2020560861, State = "state2e9ed39e", CircuitInfos = { new InterconnectCircuitInfo(), }, OperationalStatus = "operational_status14a476d9", PeerIpAddress = "peer_ip_address07617b81", ExpectedOutages = { new InterconnectOutageNotification(), }, Location = "locatione09d18d5", ProvisionedLinkCount = 1441690745, Description = "description2cf9da67", InterconnectAttachments = { "interconnect_attachmentsdc10a889", }, GoogleIpAddress = "google_ip_address246d4427", AdminEnabled = true, SelfLink = "self_link7e87f12d", SatisfiesPzs = false, InterconnectType = "interconnect_type87ba691d", LinkType = "link_type65f7baf6", GoogleReferenceId = "google_reference_id815b6ab4", }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InterconnectsClient client = new InterconnectsClientImpl(mockGrpcClient.Object, null); Interconnect response = client.Get(request.Project, request.Interconnect); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<Interconnects.InterconnectsClient> mockGrpcClient = new moq::Mock<Interconnects.InterconnectsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInterconnectRequest request = new GetInterconnectRequest { Interconnect = "interconnect253e8bf5", Project = "projectaa6ff846", }; Interconnect expectedResponse = new Interconnect { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CustomerName = "customer_name2ace137a", NocContactEmail = "noc_contact_email1d95c1b6", CreationTimestamp = "creation_timestamp235e59a1", RequestedLinkCount = 2020560861, State = "state2e9ed39e", CircuitInfos = { new InterconnectCircuitInfo(), }, OperationalStatus = "operational_status14a476d9", PeerIpAddress = "peer_ip_address07617b81", ExpectedOutages = { new InterconnectOutageNotification(), }, Location = "locatione09d18d5", ProvisionedLinkCount = 1441690745, Description = "description2cf9da67", InterconnectAttachments = { "interconnect_attachmentsdc10a889", }, GoogleIpAddress = "google_ip_address246d4427", AdminEnabled = true, SelfLink = "self_link7e87f12d", SatisfiesPzs = false, InterconnectType = "interconnect_type87ba691d", LinkType = "link_type65f7baf6", GoogleReferenceId = "google_reference_id815b6ab4", }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Interconnect>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InterconnectsClient client = new InterconnectsClientImpl(mockGrpcClient.Object, null); Interconnect responseCallSettings = await client.GetAsync(request.Project, request.Interconnect, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Interconnect responseCancellationToken = await client.GetAsync(request.Project, request.Interconnect, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetDiagnosticsRequestObject() { moq::Mock<Interconnects.InterconnectsClient> mockGrpcClient = new moq::Mock<Interconnects.InterconnectsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDiagnosticsInterconnectRequest request = new GetDiagnosticsInterconnectRequest { Interconnect = "interconnect253e8bf5", Project = "projectaa6ff846", }; InterconnectsGetDiagnosticsResponse expectedResponse = new InterconnectsGetDiagnosticsResponse { Result = new InterconnectDiagnostics(), }; mockGrpcClient.Setup(x => x.GetDiagnostics(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InterconnectsClient client = new InterconnectsClientImpl(mockGrpcClient.Object, null); InterconnectsGetDiagnosticsResponse response = client.GetDiagnostics(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetDiagnosticsRequestObjectAsync() { moq::Mock<Interconnects.InterconnectsClient> mockGrpcClient = new moq::Mock<Interconnects.InterconnectsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDiagnosticsInterconnectRequest request = new GetDiagnosticsInterconnectRequest { Interconnect = "interconnect253e8bf5", Project = "projectaa6ff846", }; InterconnectsGetDiagnosticsResponse expectedResponse = new InterconnectsGetDiagnosticsResponse { Result = new InterconnectDiagnostics(), }; mockGrpcClient.Setup(x => x.GetDiagnosticsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InterconnectsGetDiagnosticsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InterconnectsClient client = new InterconnectsClientImpl(mockGrpcClient.Object, null); InterconnectsGetDiagnosticsResponse responseCallSettings = await client.GetDiagnosticsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); InterconnectsGetDiagnosticsResponse responseCancellationToken = await client.GetDiagnosticsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetDiagnostics() { moq::Mock<Interconnects.InterconnectsClient> mockGrpcClient = new moq::Mock<Interconnects.InterconnectsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDiagnosticsInterconnectRequest request = new GetDiagnosticsInterconnectRequest { Interconnect = "interconnect253e8bf5", Project = "projectaa6ff846", }; InterconnectsGetDiagnosticsResponse expectedResponse = new InterconnectsGetDiagnosticsResponse { Result = new InterconnectDiagnostics(), }; mockGrpcClient.Setup(x => x.GetDiagnostics(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InterconnectsClient client = new InterconnectsClientImpl(mockGrpcClient.Object, null); InterconnectsGetDiagnosticsResponse response = client.GetDiagnostics(request.Project, request.Interconnect); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetDiagnosticsAsync() { moq::Mock<Interconnects.InterconnectsClient> mockGrpcClient = new moq::Mock<Interconnects.InterconnectsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDiagnosticsInterconnectRequest request = new GetDiagnosticsInterconnectRequest { Interconnect = "interconnect253e8bf5", Project = "projectaa6ff846", }; InterconnectsGetDiagnosticsResponse expectedResponse = new InterconnectsGetDiagnosticsResponse { Result = new InterconnectDiagnostics(), }; mockGrpcClient.Setup(x => x.GetDiagnosticsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InterconnectsGetDiagnosticsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InterconnectsClient client = new InterconnectsClientImpl(mockGrpcClient.Object, null); InterconnectsGetDiagnosticsResponse responseCallSettings = await client.GetDiagnosticsAsync(request.Project, request.Interconnect, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); InterconnectsGetDiagnosticsResponse responseCancellationToken = await client.GetDiagnosticsAsync(request.Project, request.Interconnect, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using NUnit.Framework; using NSubstitute; using System.Linq; using NMahjong.Base; using NMahjong.Japanese; using NMahjong.Japanese.Engine; using NMahjong.Testing; namespace NMahjong.Drivers.Mjai { [TestFixture] public class MjaiMessageProcessorTest : TestHelperWithRevealedMelds { private MjaiMessageProcessor mProcessor; private IEventSender mEventSender; [SetUp] public void Setup() { mEventSender = Substitute.For<IEventSender>(); mProcessor = new MjaiMessageProcessor(mEventSender, 1); } [Test] public void TestStartKyoku() { const string message = @"{ ""type"":""start_kyoku"",""bakaze"":""S"",""kyoku"":1,""honba"":2,""kyotaku"":3, ""oya"":0,""dora_marker"":""7s"", ""tehais"":[ [""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?""], [""3m"",""4m"",""3p"",""5pr"",""7p"",""9p"",""4s"",""4s"",""5sr"",""7s"", ""7s"",""W"",""N""], [""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?""], [""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?""] ] }"; HandStartingEventArgs handStarting = null; mEventSender.OnHandStarting( Arg.Do<HandStartingEventArgs>(e => { handStarting = e; })); SticksUpdatedEventArgs sticksUpdated = null; mEventSender.OnSticksUpdated( Arg.Do<SticksUpdatedEventArgs>(e => { sticksUpdated = e; })); var tiles = new IPlayerHand[4]; mEventSender.OnPlayerHandUpdated( Arg.Do<PlayerHandUpdatedEventArgs>(e => { tiles[e.Player.Id] = e.Tiles; })); DoraAddedEventArgs doraAdded = null; mEventSender.OnDoraAdded( Arg.Do<DoraAddedEventArgs>(e => { doraAdded = e; })); mProcessor.Process(MjaiJson.Parse(message)); mEventSender.ReceivedWithAnyArgs(1).OnHandStarting(null); Assert.AreEqual(Wind.South, handStarting.PrevailingWind); Assert.AreEqual(1, handStarting.HandNumber); Assert.AreEqual(Player3, handStarting.Dealer); Assert.AreEqual(136 - 13 * 4 - 14, handStarting.Wall.Count); mEventSender.ReceivedWithAnyArgs(1).OnSticksUpdated(null); Assert.AreEqual(2, sticksUpdated.Counters); Assert.AreEqual(3, sticksUpdated.RiichiSticks); Assert.AreEqual(2, mProcessor.Counters); Assert.AreEqual(3, mProcessor.RiichiSticks); mEventSender.ReceivedWithAnyArgs(4).OnPlayerHandUpdated(null); Assert.AreEqual(new [] { W3p, W4p, T3p, T5r, T7p, T9p, S4p, S4p, S5r, S7p, S7p, FWp, FNp }, tiles[0]); Assert.AreEqual(Enumerable.Repeat<CanonicalTile>(null, 13), tiles[1]); Assert.AreEqual(Enumerable.Repeat<CanonicalTile>(null, 13), tiles[2]); Assert.AreEqual(Enumerable.Repeat<CanonicalTile>(null, 13), tiles[3]); mEventSender.ReceivedWithAnyArgs(1).OnDoraAdded(null); Assert.AreEqual(S7p, doraAdded.Dora.Indicator); Assert.AreEqual(S8, doraAdded.Dora.Tile); mEventSender.ReceivedWithAnyArgs(1).OnHandStarted(null); } [Test] public void TestEndKyoku() { const string message = @"{""type"":""end_kyoku""}"; mProcessor.Process(MjaiJson.Parse(message)); mEventSender.ReceivedWithAnyArgs(1).OnHandEnded(null); } [Test] public void TestTsumoShowed() { const string message = @"{ ""type"":""tsumo"",""actor"":1,""pai"":""3m"", }"; TileDrawnEventArgs eventArgs = null; mEventSender.OnTileDrawn( Arg.Do<TileDrawnEventArgs>(e => { eventArgs = e; })); mProcessor.Process(MjaiJson.Parse(message)); mEventSender.ReceivedWithAnyArgs(1).OnTileDrawn(null); Assert.AreEqual(Player0, eventArgs.Player); Assert.AreEqual(W3p, eventArgs.Tile); } [Test] public void TestTsumoHidden() { const string message = @"{ ""type"":""tsumo"",""actor"":0,""pai"":""?"", }"; TileDrawnEventArgs eventArgs = null; mEventSender.OnTileDrawn( Arg.Do<TileDrawnEventArgs>(e => { eventArgs = e; })); mProcessor.Process(MjaiJson.Parse(message)); mEventSender.ReceivedWithAnyArgs(1).OnTileDrawn(null); Assert.AreEqual(Player3, eventArgs.Player); Assert.AreEqual(null, eventArgs.Tile); } [Test] public void TestDahaiTedashi() { const string message = @"{ ""type"":""dahai"",""actor"":1,""pai"":""7s"",""tsumogiri"":false }"; TileDiscardedEventArgs eventArgs = null; mEventSender.OnTileDiscarded( Arg.Do<TileDiscardedEventArgs>(e => { eventArgs = e; })); mProcessor.Process(MjaiJson.Parse(message)); mEventSender.ReceivedWithAnyArgs(1).OnTileDiscarded(null); Assert.AreEqual(Player0, eventArgs.Player); Assert.AreEqual(S7p, eventArgs.Discard); } [Test] public void TestDahaiTsumogiri() { const string message = @"{ ""type"":""dahai"",""actor"":1,""pai"":""7s"",""tsumogiri"":true }"; TileDiscardedEventArgs eventArgs = null; mEventSender.OnTileDiscarded( Arg.Do<TileDiscardedEventArgs>(e => { eventArgs = e; })); mProcessor.Process(MjaiJson.Parse(message)); mEventSender.ReceivedWithAnyArgs(1).OnTileDiscarded(null); Assert.AreEqual(Player0, eventArgs.Player); Assert.AreEqual(Drawn(S7p), eventArgs.Discard); } [Test] public void TestPon() { const string message = @"{ ""type"":""pon"",""actor"":0,""target"":1,""pai"":""5sr"", ""consumed"":[""5s"",""5s""] }"; MeldRevealedEventArgs eventArgs = null; mEventSender.OnMeldRevealed( Arg.Do<MeldRevealedEventArgs>(e => { eventArgs = e; })); mProcessor.Process(MjaiJson.Parse(message)); mEventSender.ReceivedWithAnyArgs(1).OnMeldRevealed(null); Assert.AreEqual(Player3, eventArgs.Player); MeldAssert.AreIdentical(OPung(S5p, S5p, S5r, Player0), eventArgs.Meld); } [Test] public void TestChi() { const string message = @"{ ""type"":""chi"",""actor"":0,""target"":3,""pai"":""4p"", ""consumed"":[""5p"",""6p""] }"; MeldRevealedEventArgs eventArgs = null; mEventSender.OnMeldRevealed( Arg.Do<MeldRevealedEventArgs>(e => { eventArgs = e; })); mProcessor.Process(MjaiJson.Parse(message)); mEventSender.ReceivedWithAnyArgs(1).OnMeldRevealed(null); Assert.AreEqual(Player3, eventArgs.Player); MeldAssert.AreIdentical(OChow(T5p, T6p, T4p, Player2), eventArgs.Meld); } [Test] public void TestDaiminkan() { const string message = @"{ ""type"":""daiminkan"",""actor"":3,""target"":1,""pai"":""5m"", ""consumed"":[""5m"",""5m"",""5mr""] }"; MeldRevealedEventArgs eventArgs = null; mEventSender.OnMeldRevealed( Arg.Do<MeldRevealedEventArgs>(e => { eventArgs = e; })); mProcessor.Process(MjaiJson.Parse(message)); mEventSender.ReceivedWithAnyArgs(1).OnMeldRevealed(null); Assert.AreEqual(Player2, eventArgs.Player); MeldAssert.AreIdentical(OKong(W5p, W5p, W5r, W5p, Player0), eventArgs.Meld); } [Test] public void TestAnkan() { const string message = @"{ ""type"":""ankan"",""actor"":1,""consumed"":[""N"",""N"",""N"",""N""] }"; MeldRevealedEventArgs eventArgs = null; mEventSender.OnMeldRevealed( Arg.Do<MeldRevealedEventArgs>(e => { eventArgs = e; })); mProcessor.Process(MjaiJson.Parse(message)); mEventSender.ReceivedWithAnyArgs(1).OnMeldRevealed(null); Assert.AreEqual(Player0, eventArgs.Player); MeldAssert.AreIdentical(CKong(FNp, FNp, FNp, FNp), eventArgs.Meld); } [Test] public void TestKakan() { const string message = @"{ ""type"":""kakan"",""actor"":0,""pai"":""6m"", ""consumed"":[""6m"",""6m"",""6m""] }"; MeldExtendedEventArgs eventArgs = null; mEventSender.OnMeldExtended( Arg.Do<MeldExtendedEventArgs>(e => { eventArgs = e; })); mProcessor.Process(MjaiJson.Parse(message)); mEventSender.ReceivedWithAnyArgs(1).OnMeldExtended(null); Assert.AreEqual(Player3, eventArgs.Player); Assert.AreEqual(W6p, eventArgs.Extender); } [Test] public void TestDora() { const string message = @"{""type"":""dora"",""dora_marker"":""8p""}"; DoraAddedEventArgs eventArgs = null; mEventSender.OnDoraAdded( Arg.Do<DoraAddedEventArgs>(e => { eventArgs = e; })); mProcessor.Process(MjaiJson.Parse(message)); mEventSender.ReceivedWithAnyArgs(1).OnDoraAdded(null); Assert.AreEqual(T8p, eventArgs.Dora.Indicator); Assert.AreEqual(T9, eventArgs.Dora.Tile); } [Test] public void TestReach() { const string reach = @"{ ""type"":""reach"",""actor"":1 }"; const string dahai = @"{ ""type"":""dahai"",""actor"":1,""pai"":""7s"",""tsumogiri"":false }"; RiichiEventArgs riichiDeclared = null; mEventSender.OnRiichiDeclared( Arg.Do<RiichiEventArgs>(e => { riichiDeclared = e; })); mProcessor.Process(MjaiJson.Parse(reach)); mEventSender.ReceivedWithAnyArgs(1).OnRiichiDeclared(null); Assert.IsTrue(mProcessor.IsRiichi); Assert.AreEqual(Player0, riichiDeclared.Player); TileDiscardedEventArgs tileDiscarded = null; mEventSender.OnTileDiscarded( Arg.Do<TileDiscardedEventArgs>(e => { tileDiscarded = e; })); mProcessor.Process(MjaiJson.Parse(dahai)); mEventSender.ReceivedWithAnyArgs(1).OnTileDiscarded(null); Assert.IsFalse(mProcessor.IsRiichi); Assert.AreEqual(Player0, tileDiscarded.Player); Assert.AreEqual(Riichi(S7p), tileDiscarded.Discard); } [Test] public void TestReachAccepted() { const string message = @"{ ""type"":""reach_accepted"",""actor"":1,""deltas"":[0,-1000,0,0], ""scores"":[28000,23000,24000,24000] }"; mProcessor.Counters = 2; mProcessor.RiichiSticks = 3; ScoreUpdatedEventArgs scoreUpdated = null; mEventSender.OnScoreUpdated( Arg.Do<ScoreUpdatedEventArgs>(e => { scoreUpdated = e; })); SticksUpdatedEventArgs sticksUpdated = null; mEventSender.OnSticksUpdated( Arg.Do<SticksUpdatedEventArgs>(e => { sticksUpdated = e; })); RiichiEventArgs riichiAccepted = null; mEventSender.OnRiichiAccepted( Arg.Do<RiichiEventArgs>(e => { riichiAccepted = e; })); mProcessor.Process(MjaiJson.Parse(message)); mEventSender.ReceivedWithAnyArgs(1).OnScoreUpdated(null); Assert.AreEqual(Player0, scoreUpdated.Player); Assert.AreEqual(23000, scoreUpdated.Score); Assert.AreEqual(-1000, scoreUpdated.Delta); mEventSender.ReceivedWithAnyArgs(1).OnSticksUpdated(null); Assert.AreEqual(2, sticksUpdated.Counters); Assert.AreEqual(4, sticksUpdated.RiichiSticks); Assert.AreEqual(2, mProcessor.Counters); Assert.AreEqual(4, mProcessor.RiichiSticks); mEventSender.ReceivedWithAnyArgs(1).OnRiichiAccepted(null); Assert.AreEqual(Player0, riichiAccepted.Player); } [Test] public void TestHoraTsumo() { const string message = @"{ ""type"":""hora"",""actor"":2,""target"":2,""pai"":""2m"", ""uradora_markers"":[""8p""], ""hora_tehais"":[""1m"",""3m"",""5m"",""6m"",""7m"",""1p"",""2p"",""3p"",""4p"", ""5pr"",""6p"",""W"",""W"",""2m""], ""yakus"":[[""akadora"",1],[""reach"",1],[""menzenchin_tsumoho"",1]], ""fu"":30,""fan"":3,""hora_points"":4000, ""deltas"":[-2100,-1100,6300,-1100],""scores"":[25900,21900,29300,22900] }"; WinningDeclaredEventArgs winningDeclared = null; mEventSender.OnWinningDeclared( Arg.Do<WinningDeclaredEventArgs>(e => { winningDeclared = e; })); PlayerHandUpdatedEventArgs playerHandUpdated = null; mEventSender.OnPlayerHandUpdated( Arg.Do<PlayerHandUpdatedEventArgs>(e => { playerHandUpdated = e; })); var scoreUpdates = new ScoreUpdatedEventArgs[4]; mEventSender.OnScoreUpdated( Arg.Do<ScoreUpdatedEventArgs>(e => { scoreUpdates[e.Player.Id] = e; })); mProcessor.Process(MjaiJson.Parse(message)); mEventSender.ReceivedWithAnyArgs(1).OnWinningDeclared(null); WinningInfo winningInfo = winningDeclared.WinningInfo; Assert.AreEqual(Player1, winningInfo.Winner); Assert.AreEqual(Player1, winningInfo.Feeder); Assert.AreEqual(30, winningInfo.Minipoints); Assert.AreEqual(3, winningInfo.Fan); Assert.AreEqual(4000, winningInfo.Points); Assert.AreEqual(1, winningDeclared.Uradora.Count); Assert.AreEqual(T8p, winningDeclared.Uradora[0].Indicator); Assert.AreEqual(T9, winningDeclared.Uradora[0].Tile); mEventSender.ReceivedWithAnyArgs(1).OnPlayerHandUpdated(null); Assert.AreEqual(new [] { W1p, W3p, W5p, W6p, W7p, T1p, T2p, T3p, T4p, T5r, T6p, FWp, FWp, Drawn(W2p) }, playerHandUpdated.Tiles); Assert.AreEqual(Player1, playerHandUpdated.Player); mEventSender.ReceivedWithAnyArgs(4).OnScoreUpdated(null); Assert.AreEqual(21900, scoreUpdates[0].Score); Assert.AreEqual(-1100, scoreUpdates[0].Delta); Assert.AreEqual(29300, scoreUpdates[1].Score); Assert.AreEqual(+6300, scoreUpdates[1].Delta); Assert.AreEqual(22900, scoreUpdates[2].Score); Assert.AreEqual(-1100, scoreUpdates[2].Delta); Assert.AreEqual(25900, scoreUpdates[3].Score); Assert.AreEqual(-2100, scoreUpdates[3].Delta); } [Test] public void TestHoraRon() { const string message = @"{ ""type"":""hora"",""actor"":1,""target"":0,""pai"":""7s"", ""uradora_markers"":[""3s""], ""hora_tehais"":[""2m"",""3m"",""4m"",""4p"",""5pr"",""6p"",""6p"",""7p"",""8p"", ""6s"",""8s"",""N"",""N""], ""yakus"":[[""akadora"",1],[""reach"",1]], ""fu"":40,""fan"":2,""hora_points"":2600, ""deltas"":[-4400,8400,0,0],""scores"":[27500,22300,24300,25900] }"; WinningDeclaredEventArgs winningDeclared = null; mEventSender.OnWinningDeclared( Arg.Do<WinningDeclaredEventArgs>(e => { winningDeclared = e; })); PlayerHandUpdatedEventArgs playerHandUpdated = null; mEventSender.OnPlayerHandUpdated( Arg.Do<PlayerHandUpdatedEventArgs>(e => { playerHandUpdated = e; })); var scoreUpdates = new ScoreUpdatedEventArgs[4]; mEventSender.OnScoreUpdated( Arg.Do<ScoreUpdatedEventArgs>(e => { scoreUpdates[e.Player.Id] = e; })); mProcessor.Process(MjaiJson.Parse(message)); mEventSender.ReceivedWithAnyArgs(1).OnWinningDeclared(null); WinningInfo winningInfo = winningDeclared.WinningInfo; Assert.AreEqual(Player0, winningInfo.Winner); Assert.AreEqual(Player3, winningInfo.Feeder); Assert.AreEqual(40, winningInfo.Minipoints); Assert.AreEqual(2, winningInfo.Fan); Assert.AreEqual(2600, winningInfo.Points); Assert.AreEqual(1, winningDeclared.Uradora.Count); Assert.AreEqual(S3p, winningDeclared.Uradora[0].Indicator); Assert.AreEqual(S4, winningDeclared.Uradora[0].Tile); mEventSender.ReceivedWithAnyArgs(1).OnPlayerHandUpdated(null); Assert.AreEqual(new [] { W2p, W3p, W4p, T4p, T5r, T6p, T6p, T7p, T8p, S6p, S8p, FNp, FNp, Claimed(S7p) }, playerHandUpdated.Tiles); Assert.AreEqual(Player0, playerHandUpdated.Player); mEventSender.ReceivedWithAnyArgs(2).OnScoreUpdated(null); Assert.AreEqual(22300, scoreUpdates[0].Score); Assert.AreEqual(+8400, scoreUpdates[0].Delta); Assert.AreEqual(27500, scoreUpdates[3].Score); Assert.AreEqual(-4400, scoreUpdates[3].Delta); } [Test] public void TestRyukyokuFanpai() { const string message = @"{ ""type"":""ryukyoku"",""reason"":""fanpai"", ""tehais"":[ [""5m"",""5m"",""5mr"",""3s"",""3s"",""N"",""N""], [""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?""], [""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?""], [""?"",""?"",""?"",""?""] ], ""tenpais"":[true,false,false,false], ""deltas"":[3000,-1000,-1000,-1000],""scores"":[28000,24000,24000,24000] }"; HandDrawnEventArgs handDrawn = null; mEventSender.OnHandDrawn( Arg.Do<HandDrawnEventArgs>(e => { handDrawn = e; })); var tiles = new IPlayerHand[4]; mEventSender.OnPlayerHandUpdated( Arg.Do<PlayerHandUpdatedEventArgs>(e => { tiles[e.Player.Id] = e.Tiles; })); var scoreUpdates = new ScoreUpdatedEventArgs[4]; mEventSender.OnScoreUpdated( Arg.Do<ScoreUpdatedEventArgs>(e => { scoreUpdates[e.Player.Id] = e; })); mProcessor.Process(MjaiJson.Parse(message)); mEventSender.ReceivedWithAnyArgs(1).OnHandDrawn(null); Assert.AreEqual(DrawHand.Exhaustive, handDrawn.Reason); mEventSender.ReceivedWithAnyArgs(1).OnPlayerHandUpdated(null); Assert.AreEqual(new [] { W5p, W5p, W5r, S3p, S3p, FNp, FNp }, tiles[3]); mEventSender.ReceivedWithAnyArgs(4).OnScoreUpdated(null); Assert.AreEqual(24000, scoreUpdates[0].Score); Assert.AreEqual(-1000, scoreUpdates[0].Delta); Assert.AreEqual(24000, scoreUpdates[1].Score); Assert.AreEqual(-1000, scoreUpdates[1].Delta); Assert.AreEqual(24000, scoreUpdates[2].Score); Assert.AreEqual(-1000, scoreUpdates[2].Delta); Assert.AreEqual(28000, scoreUpdates[3].Score); Assert.AreEqual(+3000, scoreUpdates[3].Delta); } [Test] public void TestRyukyokuKyushukyuhai() { const string message = @"{ ""type"":""ryukyoku"",""reason"":""kyushukyuhai"",""actor"":1, ""tehais"":[ [""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?""], [""1m"",""3m"",""5m"",""9m"",""9p"",""9p"",""1s"",""5sr"",""9s"",""E"", ""S"",""P"",""C"",""7s""], [""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?""], [""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?"",""?""], ], ""tenpais"":[false,false,false,false], ""deltas"":[0,0,0,0],""scores"":[25000,25000,25000,25000] }"; HandDrawnEventArgs handDrawn = null; mEventSender.OnHandDrawn( Arg.Do<HandDrawnEventArgs>(e => { handDrawn = e; })); var tiles = new IPlayerHand[4]; mEventSender.OnPlayerHandUpdated( Arg.Do<PlayerHandUpdatedEventArgs>(e => { tiles[e.Player.Id] = e.Tiles; })); mProcessor.Process(MjaiJson.Parse(message)); mEventSender.ReceivedWithAnyArgs(1).OnHandDrawn(null); Assert.AreEqual(DrawHand.NineTerminalsAndHonors, handDrawn.Reason); mEventSender.ReceivedWithAnyArgs(1).OnPlayerHandUpdated(null); Assert.AreEqual(new [] { W1p, W3p, W5p, W9p, T9p, T9p, S1p, S5r, S9p, FEp, FSp, JPp, JCp, S7p }, tiles[0]); mEventSender.ReceivedWithAnyArgs(0).OnScoreUpdated(null); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text.RegularExpressions; using StructureMap; using LibGit2Sharp; using Branch = LibGit2Sharp.Branch; namespace Sep.Git.Tfs.Core { public class GitRepository : GitHelpers, IGitRepository { private readonly IContainer _container; private readonly Globals _globals; private IDictionary<string, IGitTfsRemote> _cachedRemotes; private Repository _repository; private RemoteConfigConverter _remoteConfigReader; public GitRepository(TextWriter stdout, string gitDir, IContainer container, Globals globals, RemoteConfigConverter remoteConfigReader) : base(stdout, container) { _container = container; _globals = globals; GitDir = gitDir; _repository = new LibGit2Sharp.Repository(GitDir); _remoteConfigReader = remoteConfigReader; } ~GitRepository() { if (_repository != null) _repository.Dispose(); } public GitCommit Commit(LogEntry logEntry) { var parents = logEntry.CommitParents.Select(sha => _repository.Lookup<Commit>(sha)); var commit = _repository.ObjectDatabase.CreateCommit( new Signature(logEntry.AuthorName, logEntry.AuthorEmail, logEntry.Date.ToUniversalTime()), new Signature(logEntry.CommitterName, logEntry.CommitterEmail, logEntry.Date.ToUniversalTime()), logEntry.Log, logEntry.Tree, parents, false); changesetsCache[logEntry.ChangesetId] = commit.Sha; return new GitCommit(commit); } public void UpdateRef(string gitRefName, string shaCommit, string message = null) { if (message == null) _repository.Refs.Add(gitRefName, shaCommit, allowOverwrite: true); else _repository.Refs.Add(gitRefName, shaCommit, _repository.Config.BuildSignature(DateTime.Now), message, true); } public static string ShortToLocalName(string branchName) { return "refs/heads/" + branchName; } public static string ShortToTfsRemoteName(string branchName) { return "refs/remotes/tfs/" + branchName; } public string GitDir { get; set; } public string WorkingCopyPath { get; set; } public string WorkingCopySubdir { get; set; } protected override GitProcess Start(string[] command, Action<ProcessStartInfo> initialize) { return base.Start(command, initialize.And(SetUpPaths)); } private void SetUpPaths(ProcessStartInfo gitCommand) { if (GitDir != null) gitCommand.EnvironmentVariables["GIT_DIR"] = GitDir; if (WorkingCopyPath != null) gitCommand.WorkingDirectory = WorkingCopyPath; if (WorkingCopySubdir != null) gitCommand.WorkingDirectory = Path.Combine(gitCommand.WorkingDirectory, WorkingCopySubdir); } public string GetConfig(string key) { var entry = _repository.Config.Get<string>(key); return entry == null ? null : entry.Value; } public T GetConfig<T>(string key) { return GetConfig(key, default(T)); } public T GetConfig<T>(string key, T defaultValue) { try { var entry = _repository.Config.Get<T>(key); if (entry == null) return defaultValue; return entry.Value; } catch (Exception) { return defaultValue; } } public void SetConfig(string key, string value) { _repository.Config.Set<string>(key, value, ConfigurationLevel.Local); } public IEnumerable<IGitTfsRemote> ReadAllTfsRemotes() { var remotes = GetTfsRemotes().Values; foreach (var remote in remotes) remote.EnsureTfsAuthenticated(); return remotes; } public IGitTfsRemote ReadTfsRemote(string remoteId) { if (!HasRemote(remoteId)) throw new GitTfsException("Unable to locate git-tfs remote with id = " + remoteId) .WithRecommendation("Try using `git tfs bootstrap` to auto-init TFS remotes."); var remote = GetTfsRemotes()[remoteId]; remote.EnsureTfsAuthenticated(); return remote; } private IGitTfsRemote ReadTfsRemote(string tfsUrl, string tfsRepositoryPath) { var allRemotes = GetTfsRemotes(); var matchingRemotes = allRemotes.Values.Where( remote => remote.MatchesUrlAndRepositoryPath(tfsUrl, tfsRepositoryPath)); switch (matchingRemotes.Count()) { case 0: return new DerivedGitTfsRemote(tfsUrl, tfsRepositoryPath); case 1: var remote = matchingRemotes.First(); return remote; default: Trace.WriteLine("More than one remote matched!"); goto case 1; } } public IEnumerable<string> GetGitRemoteBranches(string gitRemote) { gitRemote = gitRemote + "/"; var references = _repository.Branches.Where(b => b.IsRemote && b.Name.StartsWith(gitRemote) && !b.Name.EndsWith("/HEAD")); return references.Select(r => r.Name); } private IDictionary<string, IGitTfsRemote> GetTfsRemotes() { return _cachedRemotes ?? (_cachedRemotes = ReadTfsRemotes()); } public IGitTfsRemote CreateTfsRemote(RemoteInfo remote, string autocrlf = null, string ignorecase = null) { if (HasRemote(remote.Id)) throw new GitTfsException("A remote with id \"" + remote.Id + "\" already exists."); // The autocrlf default (as indicated by a null) is false and is set to override the system-wide setting. // When creating branches we use the empty string to indicate that we do not want to set the value at all. if (autocrlf == null) autocrlf = "false"; if (autocrlf != String.Empty) _repository.Config.Set("core.autocrlf", autocrlf); if (ignorecase != null) _repository.Config.Set("core.ignorecase", ignorecase); foreach (var entry in _remoteConfigReader.Dump(remote)) { if (entry.Value != null) { _repository.Config.Set(entry.Key, entry.Value); } else { _repository.Config.Unset(entry.Key); } } var gitTfsRemote = BuildRemote(remote); gitTfsRemote.EnsureTfsAuthenticated(); return _cachedRemotes[remote.Id] = gitTfsRemote; } public void DeleteTfsRemote(IGitTfsRemote remote) { if (remote == null) throw new GitTfsException("error: the name of the remote to delete is invalid!"); UnsetTfsRemoteConfig(remote.Id); _repository.Refs.Remove(remote.RemoteRef); } private void UnsetTfsRemoteConfig(string remoteId) { foreach (var entry in _remoteConfigReader.Delete(remoteId)) { _repository.Config.Unset(entry.Key); } _cachedRemotes = null; } public void MoveRemote(string oldRemoteName, string newRemoteName) { if (!Reference.IsValidName(ShortToLocalName(oldRemoteName))) throw new GitTfsException("error: the name of the remote to move is invalid!"); if (!Reference.IsValidName(ShortToLocalName(newRemoteName))) throw new GitTfsException("error: the new name of the remote is invalid!"); if (HasRemote(newRemoteName)) throw new GitTfsException(string.Format("error: this remote name \"{0}\" is already used!", newRemoteName)); var oldRemote = ReadTfsRemote(oldRemoteName); if(oldRemote == null) throw new GitTfsException(string.Format("error: the remote \"{0}\" doesn't exist!", oldRemoteName)); var remoteInfo = oldRemote.RemoteInfo; remoteInfo.Id = newRemoteName; CreateTfsRemote(remoteInfo); var newRemote = ReadTfsRemote(newRemoteName); _repository.Refs.Rename(oldRemote.RemoteRef, newRemote.RemoteRef); UnsetTfsRemoteConfig(oldRemoteName); } public Branch RenameBranch(string oldName, string newName) { var branch = _repository.Branches[oldName]; if (branch == null) return null; return _repository.Branches.Rename(branch, newName); } private IDictionary<string, IGitTfsRemote> ReadTfsRemotes() { // does this need to ensuretfsauthenticated? _repository.Config.Set("tfs.touch", "1"); // reload configuration, because `git tfs init` and `git tfs clone` use Process.Start to update the config, so _repository's copy is out of date. return _remoteConfigReader.Load(_repository.Config).Select(x => BuildRemote(x)).ToDictionary(x => x.Id); } private IGitTfsRemote BuildRemote(RemoteInfo remoteInfo) { return _container.With(remoteInfo).With<IGitRepository>(this).GetInstance<IGitTfsRemote>(); } public bool HasRemote(string remoteId) { return GetTfsRemotes().ContainsKey(remoteId); } public bool HasRef(string gitRef) { return _repository.Refs[gitRef] != null; } public void MoveTfsRefForwardIfNeeded(IGitTfsRemote remote) { MoveTfsRefForwardIfNeeded(remote, "HEAD"); } public void MoveTfsRefForwardIfNeeded(IGitTfsRemote remote, string @ref) { long currentMaxChangesetId = remote.MaxChangesetId; var untrackedTfsChangesets = from cs in GetLastParentTfsCommits(@ref) where cs.Remote.Id == remote.Id && cs.ChangesetId > currentMaxChangesetId orderby cs.ChangesetId select cs; foreach (var cs in untrackedTfsChangesets) { // UpdateTfsHead sets tag with TFS changeset id on each commit so we can't just update to latest remote.UpdateTfsHead(cs.GitCommit, cs.ChangesetId); } } public GitCommit GetCommit(string commitish) { return new GitCommit(_repository.Lookup<Commit>(commitish)); } public MergeResult Merge(string commitish) { var commit = _repository.Lookup<Commit>(commitish); if(commit == null) throw new GitTfsException("error: commit '"+ commitish + "' can't be found and merged into!"); return _repository.Merge(commit, _repository.Config.BuildSignature(new DateTimeOffset(DateTime.Now))); } public String GetCurrentCommit() { return _repository.Head.Commits.First().Sha; } public IEnumerable<TfsChangesetInfo> GetLastParentTfsCommits(string head) { var changesets = new List<TfsChangesetInfo>(); var commit = _repository.Lookup<Commit>(head); if (commit == null) return changesets; FindTfsParentCommits(changesets, commit); return changesets; } private void FindTfsParentCommits(List<TfsChangesetInfo> changesets, Commit commit) { var commitsToFollow = new Stack<Commit>(); commitsToFollow.Push(commit); var alreadyVisitedCommits = new HashSet<string>(); while (commitsToFollow.Any()) { commit = commitsToFollow.Pop(); alreadyVisitedCommits.Add(commit.Sha); var changesetInfo = TryParseChangesetInfo(commit.Message, commit.Sha); if (changesetInfo == null) { // If commit was not a TFS commit, continue searching all new parents of the commit // Add parents in reverse order to keep topology (main parent should be treated first!) foreach (var parent in commit.Parents.Where(x => !alreadyVisitedCommits.Contains(x.Sha)).Reverse()) commitsToFollow.Push(parent); } else { changesets.Add(changesetInfo); } } Trace.WriteLine("Commits visited count:" + alreadyVisitedCommits.Count); } public TfsChangesetInfo GetTfsChangesetById(string remoteRef, long changesetId) { var commit = FindCommitByChangesetId(changesetId, remoteRef); if (commit == null) return null; return TryParseChangesetInfo(commit.Message, commit.Sha); } public TfsChangesetInfo GetCurrentTfsCommit() { var currentCommit = _repository.Head.Commits.First(); return TryParseChangesetInfo(currentCommit.Message, currentCommit.Sha); } public TfsChangesetInfo GetTfsCommit(GitCommit commit) { return TryParseChangesetInfo(commit.Message, commit.Sha); } public TfsChangesetInfo GetTfsCommit(string sha) { return GetTfsCommit(GetCommit(sha)); } private TfsChangesetInfo TryParseChangesetInfo(string gitTfsMetaInfo, string commit) { var match = GitTfsConstants.TfsCommitInfoRegex.Match(gitTfsMetaInfo); if (match.Success) { var commitInfo = _container.GetInstance<TfsChangesetInfo>(); commitInfo.Remote = ReadTfsRemote(match.Groups["url"].Value, match.Groups["repository"].Success ? match.Groups["repository"].Value : null); commitInfo.ChangesetId = Convert.ToInt32(match.Groups["changeset"].Value); commitInfo.GitCommit = commit; return commitInfo; } return null; } public IDictionary<string, GitObject> CreateObjectsDictionary() { return new Dictionary<string, GitObject>(StringComparer.InvariantCultureIgnoreCase); } public IDictionary<string, GitObject> GetObjects(string commit, IDictionary<string, GitObject> entries) { if (commit != null) { ParseEntries(entries, _repository.Lookup<Commit>(commit).Tree, commit); } return entries; } public IDictionary<string, GitObject> GetObjects(string commit) { var entries = CreateObjectsDictionary(); return GetObjects(commit, entries); } public IGitTreeBuilder GetTreeBuilder(string commit) { if (commit == null) { return new GitTreeBuilder(_repository.ObjectDatabase); } else { return new GitTreeBuilder(_repository.ObjectDatabase, _repository.Lookup<Commit>(commit).Tree); } } public string GetCommitMessage(string head, string parentCommitish) { var message = new System.Text.StringBuilder(); foreach (Commit comm in _repository.Commits.QueryBy(new CommitFilter { Since = head, Until = parentCommitish })) { // Normalize commit message line endings to CR+LF style, so that message // would be correctly shown in TFS commit dialog. message.AppendLine(NormalizeLineEndings(comm.Message)); } return GitTfsConstants.TfsCommitInfoRegex.Replace(message.ToString(), "").Trim(' ', '\r', '\n'); } private static string NormalizeLineEndings(string input) { return string.IsNullOrEmpty(input) ? input : input.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n"); } private void ParseEntries(IDictionary<string, GitObject> entries, Tree treeInfo, string commit) { var treesToDescend = new Queue<Tree>(new[] {treeInfo}); while (treesToDescend.Any()) { var currentTree = treesToDescend.Dequeue(); foreach (var item in currentTree) { if (item.TargetType == TreeEntryTargetType.Tree) { treesToDescend.Enqueue((Tree)item.Target); } var path = item.Path.Replace('\\', '/'); entries[path] = new GitObject { Mode = item.Mode, Sha = item.Target.Sha, ObjectType = item.TargetType, Path = path, Commit = commit }; } } } public IEnumerable<IGitChangedFile> GetChangedFiles(string from, string to) { using (var diffOutput = CommandOutputPipe("diff-tree", "-r", "-M", "-z", from, to)) { var changes = GitChangeInfo.GetChangedFiles(diffOutput); foreach (var change in changes) { yield return BuildGitChangedFile(change); } } } private IGitChangedFile BuildGitChangedFile(GitChangeInfo change) { return change.ToGitChangedFile(_container.With((IGitRepository) this)); } public bool WorkingCopyHasUnstagedOrUncommitedChanges { get { if (IsBare) return false; return (from entry in _repository.RetrieveStatus() where entry.State != FileStatus.Ignored && entry.State != FileStatus.Untracked select entry).Any(); } } public void CopyBlob(string sha, string outputFile) { Blob blob; var destination = new FileInfo(outputFile); if (!destination.Directory.Exists) destination.Directory.Create(); if ((blob = _repository.Lookup<Blob>(sha)) != null) using (Stream stream = blob.GetContentStream()) using (var outstream = File.Create(destination.FullName)) stream.CopyTo(outstream); } public string AssertValidBranchName(string gitBranchName) { if (!Reference.IsValidName(ShortToLocalName(gitBranchName))) throw new GitTfsException("The name specified for the new git branch is not allowed. Choose another one!"); while (IsRefNameUsed(gitBranchName)) { gitBranchName = "_" + gitBranchName; } return gitBranchName; } private bool IsRefNameUsed(string gitBranchName) { var parts = gitBranchName.Split('/'); var refName = parts.First(); for (int i = 1; i <= parts.Length; i++) { if (HasRef(ShortToLocalName(refName)) || HasRef(ShortToTfsRemoteName(refName))) return true; if (i < parts.Length) refName += '/' + parts[i]; } return false; } public bool CreateBranch(string gitBranchName, string target) { Reference reference; try { reference = _repository.Refs.Add(gitBranchName, target); } catch (Exception) { return false; } return reference != null; } private readonly Dictionary<long, string> changesetsCache = new Dictionary<long, string>(); private bool cacheIsFull = false; public string FindCommitHashByChangesetId(long changesetId) { var commit = FindCommitByChangesetId(changesetId); if (commit == null) return null; return commit.Sha; } private static readonly Regex tfsIdRegex = new Regex("^git-tfs-id: .*;C([0-9]+)\r?$", RegexOptions.Multiline | RegexOptions.Compiled | RegexOptions.RightToLeft); public static bool TryParseChangesetId(string commitMessage, out long changesetId) { var match = tfsIdRegex.Match(commitMessage); if (match.Success) { changesetId = long.Parse(match.Groups[1].Value); return true; } changesetId = 0; return false; } private Commit FindCommitByChangesetId(long changesetId, string remoteRef = null) { Trace.WriteLine("Looking for changeset " + changesetId + " in git repository..."); if (remoteRef == null) { string sha; if (changesetsCache.TryGetValue(changesetId, out sha)) return _repository.Lookup<Commit>(sha); if (cacheIsFull) return null; } var reachableFromRemoteBranches = new CommitFilter { Since = _repository.Branches.Where(p => p.IsRemote), SortBy = CommitSortStrategies.Time }; if (remoteRef != null) reachableFromRemoteBranches.Since = _repository.Branches.Where(p => p.IsRemote && p.CanonicalName.EndsWith(remoteRef)); var commitsFromRemoteBranches = _repository.Commits.QueryBy(reachableFromRemoteBranches); Commit commit = null; foreach (var c in commitsFromRemoteBranches) { long id; if (TryParseChangesetId(c.Message, out id)) { changesetsCache[id] = c.Sha; if (id == changesetId) { commit = c; break; } } } if (remoteRef == null && commit == null) cacheIsFull = true; // repository fully scanned Trace.WriteLine((commit == null) ? " => Commit not found!" : " => Commit found! hash: " + commit.Sha); return commit; } public void CreateTag(string name, string sha, string comment, string Owner, string emailOwner, System.DateTime creationDate) { if (_repository.Tags[name] == null) _repository.ApplyTag(name, sha, new Signature(Owner, emailOwner, new DateTimeOffset(creationDate)), comment); } public void CreateNote(string sha, string content, string owner, string emailOwner, DateTime creationDate) { Signature author = new Signature(owner, emailOwner, creationDate); _repository.Notes.Add(new ObjectId(sha), content, author, author, "commits"); } public void ResetHard(string sha) { _repository.Reset(ResetMode.Hard, sha); } public bool IsBare { get { return _repository.Info.IsBare; } } /// <summary> /// Gets all configured "subtree" remotes which point to the same Tfs URL as the given remote. /// If the given remote is itself a subtree, an empty enumerable is returned. /// </summary> public IEnumerable<IGitTfsRemote> GetSubtrees(IGitTfsRemote owner) { //a subtree remote cannot have subtrees itself. if (owner.IsSubtree) return Enumerable.Empty<IGitTfsRemote>(); return ReadAllTfsRemotes().Where(x => x.IsSubtree && string.Equals(x.OwningRemoteId, owner.Id, StringComparison.InvariantCultureIgnoreCase)); } public void ResetRemote(IGitTfsRemote remoteToReset, string target) { _repository.Refs.UpdateTarget(remoteToReset.RemoteRef, target); } public string GetCurrentBranch() { return _repository.Head.CanonicalName; } public void GarbageCollect(bool auto, string additionalMessage) { try { if (auto) _globals.Repository.CommandNoisy("gc", "--auto"); else _globals.Repository.CommandNoisy("gc"); } catch (Exception e) { Trace.WriteLine(e); realStdout.WriteLine("Warning: `git gc` failed! " + additionalMessage); } } public bool Checkout(string commitish) { try { _repository.Checkout(commitish); return true; } catch (MergeConflictException) { return false; } } public IEnumerable<GitCommit> FindParentCommits(string @from, string to) { var commits = _repository.Commits.QueryBy( new CommitFilter() {Since = @from, Until = to, SortBy = CommitSortStrategies.Reverse, FirstParentOnly = true}) .Select(c=>new GitCommit(c)); var parent = to; foreach (var gitCommit in commits) { if(!gitCommit.Parents.Any(c=>c.Sha == parent)) return new List<GitCommit>(); parent = gitCommit.Sha; } return commits; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.AspNetCore.Razor.Language; using Microsoft.AspNetCore.Razor.Language.Intermediate; using Microsoft.AspNetCore.Razor.Language.Legacy; using Xunit; namespace Microsoft.AspNetCore.Mvc.Razor.Extensions { public class ModelExpressionPassTest { [Fact] public void ModelExpressionPass_NonModelExpressionProperty_Ignored() { // Arrange var codeDocument = CreateDocument(@" @addTagHelper TestTagHelper, TestAssembly <p foo=""17"">"); var tagHelpers = new[] { TagHelperDescriptorBuilder.Create("TestTagHelper", "TestAssembly") .BoundAttributeDescriptor(attribute => attribute .Name("Foo") .TypeName("System.Int32")) .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")) .Build() }; var engine = CreateEngine(tagHelpers); var pass = new ModelExpressionPass() { Engine = engine, }; var irDocument = CreateIRDocument(engine, codeDocument); // Act pass.Execute(codeDocument, irDocument); // Assert var tagHelper = FindTagHelperNode(irDocument); var setProperty = tagHelper.Children.OfType<TagHelperPropertyIntermediateNode>().Single(); var token = Assert.IsAssignableFrom<IntermediateToken>(Assert.Single(setProperty.Children)); Assert.True(token.IsCSharp); Assert.Equal("17", token.Content); } [Fact] public void ModelExpressionPass_ModelExpressionProperty_SimpleExpression() { // Arrange // Using \r\n here because we verify line mappings var codeDocument = CreateDocument( "@addTagHelper TestTagHelper, TestAssembly\r\n<p foo=\"Bar\">"); var tagHelpers = new[] { TagHelperDescriptorBuilder.Create("TestTagHelper", "TestAssembly") .BoundAttributeDescriptor(attribute => attribute .Name("Foo") .TypeName("Microsoft.AspNetCore.Mvc.ViewFeatures.ModelExpression")) .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")) .Build() }; var engine = CreateEngine(tagHelpers); var pass = new ModelExpressionPass() { Engine = engine, }; var irDocument = CreateIRDocument(engine, codeDocument); // Act pass.Execute(codeDocument, irDocument); // Assert var tagHelper = FindTagHelperNode(irDocument); var setProperty = tagHelper.Children.OfType<TagHelperPropertyIntermediateNode>().Single(); var expression = Assert.IsType<CSharpExpressionIntermediateNode>(Assert.Single(setProperty.Children)); Assert.Equal("ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Bar)", GetCSharpContent(expression)); var originalNode = Assert.IsAssignableFrom<IntermediateToken>(expression.Children[2]); Assert.Equal(TokenKind.CSharp, originalNode.Kind); Assert.Equal("Bar", originalNode.Content); Assert.Equal(new SourceSpan("test.cshtml", 51, 1, 8, 3), originalNode.Source.Value); } [Fact] public void ModelExpressionPass_ModelExpressionProperty_ComplexExpression() { // Arrange // Using \r\n here because we verify line mappings var codeDocument = CreateDocument( "@addTagHelper TestTagHelper, TestAssembly\r\n<p foo=\"@Bar\">"); var tagHelpers = new[] { TagHelperDescriptorBuilder.Create("TestTagHelper", "TestAssembly") .BoundAttributeDescriptor(attribute => attribute .Name("Foo") .TypeName("Microsoft.AspNetCore.Mvc.ViewFeatures.ModelExpression")) .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")) .Build() }; var engine = CreateEngine(tagHelpers); var pass = new ModelExpressionPass() { Engine = engine, }; var irDocument = CreateIRDocument(engine, codeDocument); // Act pass.Execute(codeDocument, irDocument); // Assert var tagHelper = FindTagHelperNode(irDocument); var setProperty = tagHelper.Children.OfType<TagHelperPropertyIntermediateNode>().Single(); var expression = Assert.IsType<CSharpExpressionIntermediateNode>(Assert.Single(setProperty.Children)); Assert.Equal("ModelExpressionProvider.CreateModelExpression(ViewData, __model => Bar)", GetCSharpContent(expression)); var originalNode = Assert.IsAssignableFrom<IntermediateToken>(expression.Children[1]); Assert.Equal(TokenKind.CSharp, originalNode.Kind); Assert.Equal("Bar", originalNode.Content); Assert.Equal(new SourceSpan("test.cshtml", 52, 1, 9, 3), originalNode.Source.Value); } private RazorCodeDocument CreateDocument(string content) { var source = RazorSourceDocument.Create(content, "test.cshtml"); return RazorCodeDocument.Create(source); } private RazorEngine CreateEngine(params TagHelperDescriptor[] tagHelpers) { return RazorProjectEngine.Create(b => { b.Features.Add(new TestTagHelperFeature(tagHelpers)); }).Engine; } private DocumentIntermediateNode CreateIRDocument(RazorEngine engine, RazorCodeDocument codeDocument) { for (var i = 0; i < engine.Phases.Count; i++) { var phase = engine.Phases[i]; phase.Execute(codeDocument); if (phase is IRazorDirectiveClassifierPhase) { break; } } var irNode = codeDocument.GetDocumentIntermediateNode(); irNode.DocumentKind = MvcViewDocumentClassifierPass.MvcViewDocumentKind; return irNode; } private TagHelperIntermediateNode FindTagHelperNode(IntermediateNode node) { var visitor = new TagHelperNodeVisitor(); visitor.Visit(node); return visitor.Node; } private string GetCSharpContent(IntermediateNode node) { var builder = new StringBuilder(); for (var i = 0; i < node.Children.Count; i++) { var child = node.Children[i] as IntermediateToken; if (child.Kind == TokenKind.CSharp) { builder.Append(child.Content); } } return builder.ToString(); } private class TagHelperNodeVisitor : IntermediateNodeWalker { public TagHelperIntermediateNode Node { get; set; } public override void VisitTagHelper(TagHelperIntermediateNode node) { Node = node; } } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Syndication { using System; using System.Diagnostics; using System.Globalization; using System.Runtime; using System.Runtime.Serialization; using System.ServiceModel.Diagnostics; using System.Xml; using DiagnosticUtility = System.ServiceModel.DiagnosticUtility; using System.Runtime.CompilerServices; [TypeForwardedFrom("System.ServiceModel.Web, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] [DataContract] public abstract class SyndicationFeedFormatter { SyndicationFeed feed; protected SyndicationFeedFormatter() { this.feed = null; } protected SyndicationFeedFormatter(SyndicationFeed feedToWrite) { if (feedToWrite == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("feedToWrite"); } this.feed = feedToWrite; } public SyndicationFeed Feed { get { return this.feed; } } public abstract string Version { get; } public abstract bool CanRead(XmlReader reader); public abstract void ReadFrom(XmlReader reader); public override string ToString() { return String.Format(CultureInfo.CurrentCulture, "{0}, SyndicationVersion={1}", this.GetType(), this.Version); } public abstract void WriteTo(XmlWriter writer); internal static protected SyndicationCategory CreateCategory(SyndicationFeed feed) { if (feed == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("feed"); } return GetNonNullValue<SyndicationCategory>(feed.CreateCategory(), SR.FeedCreatedNullCategory); } internal static protected SyndicationCategory CreateCategory(SyndicationItem item) { if (item == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item"); } return GetNonNullValue<SyndicationCategory>(item.CreateCategory(), SR.ItemCreatedNullCategory); } internal static protected SyndicationItem CreateItem(SyndicationFeed feed) { if (feed == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("feed"); } return GetNonNullValue<SyndicationItem>(feed.CreateItem(), SR.FeedCreatedNullItem); } internal static protected SyndicationLink CreateLink(SyndicationFeed feed) { if (feed == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("feed"); } return GetNonNullValue<SyndicationLink>(feed.CreateLink(), SR.FeedCreatedNullPerson); } internal static protected SyndicationLink CreateLink(SyndicationItem item) { if (item == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item"); } return GetNonNullValue<SyndicationLink>(item.CreateLink(), SR.ItemCreatedNullPerson); } internal static protected SyndicationPerson CreatePerson(SyndicationFeed feed) { if (feed == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("feed"); } return GetNonNullValue<SyndicationPerson>(feed.CreatePerson(), SR.FeedCreatedNullPerson); } internal static protected SyndicationPerson CreatePerson(SyndicationItem item) { if (item == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item"); } return GetNonNullValue<SyndicationPerson>(item.CreatePerson(), SR.ItemCreatedNullPerson); } internal static protected void LoadElementExtensions(XmlReader reader, SyndicationFeed feed, int maxExtensionSize) { if (feed == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("feed"); } feed.LoadElementExtensions(reader, maxExtensionSize); } internal static protected void LoadElementExtensions(XmlReader reader, SyndicationItem item, int maxExtensionSize) { if (item == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item"); } item.LoadElementExtensions(reader, maxExtensionSize); } internal static protected void LoadElementExtensions(XmlReader reader, SyndicationCategory category, int maxExtensionSize) { if (category == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("category"); } category.LoadElementExtensions(reader, maxExtensionSize); } internal static protected void LoadElementExtensions(XmlReader reader, SyndicationLink link, int maxExtensionSize) { if (link == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("link"); } link.LoadElementExtensions(reader, maxExtensionSize); } internal static protected void LoadElementExtensions(XmlReader reader, SyndicationPerson person, int maxExtensionSize) { if (person == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("person"); } person.LoadElementExtensions(reader, maxExtensionSize); } internal static protected bool TryParseAttribute(string name, string ns, string value, SyndicationFeed feed, string version) { if (feed == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("feed"); } if (FeedUtils.IsXmlns(name, ns)) { return true; } return feed.TryParseAttribute(name, ns, value, version); } internal static protected bool TryParseAttribute(string name, string ns, string value, SyndicationItem item, string version) { if (item == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item"); } if (FeedUtils.IsXmlns(name, ns)) { return true; } return item.TryParseAttribute(name, ns, value, version); } internal static protected bool TryParseAttribute(string name, string ns, string value, SyndicationCategory category, string version) { if (category == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("category"); } if (FeedUtils.IsXmlns(name, ns)) { return true; } return category.TryParseAttribute(name, ns, value, version); } internal static protected bool TryParseAttribute(string name, string ns, string value, SyndicationLink link, string version) { if (link == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("link"); } if (FeedUtils.IsXmlns(name, ns)) { return true; } return link.TryParseAttribute(name, ns, value, version); } internal static protected bool TryParseAttribute(string name, string ns, string value, SyndicationPerson person, string version) { if (person == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("person"); } if (FeedUtils.IsXmlns(name, ns)) { return true; } return person.TryParseAttribute(name, ns, value, version); } internal static protected bool TryParseContent(XmlReader reader, SyndicationItem item, string contentType, string version, out SyndicationContent content) { return item.TryParseContent(reader, contentType, version, out content); } internal static protected bool TryParseElement(XmlReader reader, SyndicationFeed feed, string version) { if (feed == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("feed"); } return feed.TryParseElement(reader, version); } internal static protected bool TryParseElement(XmlReader reader, SyndicationItem item, string version) { if (item == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item"); } return item.TryParseElement(reader, version); } internal static protected bool TryParseElement(XmlReader reader, SyndicationCategory category, string version) { if (category == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("category"); } return category.TryParseElement(reader, version); } internal static protected bool TryParseElement(XmlReader reader, SyndicationLink link, string version) { if (link == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("link"); } return link.TryParseElement(reader, version); } internal static protected bool TryParseElement(XmlReader reader, SyndicationPerson person, string version) { if (person == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("person"); } return person.TryParseElement(reader, version); } internal static protected void WriteAttributeExtensions(XmlWriter writer, SyndicationFeed feed, string version) { if (feed == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("feed"); } feed.WriteAttributeExtensions(writer, version); } internal static protected void WriteAttributeExtensions(XmlWriter writer, SyndicationItem item, string version) { if (item == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item"); } item.WriteAttributeExtensions(writer, version); } internal static protected void WriteAttributeExtensions(XmlWriter writer, SyndicationCategory category, string version) { if (category == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("category"); } category.WriteAttributeExtensions(writer, version); } internal static protected void WriteAttributeExtensions(XmlWriter writer, SyndicationLink link, string version) { if (link == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("link"); } link.WriteAttributeExtensions(writer, version); } internal static protected void WriteAttributeExtensions(XmlWriter writer, SyndicationPerson person, string version) { if (person == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("person"); } person.WriteAttributeExtensions(writer, version); } internal static protected void WriteElementExtensions(XmlWriter writer, SyndicationFeed feed, string version) { if (feed == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("feed"); } feed.WriteElementExtensions(writer, version); } internal static protected void WriteElementExtensions(XmlWriter writer, SyndicationItem item, string version) { if (item == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item"); } item.WriteElementExtensions(writer, version); } internal static protected void WriteElementExtensions(XmlWriter writer, SyndicationCategory category, string version) { if (category == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("category"); } category.WriteElementExtensions(writer, version); } internal static protected void WriteElementExtensions(XmlWriter writer, SyndicationLink link, string version) { if (link == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("link"); } link.WriteElementExtensions(writer, version); } internal static protected void WriteElementExtensions(XmlWriter writer, SyndicationPerson person, string version) { if (person == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("person"); } person.WriteElementExtensions(writer, version); } internal protected virtual void SetFeed(SyndicationFeed feed) { if (feed == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("feed"); } this.feed = feed; } internal static void CloseBuffer(XmlBuffer buffer, XmlDictionaryWriter extWriter) { if (buffer == null) { return; } extWriter.WriteEndElement(); buffer.CloseSection(); buffer.Close(); } internal static void CreateBufferIfRequiredAndWriteNode(ref XmlBuffer buffer, ref XmlDictionaryWriter extWriter, XmlReader reader, int maxExtensionSize) { if (buffer == null) { buffer = new XmlBuffer(maxExtensionSize); extWriter = buffer.OpenSection(XmlDictionaryReaderQuotas.Max); extWriter.WriteStartElement(Rss20Constants.ExtensionWrapperTag); } extWriter.WriteNode(reader, false); } internal static SyndicationFeed CreateFeedInstance(Type feedType) { if (feedType.Equals(typeof(SyndicationFeed))) { return new SyndicationFeed(); } else { return (SyndicationFeed) Activator.CreateInstance(feedType); } } internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationFeed feed) { if (feed == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("feed"); } CloseBuffer(buffer, writer); feed.LoadElementExtensions(buffer); } internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationItem item) { if (item == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item"); } CloseBuffer(buffer, writer); item.LoadElementExtensions(buffer); } internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationCategory category) { if (category == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("category"); } CloseBuffer(buffer, writer); category.LoadElementExtensions(buffer); } internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationLink link) { if (link == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("link"); } CloseBuffer(buffer, writer); link.LoadElementExtensions(buffer); } internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationPerson person) { if (person == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("person"); } CloseBuffer(buffer, writer); person.LoadElementExtensions(buffer); } internal static void MoveToStartElement(XmlReader reader) { Fx.Assert(reader != null, "reader != null"); if (!reader.IsStartElement()) { XmlExceptionHelper.ThrowStartElementExpected(XmlDictionaryReader.CreateDictionaryReader(reader)); } } internal static void TraceFeedReadBegin() { if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SyndicationReadFeedBegin, SR.GetString(SR.TraceCodeSyndicationFeedReadBegin)); } } internal static void TraceFeedReadEnd() { if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SyndicationReadFeedEnd, SR.GetString(SR.TraceCodeSyndicationFeedReadEnd)); } } internal static void TraceFeedWriteBegin() { if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SyndicationWriteFeedBegin, SR.GetString(SR.TraceCodeSyndicationFeedWriteBegin)); } } internal static void TraceFeedWriteEnd() { if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SyndicationWriteFeedEnd, SR.GetString(SR.TraceCodeSyndicationFeedWriteEnd)); } } internal static void TraceItemReadBegin() { if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SyndicationReadItemBegin, SR.GetString(SR.TraceCodeSyndicationItemReadBegin)); } } internal static void TraceItemReadEnd() { if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SyndicationReadItemEnd, SR.GetString(SR.TraceCodeSyndicationItemReadEnd)); } } internal static void TraceItemWriteBegin() { if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SyndicationWriteItemBegin, SR.GetString(SR.TraceCodeSyndicationItemWriteBegin)); } } internal static void TraceItemWriteEnd() { if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SyndicationWriteItemEnd, SR.GetString(SR.TraceCodeSyndicationItemWriteEnd)); } } internal static void TraceSyndicationElementIgnoredOnRead(XmlReader reader) { if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.SyndicationProtocolElementIgnoredOnRead, SR.GetString(SR.TraceCodeSyndicationProtocolElementIgnoredOnRead, reader.NodeType, reader.LocalName, reader.NamespaceURI)); } } protected abstract SyndicationFeed CreateFeedInstance(); static T GetNonNullValue<T>(T value, string errorMsg) { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(errorMsg))); } return value; } static class XmlExceptionHelper { static void ThrowXmlException(XmlDictionaryReader reader, string res, string arg1) { string s = SR.GetString(res, arg1); IXmlLineInfo lineInfo = reader as IXmlLineInfo; if (lineInfo != null && lineInfo.HasLineInfo()) { s += " " + SR.GetString(SR.XmlLineInfo, lineInfo.LineNumber, lineInfo.LinePosition); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(s)); } static string GetName(string prefix, string localName) { if (prefix.Length == 0) return localName; else return string.Concat(prefix, ":", localName); } static string GetWhatWasFound(XmlDictionaryReader reader) { if (reader.EOF) return SR.GetString(SR.XmlFoundEndOfFile); switch (reader.NodeType) { case XmlNodeType.Element: return SR.GetString(SR.XmlFoundElement, GetName(reader.Prefix, reader.LocalName), reader.NamespaceURI); case XmlNodeType.EndElement: return SR.GetString(SR.XmlFoundEndElement, GetName(reader.Prefix, reader.LocalName), reader.NamespaceURI); case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: return SR.GetString(SR.XmlFoundText, reader.Value); case XmlNodeType.Comment: return SR.GetString(SR.XmlFoundComment, reader.Value); case XmlNodeType.CDATA: return SR.GetString(SR.XmlFoundCData, reader.Value); } return SR.GetString(SR.XmlFoundNodeType, reader.NodeType); } static public void ThrowStartElementExpected(XmlDictionaryReader reader) { ThrowXmlException(reader, SR.XmlStartElementExpected, GetWhatWasFound(reader)); } } } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.Linq; using NLog.Internal; using Xunit; namespace NLog.UnitTests.Internal { public class EnumHelpersTests : NLogTestBase { enum TestEnum { Foo, bar, } #region tryparse - no ignorecase parameter [Fact] public void EnumParse1() { TestEnumParseCaseSentisive("Foo", TestEnum.Foo, true); } [Fact] public void EnumParse2() { TestEnumParseCaseSentisive("foo", TestEnum.Foo, false); } [Fact] public void EnumParseDefault() { TestEnumParseCaseSentisive("BAR", TestEnum.Foo, false); } [Fact] public void EnumParseDefault2() { TestEnumParseCaseSentisive("x", TestEnum.Foo, false); } [Fact] public void EnumParseBar() { TestEnumParseCaseSentisive("bar", TestEnum.bar, true); } [Fact] public void EnumParseBar2() { TestEnumParseCaseSentisive(" bar ", TestEnum.bar, true); } [Fact] public void EnumParseBar3() { TestEnumParseCaseSentisive(" \r\nbar ", TestEnum.bar, true); } [Fact] public void EnumParse_null() { TestEnumParseCaseSentisive(null, TestEnum.Foo, false); } [Fact] public void EnumParse_emptystring() { TestEnumParseCaseSentisive(string.Empty, TestEnum.Foo, false); } [Fact] public void EnumParse_whitespace() { TestEnumParseCaseSentisive(" ", TestEnum.Foo, false); } [Fact] public void EnumParse_ArgumentException() { double result; Assert.Throws<ArgumentException>(() => EnumHelpers.TryParse("not enum", out result)); } [Fact] public void EnumParse_null_ArgumentException() { //even with null, first ArgumentException double result; Assert.Throws<ArgumentException>(() => EnumHelpers.TryParse(null, out result)); } #endregion #region tryparse - ignorecase parameter: false [Fact] public void EnumParse1_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam("Foo", false, TestEnum.Foo, true); } [Fact] public void EnumParse2_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam("foo", false, TestEnum.Foo, false); } [Fact] public void EnumParseDefault_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam("BAR", false, TestEnum.Foo, false); } [Fact] public void EnumParseDefault2_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam("x", false, TestEnum.Foo, false); } [Fact] public void EnumParseBar_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam("bar", false, TestEnum.bar, true); } [Fact] public void EnumParseBar2_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam(" bar ", false, TestEnum.bar, true); } [Fact] public void EnumParseBar3_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam(" \r\nbar ", false, TestEnum.bar, true); } [Fact] public void EnumParse_null_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam(null, false, TestEnum.Foo, false); } [Fact] public void EnumParse_emptystring_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam(string.Empty, false, TestEnum.Foo, false); } [Fact] public void EnumParse_whitespace_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam(" ", false, TestEnum.Foo, false); } [Fact] public void EnumParse_ArgumentException_ignoreCaseFalse() { double result; Assert.Throws<ArgumentException>(() => EnumHelpers.TryParse("not enum", false, out result)); } [Fact] public void EnumParse_null_ArgumentException_ignoreCaseFalse() { //even with null, first ArgumentException double result; Assert.Throws<ArgumentException>(() => EnumHelpers.TryParse(null, false, out result)); } #endregion #region tryparse - ignorecase parameter: true [Fact] public void EnumParse1_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam("Foo", true, TestEnum.Foo, true); } [Fact] public void EnumParse2_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam("foo", true, TestEnum.Foo, true); } [Fact] public void EnumParseDefault_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam("BAR", true, TestEnum.bar, true); } [Fact] public void EnumParseDefault2_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam("x", true, TestEnum.Foo, false); } [Fact] public void EnumParseBar_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam("bar", true, TestEnum.bar, true); } [Fact] public void EnumParseBar2_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam(" bar ", true, TestEnum.bar, true); } [Fact] public void EnumParseBar3_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam(" \r\nbar ", true, TestEnum.bar, true); } [Fact] public void EnumParse_null_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam(null, true, TestEnum.Foo, false); } [Fact] public void EnumParse_emptystring_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam(string.Empty, true, TestEnum.Foo, false); } [Fact] public void EnumParse_whitespace_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam(" ", true, TestEnum.Foo, false); } [Fact] public void EnumParse_ArgumentException_ignoreCaseTrue() { double result; Assert.Throws<ArgumentException>(() => EnumHelpers.TryParse("not enum", true, out result)); } [Fact] public void EnumParse_null_ArgumentException_ignoreCaseTrue() { //even with null, first ArgumentException double result; Assert.Throws<ArgumentException>(() => EnumHelpers.TryParse(null, true, out result)); } #endregion #region helpers private static void TestEnumParseCaseSentisive(string value, TestEnum expected, bool expectedReturn) { TestEnum result; var returnResult = EnumHelpers.TryParse(value, out result); Assert.Equal(expected, result); Assert.Equal(expectedReturn, returnResult); } private static void TestEnumParseCaseIgnoreCaseParam(string value, bool ignoreCase, TestEnum expected, bool expectedReturn) { TestEnum result; var returnResult = EnumHelpers.TryParse(value, ignoreCase, out result); Assert.Equal(expected, result); Assert.Equal(expectedReturn, returnResult); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security.Cryptography; using System.IO; using System.Runtime.CompilerServices; using System.Threading; using Internal.NativeCrypto; namespace System.Security.Cryptography { public sealed partial class RSACryptoServiceProvider : RSA, ICspAsymmetricAlgorithm { private int _keySize; private CspParameters _parameters; private bool _randomKeyContainer; private SafeKeyHandle _safeKeyHandle; private SafeProvHandle _safeProvHandle; private static volatile CspProviderFlags s_UseMachineKeyStore = 0; public RSACryptoServiceProvider() : this(0, new CspParameters(CapiHelper.DefaultRsaProviderType, null, null, s_UseMachineKeyStore), true) { } public RSACryptoServiceProvider(int dwKeySize) : this(dwKeySize, new CspParameters(CapiHelper.DefaultRsaProviderType, null, null, s_UseMachineKeyStore), false) { } public RSACryptoServiceProvider(int dwKeySize, CspParameters parameters) : this(dwKeySize, parameters, false) { } public RSACryptoServiceProvider(CspParameters parameters) : this(0, parameters, true) { } private RSACryptoServiceProvider(int keySize, CspParameters parameters, bool useDefaultKeySize) { if (keySize < 0) { throw new ArgumentOutOfRangeException("dwKeySize", "ArgumentOutOfRange_NeedNonNegNum"); } _parameters = CapiHelper.SaveCspParameters(CapiHelper.CspAlgorithmType.Rsa, parameters, s_UseMachineKeyStore, ref _randomKeyContainer); _legalKeySizesValue = new KeySizes[] { new KeySizes(384, 16384, 8) }; _keySize = useDefaultKeySize ? 1024 : keySize; // If this is not a random container we generate, create it eagerly // in the constructor so we can report any errors now. if (!_randomKeyContainer) { GetKeyPair(); } } /// <summary> /// Retreives the key pair /// </summary> private void GetKeyPair() { if (_safeKeyHandle == null) { lock (this) { if (_safeKeyHandle == null) { // We only attempt to generate a random key on desktop runtimes because the CoreCLR // RSA surface area is limited to simply verifying signatures. Since generating a // random key to verify signatures will always lead to failure (unless we happend to // win the lottery and randomly generate the signing key ...), there is no need // to add this functionality to CoreCLR at this point. CapiHelper.GetKeyPairHelper(CapiHelper.CspAlgorithmType.Rsa, _parameters, _randomKeyContainer, _keySize, ref _safeProvHandle, ref _safeKeyHandle); } } } } /// <summary> /// CspKeyContainerInfo property /// </summary> public CspKeyContainerInfo CspKeyContainerInfo { get { GetKeyPair(); return new CspKeyContainerInfo(_parameters, _randomKeyContainer); } } /// <summary> /// _keySize property /// </summary> public override int KeySize { get { GetKeyPair(); byte[] keySize = (byte[])CapiHelper.GetKeyParameter(_safeKeyHandle, Constants.CLR_KEYLEN); _keySize = (keySize[0] | (keySize[1] << 8) | (keySize[2] << 16) | (keySize[3] << 24)); return _keySize; } } /// <summary> /// get set Persisted key in CSP /// </summary> public bool PersistKeyInCsp { get { if (_safeProvHandle == null) { lock (this) { if (_safeProvHandle == null) { _safeProvHandle = CapiHelper.CreateProvHandle(_parameters, _randomKeyContainer); } } } return CapiHelper.GetPersistKeyInCsp(_safeProvHandle); } set { bool oldPersistKeyInCsp = this.PersistKeyInCsp; if (value == oldPersistKeyInCsp) { return; // Do nothing } CapiHelper.SetPersistKeyInCsp(_safeProvHandle, value); } } /// <summary> /// Gets the information of key if it is a public key /// </summary> public bool PublicOnly { get { GetKeyPair(); byte[] publicKey = (byte[])CapiHelper.GetKeyParameter(_safeKeyHandle, Constants.CLR_PUBLICKEYONLY); return (publicKey[0] == 1); } } /// <summary> /// MachineKey store properties /// </summary> public static bool UseMachineKeyStore { get { return (s_UseMachineKeyStore == CspProviderFlags.UseMachineKeyStore); } set { s_UseMachineKeyStore = (value ? CspProviderFlags.UseMachineKeyStore : 0); } } /// <summary> /// Decrypt raw data, generally used for decrypting symmetric key material /// </summary> /// <param name="rgb">encrypted data</param> /// <param name="fOAEP">true to use OAEP padding (PKCS #1 v2), false to use PKCS #1 type 2 padding</param> /// <returns>decrypted data</returns> public byte[] Decrypt(byte[] rgb, bool fOAEP) { if (rgb == null) { throw new ArgumentNullException("rgb"); } GetKeyPair(); // size check -- must be at most the modulus size if (rgb.Length > (KeySize / 8)) { throw new CryptographicException(SR.Format(SR.Cryptography_Padding_DecDataTooBig, Convert.ToString(KeySize / 8))); } byte[] decryptedKey = null; CapiHelper.DecryptKey(_safeKeyHandle, rgb, rgb.Length, fOAEP, out decryptedKey); return decryptedKey; } /// <summary> /// Dispose the key handles /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed) { _safeKeyHandle.Dispose(); } if (_safeProvHandle != null && !_safeProvHandle.IsClosed) { _safeProvHandle.Dispose(); } } /// <summary> /// Encrypt raw data, generally used for encrypting symmetric key material. /// </summary> /// <remarks> /// This method can only encrypt (keySize - 88 bits) of data, so should not be used for encrypting /// arbitrary byte arrays. Instead, encrypt a symmetric key with this method, and use the symmetric /// key to encrypt the sensitive data. /// </remarks> /// <param name="rgb">raw data to encryt</param> /// <param name="fOAEP">true to use OAEP padding (PKCS #1 v2), false to use PKCS #1 type 2 padding</param> /// <returns>Encrypted key</returns> public byte[] Encrypt(byte[] rgb, bool fOAEP) { if (rgb == null) { throw new ArgumentNullException("rgb"); } GetKeyPair(); byte[] encryptedKey = null; CapiHelper.EncryptKey(_safeKeyHandle, rgb, rgb.Length, fOAEP, ref encryptedKey); return encryptedKey; } /// <summary> ///Exports a blob containing the key information associated with an RSACryptoServiceProvider object. /// </summary> public byte[] ExportCspBlob(bool includePrivateParameters) { GetKeyPair(); return CapiHelper.ExportKeyBlob(includePrivateParameters, _safeKeyHandle); } /// <summary> /// Exports the RSAParameters /// </summary> public override RSAParameters ExportParameters(bool includePrivateParameters) { GetKeyPair(); byte[] cspBlob = ExportCspBlob(includePrivateParameters); return cspBlob.ToRSAParameters(includePrivateParameters); } /// <summary> /// This method helps Acquire the default CSP and avoids the need for static SafeProvHandle /// in CapiHelper class /// </summary> /// <param name="safeProvHandle"> SafeProvHandle. Intialized if successful</param> /// <returns>does not return. AcquireCSP throw exception</returns> private void AcquireSafeProviderHandle(ref SafeProvHandle safeProvHandle) { CapiHelper.AcquireCsp(new CspParameters(CapiHelper.DefaultRsaProviderType), ref safeProvHandle); } /// <summary> /// Imports a blob that represents RSA key information /// </summary> /// <param name="keyBlob"></param> public void ImportCspBlob(byte[] keyBlob) { // Free the current key handle if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed) { _safeKeyHandle.Dispose(); _safeKeyHandle = null; } _safeKeyHandle = SafeKeyHandle.InvalidHandle; if (IsPublic(keyBlob)) { SafeProvHandle safeProvHandleTemp = SafeProvHandle.InvalidHandle; AcquireSafeProviderHandle(ref safeProvHandleTemp); CapiHelper.ImportKeyBlob(safeProvHandleTemp, (CspProviderFlags)0, keyBlob, ref _safeKeyHandle); _safeProvHandle = safeProvHandleTemp; } else { if (_safeProvHandle == null) { _safeProvHandle = CapiHelper.CreateProvHandle(_parameters, _randomKeyContainer); } CapiHelper.ImportKeyBlob(_safeProvHandle, _parameters.Flags, keyBlob, ref _safeKeyHandle); } } /// <summary> /// Imports the specified RSAParameters /// </summary> public override void ImportParameters(RSAParameters parameters) { // Free the current key handle if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed) { _safeKeyHandle.Dispose(); _safeKeyHandle = null; } _safeKeyHandle = SafeKeyHandle.InvalidHandle; byte[] keyBlob = parameters.ToKeyBlob(CapiHelper.CALG_RSA_KEYX); ImportCspBlob(keyBlob); return; } /// <summary> /// Computes the hash value of a subset of the specified byte array using the specified hash algorithm, and signs the resulting hash value. /// </summary> /// <param name="buffer">The input data for which to compute the hash</param> /// <param name="offset">The offset into the array from which to begin using data</param> /// <param name="count">The number of bytes in the array to use as data. </param> /// <param name="halg">The hash algorithm to use to create the hash value. </param> /// <returns>The RSA signature for the specified data.</returns> public byte[] SignData(byte[] buffer, int offset, int count, Object halg) { int calgHash = CapiHelper.ObjToHashAlgId(halg); HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg); byte[] hashVal = hash.ComputeHash(buffer, offset, count); return SignHash(hashVal, calgHash); } /// <summary> /// Computes the hash value of a subset of the specified byte array using the specified hash algorithm, and signs the resulting hash value. /// </summary> /// <param name="buffer">The input data for which to compute the hash</param> /// <param name="halg">The hash algorithm to use to create the hash value. </param> /// <returns>The RSA signature for the specified data.</returns> public byte[] SignData(byte[] buffer, Object halg) { int calgHash = CapiHelper.ObjToHashAlgId(halg); HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg); byte[] hashVal = hash.ComputeHash(buffer); return SignHash(hashVal, calgHash); } /// <summary> /// Computes the hash value of a subset of the specified byte array using the specified hash algorithm, and signs the resulting hash value. /// </summary> /// <param name="inputStream">The input data for which to compute the hash</param> /// <param name="halg">The hash algorithm to use to create the hash value. </param> /// <returns>The RSA signature for the specified data.</returns> public byte[] SignData(Stream inputStream, Object halg) { int calgHash = CapiHelper.ObjToHashAlgId(halg); HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg); byte[] hashVal = hash.ComputeHash(inputStream); return SignHash(hashVal, calgHash); } /// <summary> /// Computes the hash value of a subset of the specified byte array using the specified hash algorithm, and signs the resulting hash value. /// </summary> /// <param name="rgbHash">The input data for which to compute the hash</param> /// <param name="str">The hash algorithm to use to create the hash value. </param> /// <returns>The RSA signature for the specified data.</returns> public byte[] SignHash(byte[] rgbHash, string str) { if (rgbHash == null) throw new ArgumentNullException("rgbHash"); if (PublicOnly) throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); int calgHash = CapiHelper.NameOrOidToHashAlgId(str); return SignHash(rgbHash, calgHash); } /// <summary> /// Computes the hash value of a subset of the specified byte array using the specified hash algorithm, and signs the resulting hash value. /// </summary> /// <param name="rgbHash">The input data for which to compute the hash</param> /// <param name="calgHash">The hash algorithm to use to create the hash value. </param> /// <returns>The RSA signature for the specified data.</returns> private byte[] SignHash(byte[] rgbHash, int calgHash) { Debug.Assert(rgbHash != null); GetKeyPair(); return CapiHelper.SignValue(_safeProvHandle, _safeKeyHandle, _parameters.KeyNumber, CapiHelper.CALG_RSA_SIGN, calgHash, rgbHash); } /// <summary> /// Verifies the signature of a hash value. /// </summary> public bool VerifyData(byte[] buffer, object halg, byte[] signature) { int calgHash = CapiHelper.ObjToHashAlgId(halg); HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg); byte[] hashVal = hash.ComputeHash(buffer); return VerifyHash(hashVal, calgHash, signature); } /// <summary> /// Verifies the signature of a hash value. /// </summary> public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature) { if (rgbHash == null) throw new ArgumentNullException("rgbHash"); if (rgbSignature == null) throw new ArgumentNullException("rgbSignature"); int calgHash = CapiHelper.NameOrOidToHashAlgId(str); return VerifyHash(rgbHash, calgHash, rgbSignature); } /// <summary> /// Verifies the signature of a hash value. /// </summary> private bool VerifyHash(byte[] rgbHash, int calgHash, byte[] rgbSignature) { GetKeyPair(); return CapiHelper.VerifySign(_safeProvHandle, _safeKeyHandle, CapiHelper.CALG_RSA_SIGN, calgHash, rgbHash, rgbSignature); } /// <summary> /// find whether an RSA key blob is public. /// </summary> private static bool IsPublic(byte[] keyBlob) { if (keyBlob == null) { throw new ArgumentNullException("keyBlob"); } // The CAPI RSA public key representation consists of the following sequence: // - BLOBHEADER // - RSAPUBKEY // The first should be PUBLICKEYBLOB and magic should be RSA_PUB_MAGIC "RSA1" if (keyBlob[0] != CapiHelper.PUBLICKEYBLOB) { return false; } if (keyBlob[11] != 0x31 || keyBlob[10] != 0x41 || keyBlob[9] != 0x53 || keyBlob[8] != 0x52) { return false; } return true; } /// <summary> /// Since P is required, we will assume its presence is synonymous to a private key. /// </summary> /// <param name="rsaParams"></param> /// <returns></returns> private static bool IsPublic(RSAParameters rsaParams) { return (rsaParams.P == null); } protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { // we're sealed and the base should have checked this already Contract.Assert(data != null); Contract.Assert(count >= 0 && count <= data.Length); Contract.Assert(offset >= 0 && offset <= data.Length - count); Contract.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name)); using (HashAlgorithm hash = GetHashAlgorithm(hashAlgorithm)) { return hash.ComputeHash(data, offset, count); } } protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) { // we're sealed and the base should have checked this already Contract.Assert(data != null); Contract.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name)); using (HashAlgorithm hash = GetHashAlgorithm(hashAlgorithm)) { return hash.ComputeHash(data); } } private static HashAlgorithm GetHashAlgorithm(HashAlgorithmName hashAlgorithm) { switch (hashAlgorithm.Name) { case "MD5": return MD5.Create(); case "SHA1": return SHA1.Create(); case "SHA256": return SHA256.Create(); case "SHA384": return SHA384.Create(); case "SHA512": return SHA512.Create(); default: throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name); } } private static int GetAlgorithmId(HashAlgorithmName hashAlgorithm) { switch (hashAlgorithm.Name) { case "MD5": return CapiHelper.CALG_MD5; case "SHA1": return CapiHelper.CALG_SHA1; case "SHA256": return CapiHelper.CALG_SHA_256; case "SHA384": return CapiHelper.CALG_SHA_384; case "SHA512": return CapiHelper.CALG_SHA_512; default: throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name); } } public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) { if (data == null) throw new ArgumentNullException("data"); if (padding == null) throw new ArgumentNullException("padding"); if (padding == RSAEncryptionPadding.Pkcs1) { return Encrypt(data, fOAEP: false); } else if (padding == RSAEncryptionPadding.OaepSHA1) { return Encrypt(data, fOAEP: true); } else { throw PaddingModeNotSupported(); } } public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) { if (data == null) throw new ArgumentNullException("data"); if (padding == null) throw new ArgumentNullException("padding"); if (padding == RSAEncryptionPadding.Pkcs1) { return Decrypt(data, fOAEP: false); } else if (padding == RSAEncryptionPadding.OaepSHA1) { return Decrypt(data, fOAEP: true); } else { throw PaddingModeNotSupported(); } } public override byte[] SignHash( byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (hash == null) throw new ArgumentNullException("hash"); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException("padding"); if (padding != RSASignaturePadding.Pkcs1) throw PaddingModeNotSupported(); return SignHash(hash, GetAlgorithmId(hashAlgorithm)); } public override bool VerifyHash( byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (hash == null) throw new ArgumentNullException("hash"); if (signature == null) throw new ArgumentNullException("signature"); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException("padding"); if (padding != RSASignaturePadding.Pkcs1) throw PaddingModeNotSupported(); return VerifyHash(hash, GetAlgorithmId(hashAlgorithm), signature); } private static Exception PaddingModeNotSupported() { return new CryptographicException(SR.Cryptography_InvalidPaddingMode); } private static Exception HashAlgorithmNameNullOrEmpty() { return new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm"); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.Maintainability.AvoidUnusedPrivateFieldsAnalyzer, Microsoft.CodeQuality.Analyzers.Maintainability.AvoidUnusedPrivateFieldsFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.Maintainability.AvoidUnusedPrivateFieldsAnalyzer, Microsoft.CodeQuality.Analyzers.Maintainability.AvoidUnusedPrivateFieldsFixer>; namespace Microsoft.CodeQuality.Analyzers.Maintainability.UnitTests { public class AvoidUnusedPrivateFieldsTests { private const string CSharpMEFAttributesDefinition = @" namespace System.ComponentModel.Composition { public class ExportAttribute: System.Attribute { } } namespace System.Composition { public class ExportAttribute: System.Attribute { } } "; private const string BasicMEFAttributesDefinition = @" Namespace System.ComponentModel.Composition Public Class ExportAttribute Inherits System.Attribute End Class End Namespace Namespace System.Composition Public Class ExportAttribute Inherits System.Attribute End Class End Namespace "; [Fact] public async Task CA1823_CSharp_AttributeUsage_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" [System.Obsolete(Message)] public class Class { private const string Message = ""Test""; } "); } [Fact] public async Task CA1823_CSharp_InterpolatedStringUsage_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { private const string Message = ""Test""; public string PublicMessage = $""Test: {Message}""; } "); } [Fact] public async Task CA1823_CSharp_CollectionInitializerUsage_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System.Collections.Generic; public class Class { private const string Message = ""Test""; public List<string> PublicMessage = new List<string> { Message }; } "); } [Fact, WorkItem(1219, "https://github.com/dotnet/roslyn-analyzers/issues/1219")] public async Task CA1823_CSharp_FieldOffsetAttribute_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Explicit)] public class Class { [System.Runtime.InteropServices.FieldOffsetAttribute(8)] private int fieldWithFieldOffsetAttribute; } "); } [Fact, WorkItem(1219, "https://github.com/dotnet/roslyn-analyzers/issues/1219")] public async Task CA1823_CSharp_FieldOffsetAttributeError_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Explicit)] public class Class { [{|CS7036:System.Runtime.InteropServices.FieldOffsetAttribute|}] private int {|CS0625:fieldWithFieldOffsetAttribute|}; } "); } [Fact, WorkItem(1219, "https://github.com/dotnet/roslyn-analyzers/issues/1219")] public async Task CA1823_CSharp_StructLayoutAttribute_LayoutKindSequential_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)] class Class1 { private int field; } // System.Runtime.InteropServices.LayoutKind.Sequential has value 0 [System.Runtime.InteropServices.StructLayout((short)0)] class Class2 { private int field; } "); } [Fact, WorkItem(1219, "https://github.com/dotnet/roslyn-analyzers/issues/1219")] public async Task CA1823_CSharp_StructLayoutAttribute_LayoutKindAuto_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Auto)] class Class { private int field; } ", GetCA1823CSharpResultAt(5, 17, "field")); } [Fact, WorkItem(1219, "https://github.com/dotnet/roslyn-analyzers/issues/1219")] public async Task CA1823_CSharp_StructLayoutAttribute_LayoutKindExplicit_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Explicit)] class Class { private int {|CS0625:field|}; } ", GetCA1823CSharpResultAt(5, 17, "field")); } [Fact, WorkItem(1219, "https://github.com/dotnet/roslyn-analyzers/issues/1219")] public async Task CA1823_CSharp_StructLayoutAttributeError_NoLayoutKind_Diagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" [{|CS1729:System.Runtime.InteropServices.StructLayout|}] class Class1 { private int field; } [System.Runtime.InteropServices.StructLayout(1000)] class Class2 { private int field; } ", GetCA1823CSharpResultAt(5, 17, "field"), GetCA1823CSharpResultAt(11, 17, "field")); } [Fact, WorkItem(1217, "https://github.com/dotnet/roslyn-analyzers/issues/1217")] public async Task CA1823_CSharp_MEFAttributes_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(CSharpMEFAttributesDefinition + @" public class Class { [System.Composition.ExportAttribute] private int fieldWithMefV1ExportAttribute; [System.ComponentModel.Composition.ExportAttribute] private int fieldWithMefV2ExportAttribute; } "); } [Fact, WorkItem(1217, "https://github.com/dotnet/roslyn-analyzers/issues/1217")] public async Task CA1823_CSharp_MEFAttributesError_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(CSharpMEFAttributesDefinition + @" public class Class { [{|CS1729:System.Composition.ExportAttribute(0)|}] private int fieldWithMefV1ExportAttribute; [{|CS1729:System.ComponentModel.Composition.ExportAttribute(0)|}] private int fieldWithMefV2ExportAttribute; } "); } [Fact, WorkItem(1217, "https://github.com/dotnet/roslyn-analyzers/issues/1217")] public async Task CA1823_CSharp_MEFAttributesUndefined_Diagnostic() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Default, TestCode = @" public class Class { [System.{|CS0234:Composition|}.ExportAttribute] private int fieldWithMefV1ExportAttribute; [System.ComponentModel.{|CS0234:Composition|}.ExportAttribute] private int fieldWithMefV2ExportAttribute; } ", ExpectedDiagnostics = { GetCA1823CSharpResultAt(5, 17, "fieldWithMefV1ExportAttribute"), GetCA1823CSharpResultAt(8, 17, "fieldWithMefV2ExportAttribute"), }, }.RunAsync(); } [Fact] public async Task CA1823_CSharp_SimpleUsages_DiagnosticCases() { await VerifyCS.VerifyAnalyzerAsync(@" public class Class { private string fileName = ""data.txt""; private int Used1 = 10; private int Used2; private int Unused1 = 20; private int Unused2; public int Unused3; public string FileName() { return fileName; } private int Value => Used1 + Used2; } ", GetCA1823CSharpResultAt(7, 17, "Unused1"), GetCA1823CSharpResultAt(8, 17, "Unused2")); } [Fact] public async Task CA1823_VisualBasic_DiagnosticCases() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class Class1 Private fileName As String Private Used1 As Integer = 10 Private Used2 As Integer Private Unused1 As Integer = 20 Private Unused2 As Integer Public Unused3 As Integer Public Function MyFileName() As String Return filename End Function Public ReadOnly Property MyValue As Integer Get Return Used1 + Used2 End Get End Property End Class ", GetCA1823BasicResultAt(6, 13, "Unused1"), GetCA1823BasicResultAt(7, 13, "Unused2")); } [Fact, WorkItem(1219, "https://github.com/dotnet/roslyn-analyzers/issues/1219")] public async Task CA1823_VisualBasic_FieldOffsetAttribute_NoDiagnostic() { await VerifyVB.VerifyAnalyzerAsync(@" <System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Explicit)> _ Public Class [Class] <System.Runtime.InteropServices.FieldOffsetAttribute(8)> _ Private fieldWithFieldOffsetAttribute As Integer End Class "); } [Fact, WorkItem(1219, "https://github.com/dotnet/roslyn-analyzers/issues/1219")] public async Task CA1823_VisualBasic_FieldOffsetAttributeError_NoDiagnostic() { await VerifyVB.VerifyAnalyzerAsync(@" <System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Explicit)> Public Class [Class] <System.Runtime.InteropServices.{|BC30455:FieldOffsetAttribute|}> Private fieldWithFieldOffsetAttribute As Integer End Class "); } [Fact, WorkItem(1219, "https://github.com/dotnet/roslyn-analyzers/issues/1219")] public async Task CA1823_VisualBasic_StructLayoutAttribute_LayoutKindSequential_NoDiagnostic() { await VerifyVB.VerifyAnalyzerAsync(@" <System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)> _ Public Class Class1 Private field As Integer End Class ' System.Runtime.InteropServices.LayoutKind.Sequential has value 0 <System.Runtime.InteropServices.StructLayout(0)> _ Public Class Class2 Private field As Integer End Class "); } [Fact, WorkItem(1219, "https://github.com/dotnet/roslyn-analyzers/issues/1219")] public async Task CA1823_VisualBasic_StructLayoutAttribute_LayoutKindAuto_Diagnostic() { await VerifyVB.VerifyAnalyzerAsync(@" <System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Auto)> _ Public Class [Class] Private field As Integer End Class ", GetCA1823BasicResultAt(4, 13, "field")); } [Fact, WorkItem(1219, "https://github.com/dotnet/roslyn-analyzers/issues/1219")] public async Task CA1823_VisualBasic_StructLayoutAttribute_LayoutKindExplicit_Diagnostic() { await VerifyVB.VerifyAnalyzerAsync(@" <System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Explicit)> _ Public Class [Class] Private field As Integer End Class ", GetCA1823BasicResultAt(4, 13, "field")); } [Fact, WorkItem(1219, "https://github.com/dotnet/roslyn-analyzers/issues/1219")] public async Task CA1823_VisualBasic_StructLayoutAttributeError_NoLayoutKind_Diagnostic() { await VerifyVB.VerifyAnalyzerAsync(@" <System.Runtime.InteropServices.{|BC30516:StructLayout|}> _ Public Class Class1 Private field As Integer End Class <System.Runtime.InteropServices.{|BC30519:StructLayout|}(1000)> _ Public Class Class2 Private field As Integer End Class ", GetCA1823BasicResultAt(4, 13, "field"), GetCA1823BasicResultAt(9, 13, "field")); } [Fact, WorkItem(1217, "https://github.com/dotnet/roslyn-analyzers/issues/1217")] public async Task CA1823_VisualBasic_MEFAttributes_NoDiagnostic() { await VerifyVB.VerifyAnalyzerAsync(BasicMEFAttributesDefinition + @" Public Class [Class] <System.Composition.ExportAttribute> _ Private fieldWithMefV1ExportAttribute As Integer <System.ComponentModel.Composition.ExportAttribute> _ Private fieldWithMefV2ExportAttribute As Integer End Class "); } [Fact, WorkItem(1217, "https://github.com/dotnet/roslyn-analyzers/issues/1217")] public async Task CA1823_VisualBasic_MEFAttributesError_NoDiagnostic() { await VerifyVB.VerifyAnalyzerAsync(BasicMEFAttributesDefinition + @" Public Class [Class] <System.Composition.ExportAttribute({|BC30057:0|})> _ Private fieldWithMefV1ExportAttribute As Integer <System.ComponentModel.Composition.ExportAttribute({|BC30057:0|})> _ Private fieldWithMefV2ExportAttribute As Integer End Class "); } [Fact, WorkItem(1217, "https://github.com/dotnet/roslyn-analyzers/issues/1217")] public async Task CA1823_VisualBasic_MEFAttributesUndefined_Diagnostic() { await new VerifyVB.Test { ReferenceAssemblies = ReferenceAssemblies.Default, TestCode = @" Public Class [Class] <{|BC30002:System.Composition.ExportAttribute|}> _ Private fieldWithMefV1ExportAttribute As Integer <{|BC30002:System.ComponentModel.Composition.ExportAttribute|}> _ Private fieldWithMefV2ExportAttribute As Integer End Class ", ExpectedDiagnostics = { GetCA1823BasicResultAt(4, 13, "fieldWithMefV1ExportAttribute"), GetCA1823BasicResultAt(7, 13, "fieldWithMefV2ExportAttribute"), }, }.RunAsync(); } private static DiagnosticResult GetCA1823CSharpResultAt(int line, int column, string fieldName) => VerifyCS.Diagnostic() .WithLocation(line, column) .WithArguments(fieldName); private static DiagnosticResult GetCA1823BasicResultAt(int line, int column, string fieldName) => VerifyVB.Diagnostic() .WithLocation(line, column) .WithArguments(fieldName); } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using System.Threading; using JetBrains.Annotations; using Newtonsoft.Json; using Reusable.Data; using Reusable.Diagnostics; using Reusable.Exceptionize; using Reusable.OmniLog.Abstractions; namespace Reusable.Flexo { public interface ISwitchable { [DefaultValue(true)] bool Enabled { get; } } [UsedImplicitly] [PublicAPI] public interface IExpression : ISwitchable { [NotNull] SoftString Name { get; } [CanBeNull] string Description { get; } [CanBeNull] IExpression Extension { get; } [NotNull] IConstant Invoke(); } public interface IExtension<out T> { T This { get; } } public static class ExpressionContext { public static IImmutableSession Default => ImmutableSession .Empty .Set(Expression.Namespace, x => x.Comparers, ImmutableDictionary<SoftString, IEqualityComparer<object>>.Empty) .Set(Expression.Namespace, x => x.References, ImmutableDictionary<SoftString, IExpression>.Empty) .Set(Expression.Namespace, x => x.DebugView, TreeNode.Create(ExpressionDebugView.Root)) .WithDefaultComparer() .WithSoftStringComparer() .WithRegexComparer(); } public abstract class Expression : IExpression { // ReSharper disable RedundantNameQualifier - Use full namespace to avoid conflicts with other types. public static readonly Type[] Types = { typeof(Reusable.Flexo.IsEqual), typeof(Reusable.Flexo.IsNull), typeof(Reusable.Flexo.IsNullOrEmpty), typeof(Reusable.Flexo.IsGreaterThan), typeof(Reusable.Flexo.IsGreaterThanOrEqual), typeof(Reusable.Flexo.IsLessThan), typeof(Reusable.Flexo.IsLessThanOrEqual), typeof(Reusable.Flexo.Not), typeof(Reusable.Flexo.All), typeof(Reusable.Flexo.Any), typeof(Reusable.Flexo.IIf), typeof(Reusable.Flexo.Switch), typeof(Reusable.Flexo.ToDouble), typeof(Reusable.Flexo.ToString), typeof(Reusable.Flexo.GetSingle), typeof(Reusable.Flexo.GetMany), typeof(Reusable.Flexo.SetSingle), typeof(Reusable.Flexo.SetMany), typeof(Reusable.Flexo.Ref), typeof(Reusable.Flexo.Contains), typeof(Reusable.Flexo.In), typeof(Reusable.Flexo.Overlaps), typeof(Reusable.Flexo.Matches), typeof(Reusable.Flexo.Min), typeof(Reusable.Flexo.Max), typeof(Reusable.Flexo.Count), typeof(Reusable.Flexo.Sum), typeof(Reusable.Flexo.Constant<>), typeof(Reusable.Flexo.Double), typeof(Reusable.Flexo.Integer), typeof(Reusable.Flexo.Decimal), //typeof(Reusable.Flexo.DateTime), //typeof(Reusable.Flexo.TimeSpan), typeof(Reusable.Flexo.String), typeof(Reusable.Flexo.True), typeof(Reusable.Flexo.False), typeof(Reusable.Flexo.Collection), typeof(Reusable.Flexo.Select), typeof(Reusable.Flexo.Throw), typeof(Reusable.Flexo.Where), typeof(Reusable.Flexo.Concat), typeof(Reusable.Flexo.Union), typeof(Reusable.Flexo.Block), }; // ReSharper restore RedundantNameQualifier private SoftString _name; protected Expression([NotNull] ILogger logger, SoftString name) { Logger = logger ?? throw new ArgumentNullException(nameof(logger)); _name = name ?? throw new ArgumentNullException(nameof(name)); } [NotNull] protected ILogger Logger { get; } [NotNull] public static ExpressionScope Scope => ExpressionScope.Current ?? throw new InvalidOperationException("Expressions must be invoked within a valid scope. Use 'BeginScope' to introduce one."); public static INamespace<IExpressionNamespace> Namespace => Use<IExpressionNamespace>.Namespace; public virtual SoftString Name { get => _name; set => _name = value ?? throw new ArgumentNullException(nameof(Name)); } public string Description { get; set; } public bool Enabled { get; set; } = true; /// <summary> /// Gets a value indicating whether a separate debug-view should be created for this expression. Returns true to avoid duplicated debug-views. /// </summary> protected virtual bool SuppressDebugView { get; } [JsonProperty("This")] public IExpression Extension { get; set; } public abstract IConstant Invoke(); public static ExpressionScope BeginScope(Func<IImmutableSession, IImmutableSession> configureContext) { return ExpressionScope.Push(configureContext(ExpressionScope.Current?.Context ?? ExpressionContext.Default)); } protected class ZeroLogger : ILogger { private ZeroLogger() { } public static ILogger Default => new ZeroLogger(); public SoftString Name { get; } = nameof(ZeroLogger); public ILogger Log(ILogLevel logLevel, Action<ILog> logAction) => this; public void Dispose() { } } } [DebuggerDisplay(DebuggerDisplayString.DefaultNoQuotes)] public class ExpressionScope : IDisposable { // ReSharper disable once InconsistentNaming - This cannot be renamed because it'd conflict with the property that has the same name. private static readonly AsyncLocal<ExpressionScope> _current = new AsyncLocal<ExpressionScope>(); static ExpressionScope() { } private ExpressionScope(int depth) { Depth = depth; } private string DebuggerDisplay => this.ToDebuggerDisplayString(builder => { //builder.Property(x => x.CorrelationId); //builder.Property(x => x.CorrelationContext); builder.DisplayValue(x => x.Depth); }); public ExpressionScope Parent { get; private set; } /// <summary> /// Gets the current log-scope which is the deepest one. /// </summary> [CanBeNull] public static ExpressionScope Current { get => _current.Value; private set => _current.Value = value; } public int Depth { get; } public IImmutableSession Context { get; private set; } public static ExpressionScope Push(IImmutableSession context) { var scope = Current = new ExpressionScope(Current?.Depth + 1 ?? 0) { Parent = Current, Context = context }; return scope; } public void Dispose() { Current = Current?.Parent; } } public static class ExpressionInvokeHelper { } public interface IExpressionNamespace : INamespace { object This { get; } IImmutableDictionary<SoftString, IEqualityComparer<object>> Comparers { get; } IImmutableDictionary<SoftString, IExpression> References { get; } TreeNode<ExpressionDebugView> DebugView { get; } } [PublicAPI] public static class ExpressionScopeExtensions { public static IEnumerable<ExpressionScope> Enumerate(this ExpressionScope scope) { var current = scope; while (current != null) { yield return current; current = current.Parent; } } } }
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1) #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using PlayFab.Json.Utilities; using System.Collections; using System.Globalization; namespace PlayFab.Json.Linq { /// <summary> /// Contains the LINQ to JSON extension methods. /// </summary> public static class LinqExtensions { /// <summary> /// Returns a collection of tokens that contains the ancestors of every token in the source collection. /// </summary> /// <typeparam name="T">The type of the objects in source, constrained to <see cref="JToken"/>.</typeparam> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the ancestors of every node in the source collection.</returns> public static IJEnumerable<JToken> Ancestors<T>(this IEnumerable<T> source) where T : JToken { ValidationUtils.ArgumentNotNull(source, "source"); return source.SelectMany(j => j.Ancestors()).AsJEnumerable(); } //TODO //public static IEnumerable<JObject> AncestorsAndSelf<T>(this IEnumerable<T> source) where T : JObject //{ // ValidationUtils.ArgumentNotNull(source, "source"); // return source.SelectMany(j => j.AncestorsAndSelf()); //} /// <summary> /// Returns a collection of tokens that contains the descendants of every token in the source collection. /// </summary> /// <typeparam name="T">The type of the objects in source, constrained to <see cref="JContainer"/>.</typeparam> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the descendants of every node in the source collection.</returns> public static IJEnumerable<JToken> Descendants<T>(this IEnumerable<T> source) where T : JContainer { ValidationUtils.ArgumentNotNull(source, "source"); return source.SelectMany(j => j.Descendants()).AsJEnumerable(); } //TODO //public static IEnumerable<JObject> DescendantsAndSelf<T>(this IEnumerable<T> source) where T : JContainer //{ // ValidationUtils.ArgumentNotNull(source, "source"); // return source.SelectMany(j => j.DescendantsAndSelf()); //} /// <summary> /// Returns a collection of child properties of every object in the source collection. /// </summary> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JObject"/> that contains the source collection.</param> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JProperty"/> that contains the properties of every object in the source collection.</returns> public static IJEnumerable<JProperty> Properties(this IEnumerable<JObject> source) { ValidationUtils.ArgumentNotNull(source, "source"); return source.SelectMany(d => d.Properties()).AsJEnumerable(); } /// <summary> /// Returns a collection of child values of every object in the source collection with the given key. /// </summary> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <param name="key">The token key.</param> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the values of every node in the source collection with the given key.</returns> public static IJEnumerable<JToken> Values(this IEnumerable<JToken> source, object key) { return Values<JToken, JToken>(source, key).AsJEnumerable(); } /// <summary> /// Returns a collection of child values of every object in the source collection. /// </summary> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the values of every node in the source collection.</returns> public static IJEnumerable<JToken> Values(this IEnumerable<JToken> source) { return source.Values(null); } /// <summary> /// Returns a collection of converted child values of every object in the source collection with the given key. /// </summary> /// <typeparam name="U">The type to convert the values to.</typeparam> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <param name="key">The token key.</param> /// <returns>An <see cref="IEnumerable{T}"/> that contains the converted values of every node in the source collection with the given key.</returns> public static IEnumerable<U> Values<U>(this IEnumerable<JToken> source, object key) { return Values<JToken, U>(source, key); } /// <summary> /// Returns a collection of converted child values of every object in the source collection. /// </summary> /// <typeparam name="U">The type to convert the values to.</typeparam> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <returns>An <see cref="IEnumerable{T}"/> that contains the converted values of every node in the source collection.</returns> public static IEnumerable<U> Values<U>(this IEnumerable<JToken> source) { return Values<JToken, U>(source, null); } /// <summary> /// Converts the value. /// </summary> /// <typeparam name="U">The type to convert the value to.</typeparam> /// <param name="value">A <see cref="JToken"/> cast as a <see cref="IEnumerable{T}"/> of <see cref="JToken"/>.</param> /// <returns>A converted value.</returns> public static U Value<U>(this IEnumerable<JToken> value) { return value.Value<JToken, U>(); } /// <summary> /// Converts the value. /// </summary> /// <typeparam name="T">The source collection type.</typeparam> /// <typeparam name="U">The type to convert the value to.</typeparam> /// <param name="value">A <see cref="JToken"/> cast as a <see cref="IEnumerable{T}"/> of <see cref="JToken"/>.</param> /// <returns>A converted value.</returns> public static U Value<T, U>(this IEnumerable<T> value) where T : JToken { ValidationUtils.ArgumentNotNull(value, "source"); JToken token = value as JToken; if (token == null) throw new ArgumentException("Source value must be a JToken."); return token.Convert<JToken, U>(); } internal static IEnumerable<U> Values<T, U>(this IEnumerable<T> source, object key) where T : JToken { ValidationUtils.ArgumentNotNull(source, "source"); foreach (JToken token in source) { if (key == null) { if (token is JValue) { yield return Convert<JValue, U>((JValue)token); } else { foreach (JToken t in token.Children()) { yield return t.Convert<JToken, U>(); ; } } } else { JToken value = token[key]; if (value != null) yield return value.Convert<JToken, U>(); } } yield break; } //TODO //public static IEnumerable<T> InDocumentOrder<T>(this IEnumerable<T> source) where T : JObject; //public static IEnumerable<JToken> Children<T>(this IEnumerable<T> source) where T : JToken //{ // ValidationUtils.ArgumentNotNull(source, "source"); // return source.SelectMany(c => c.Children()); //} /// <summary> /// Returns a collection of child tokens of every array in the source collection. /// </summary> /// <typeparam name="T">The source collection type.</typeparam> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the values of every node in the source collection.</returns> public static IJEnumerable<JToken> Children<T>(this IEnumerable<T> source) where T : JToken { return Children<T, JToken>(source).AsJEnumerable(); } /// <summary> /// Returns a collection of converted child tokens of every array in the source collection. /// </summary> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <typeparam name="U">The type to convert the values to.</typeparam> /// <typeparam name="T">The source collection type.</typeparam> /// <returns>An <see cref="IEnumerable{T}"/> that contains the converted values of every node in the source collection.</returns> public static IEnumerable<U> Children<T, U>(this IEnumerable<T> source) where T : JToken { ValidationUtils.ArgumentNotNull(source, "source"); return source.SelectMany(c => c.Children()).Convert<JToken, U>(); } internal static IEnumerable<U> Convert<T, U>(this IEnumerable<T> source) where T : JToken { ValidationUtils.ArgumentNotNull(source, "source"); foreach (JToken token in source) { yield return Convert<JToken, U>(token); } } internal static U Convert<T, U>(this T token) where T : JToken { if (token == null) return default(U); if (token is U // don't want to cast JValue to its interfaces, want to get the internal value && typeof(U) != typeof(IComparable) && typeof(U) != typeof(IFormattable)) { // HACK return (U)(object)token; } else { JValue value = token as JValue; if (value == null) throw new InvalidCastException("Cannot cast {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, token.GetType(), typeof(T))); if (value.Value is U) return (U)value.Value; Type targetType = typeof(U); if (ReflectionUtils.IsNullableType(targetType)) { if (value.Value == null) return default(U); targetType = Nullable.GetUnderlyingType(targetType); } return (U)System.Convert.ChangeType(value.Value, targetType, CultureInfo.InvariantCulture); } } //TODO //public static void Remove<T>(this IEnumerable<T> source) where T : JContainer; /// <summary> /// Returns the input typed as <see cref="IJEnumerable{T}"/>. /// </summary> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <returns>The input typed as <see cref="IJEnumerable{T}"/>.</returns> public static IJEnumerable<JToken> AsJEnumerable(this IEnumerable<JToken> source) { return source.AsJEnumerable<JToken>(); } /// <summary> /// Returns the input typed as <see cref="IJEnumerable{T}"/>. /// </summary> /// <typeparam name="T">The source collection type.</typeparam> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <returns>The input typed as <see cref="IJEnumerable{T}"/>.</returns> public static IJEnumerable<T> AsJEnumerable<T>(this IEnumerable<T> source) where T : JToken { if (source == null) return null; else if (source is IJEnumerable<T>) return (IJEnumerable<T>)source; else return new JEnumerable<T>(source); } } } #endif
using System; using System.Collections.Generic; using System.Data; using System.Text; using System.Windows.Forms; using NQuery.Demo.AddIns; namespace NQuery.Demo.DefaultAddins { public sealed class LoadTableFromClipboard : IAddIn { #region Tab Delimeted Values Parsing private enum TokenType { Eof, Linebreak, Separator, Value } private sealed class Token { private TokenType _tokenType; private string _text; public Token(TokenType tokenType, string text) { _tokenType = tokenType; _text = text; } public TokenType TokenType { get { return _tokenType; } } public string Text { get { return _text; } } } private sealed class CharReader { private string _text; private int _pos; public CharReader(string text) { _text = text; } public bool Eof { get { return _pos >= _text.Length; } } public char Current { get { return Peek(0); } } public char Peek() { return Peek(1); } public char Peek(int lookahead) { int index = _pos + lookahead; if (index < 0 || index >= _text.Length) return '\0'; return _text[index]; } public int Pos { get { return _pos; } set { _pos = value; } } } private sealed class Scanner { private CharReader _charReader; private const char EOF = '\0'; private const char CR = '\r'; private const char LF = '\n'; private const char TAB = '\t'; private const char QUOTE = '"'; public Scanner(string text) { _charReader = new CharReader(text); } public Token Read() { if (_charReader.Eof) return new Token(TokenType.Eof, String.Empty); switch(_charReader.Current) { case CR: _charReader.Pos++; if (_charReader.Current == LF) _charReader.Pos++; return new Token(TokenType.Linebreak, Environment.NewLine); case LF: _charReader.Pos++; return new Token(TokenType.Linebreak, Environment.NewLine); case TAB: _charReader.Pos++; return new Token(TokenType.Separator, "\t"); case QUOTE: return ReadMaskedValue(); default: return ReadValue(); } } private Token ReadMaskedValue() { _charReader.Pos++; StringBuilder sb = new StringBuilder(); while (_charReader.Current != EOF) { if (_charReader.Current == QUOTE) { _charReader.Pos++; if (_charReader.Current != QUOTE) break; } sb.Append(_charReader.Current); _charReader.Pos++; } return new Token(TokenType.Value, sb.ToString()); } private Token ReadValue() { StringBuilder sb = new StringBuilder(); while (_charReader.Current != EOF) { if (_charReader.Current == TAB || _charReader.Current == CR || _charReader.Current == LF) break; sb.Append(_charReader.Current); _charReader.Pos++; } return new Token(TokenType.Value, sb.ToString()); } } private sealed class Parser { private Scanner _scanner; private Token _current; private Token _lookahead; public Parser(string text) { _scanner = new Scanner(text); _current = _scanner.Read(); _lookahead = _scanner.Read(); } private void Next() { _current = _lookahead; _lookahead = _scanner.Read(); } private void Match(TokenType value) { if (_current.TokenType != value) throw new InvalidOperationException(String.Format("Expected token '{0}' but found '{1}", value, _current.TokenType)); Next(); } public DataTable ParseTable() { DataTable result = new DataTable(); // Build column definitions string[] headers = ParseRow(); foreach (string header in headers) { DataColumn dataColumn = new DataColumn(header, typeof(string)); result.Columns.Add(dataColumn); } // Read rows while (_current.TokenType != TokenType.Eof) { string[] values = ParseRow(); if (values.Length > result.Columns.Count) { // Drop all values beyond column count string[] newValues = new string[result.Columns.Count]; Array.Copy(values, newValues, newValues.Length); values = newValues; } else if (values.Length < result.Columns.Count) { // Padd with empty strings string[] newValues = new string[result.Columns.Count]; Array.Copy(values, newValues, values.Length); for (int i = values.Length; i < newValues.Length; i++) newValues[i] = String.Empty; values = newValues; } result.Rows.Add(values); } return result; } private string[] ParseRow() { List<string> values = new List<string>(); while (_current.TokenType != TokenType.Eof) { if (_current.TokenType == TokenType.Value) { values.Add(_current.Text); Next(); } else if (_current.TokenType == TokenType.Separator) { values.Add(null); } if (_current.TokenType == TokenType.Separator) Next(); if (_current.TokenType == TokenType.Linebreak) { Next(); break; } } return values.ToArray(); } } #endregion public QueryContext CreateQueryContext() { string textFromClipboard = Clipboard.GetText(); Parser parser = new Parser(textFromClipboard); DataTable dataTable = parser.ParseTable(); dataTable.TableName = "Clipboard"; Query query = new Query(); query.DataContext.Tables.Add(dataTable); query.Text = "SELECT * FROM Clipboard"; QueryContext queryContext = new QueryContext(query, "Clipboard"); return queryContext; } public string Name { get { return "Load Table From Clipboard"; } } } }
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 UdemyProject.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using Ecosim.SceneData; /** * Monobehaviour class that manages a queue of questionnaires and repors to be shown * to the player. While showing a questionnaire or report the UI will be blocked. */ public class ShowReports : MonoBehaviour { private static ShowReports self = null; private static volatile bool hasQueue = false; private bool isShowing = false; private QuestionnaireWindow questionnaireWindow; private Questionnaire currentQuestionnaire; private ReportWindow reportWindow; private Report currentReport; public static void NotifyQueueChange () { hasQueue = true; } public static void CancelCurrentQuestionnaire () { if (self != null && self.currentQuestionnaire != null) { // Nullify and dispose self.currentQuestionnaire = null; self.questionnaireWindow.Dispose (); self.questionnaireWindow = null; } } void Awake () { self = this; } void Start () { EditorCtrl.self.onSceneChanged += OnSceneChanged; } void OnSceneChanged (Scene scene) { if (scene == null) { hasQueue = false; isShowing = false; if (questionnaireWindow != null) questionnaireWindow.Dispose (); questionnaireWindow = null; currentQuestionnaire = null; if (reportWindow != null) reportWindow.Dispose (); reportWindow = null; currentReport = null; SetGameControlButtons (true); } } void OnGUI () { // TODO: Exception time; we should only come AFTER showArticles.cs if (ShowArticles.HasUnreadMessages) { // Check if we were showing before we had unread articles // This generates a loop where no articles and reports are shown // and no if (isShowing) { isShowing = false; SetGameControlButtons (true); GameControl.InterfaceChanged (); } return; } GameControl ctrl = GameControl.self; Scene scene = ctrl.scene; // Check for null scene if (scene == null) return; if (hasQueue && (!isShowing)) { if (ctrl.hideToolBar || ctrl.hideSuccessionButton) { // toolbar/succession button is hidden, apparently we're busy with something, wait till // we're ready for showing article... return; } isShowing = true; SetGameControlButtons (false); GameControl.InterfaceChanged (); object inQueue = scene.reports.CurrentInQueue (); if (inQueue is Questionnaire) { this.currentReport = null; this.currentQuestionnaire = (Questionnaire)inQueue; } else if (inQueue is Report) { this.currentQuestionnaire = null; this.currentReport = (Report)inQueue; } } else if (isShowing) { //GUI.depth = 100; //CameraControl.MouseOverGUI = true; if (this.currentQuestionnaire != null) { RenderQuestionnaire (); } else if (this.currentReport != null) { RenderReport (); } else { isShowing = false; SetGameControlButtons (true); GameControl.InterfaceChanged (); hasQueue = scene.reports.ToNextInQueue (); } } } void RenderQuestionnaire () { if (this.questionnaireWindow == null) { this.questionnaireWindow = new QuestionnaireWindow (currentQuestionnaire, delegate() { if (this.currentQuestionnaire.useBudget) { int totalMoneyEarned = EditorCtrl.self.scene.progression.GetQuestionnaireState (this.currentQuestionnaire.id).totalMoneyEarned; EditorCtrl.self.scene.progression.budget += totalMoneyEarned; GameControl.BudgetChanged (); } this.currentQuestionnaire = null; this.questionnaireWindow.Dispose (); this.questionnaireWindow = null; }, ReportBaseWindow.defaultIcon); } //GUI.depth = this.questionnaireWindow.depth + 1; this.questionnaireWindow.Render (); } void RenderReport () { if (this.reportWindow == null) { this.reportWindow = new ReportWindow (currentReport, delegate () { this.currentReport = null; this.reportWindow.Dispose (); this.reportWindow = null; }, ReportBaseWindow.defaultIcon); } //GUI.depth = this.reportWindow.depth + 1; this.reportWindow.Render (); } void SetGameControlButtons (bool enabled) { GameControl ctrl = GameControl.self; //ctrl.hideToolBar = enabled; ctrl.hideGameActions = !enabled; ctrl.hideSuccessionButton = !enabled; } /* * void OnGUI () { GameControl ctrl = GameControl.self; Scene scene = ctrl.scene; if ((scene != null) && hasUnreadMessages && (!isShowing)) { if (ctrl.hideToolBar || ctrl.hideSuccessionButton) { // toolbar/succession button is hidden, apparently we're busy with something, wait till // we're ready for showing article... return; } RenderFontToTexture.self.RenderNewsArticle (scene.progression.CurrentMessage ().text, scene, articleTex, false); isShowing = true; yPos = (float) Screen.height; targetYPos = Screen.height - articleTex.height;// Mathf.Min (Screen.height - articleTex.height, 200); ctrl.hideToolBar = true; ctrl.hideSuccessionButton = true; } else if (isShowing) { yPos = Mathf.Max (targetYPos, yPos - 1200f * Time.deltaTime); int sWidth = Screen.width; int xOffset = 0; if (EditorCtrl.self.isOpen) { sWidth -= 400; xOffset += 400; } GUI.depth = 100; CameraControl.MouseOverGUI = true; SimpleGUI.Label (new Rect ((sWidth - articleTex.width ) / 2, yPos, articleTex.width, articleTex.height), articleTex, GUIStyle.none); if (Event.current.type == EventType.MouseDown) { Event.current.Use (); ctrl.hideToolBar = false; ctrl.hideSuccessionButton = false; isShowing = false; hasUnreadMessages = ctrl.scene.progression.ToNextMessage (); } } } */ }
// // $Id: GraphForm.cs 11022 2017-07-03 17:43:28Z chambm $ // // // Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu> // // Copyright 2009 Vanderbilt University - Nashville, TN 37232 // // 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.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Drawing2D; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using DigitalRune.Windows.Docking; using pwiz.MSGraph; using ZedGraph; using System.Diagnostics; using System.Linq; using SpyTools; namespace seems { public partial class GraphForm : DockableForm, IDataView { #region IDataView Members public IList<ManagedDataSource> Sources { get { List<ManagedDataSource> sources = new List<ManagedDataSource>(); for( int i = 0; i < paneList.Count; ++i ) { Pane logicalPane = paneList[i]; foreach( GraphItem item in logicalPane ) sources.Add( item.Source ); } return sources; } } public IList<GraphItem> DataItems { get { List<GraphItem> graphItems = new List<GraphItem>(); for( int i = 0; i < paneList.Count; ++i ) { Pane logicalPane = paneList[i]; foreach( GraphItem item in logicalPane ) graphItems.Add( item ); } return graphItems; } } #endregion public pwiz.MSGraph.MSGraphControl ZedGraphControl { get { return msGraphControl; } } MSGraphPane focusedPane = null; CurveItem focusedItem = null; Manager manager = null; /// <summary> /// Occurs when the FocusedItem property changes; /// usually caused by a left click near a different MSGraphItem /// </summary> public event EventHandler ItemGotFocus; private void OnItemGotFocus( GraphForm graphForm, EventArgs eventArgs ) { if( ItemGotFocus != null ) ItemGotFocus( graphForm, eventArgs ); } private void setFocusedItem( CurveItem item ) { if( item != focusedItem ) { focusedItem = item; OnItemGotFocus( this, EventArgs.Empty ); } } /// <summary> /// Gets the MSGraphPane that was last focused on within the MSGraphControl /// </summary> public MSGraphPane FocusedPane { get { return focusedPane; } } /// <summary> /// If FocusedPane has a single item, it will return that; /// If the last left mouse click was less than ZedGraph.GraphPane.Default.NearestTol /// from a point, it will return the item containing that point; /// Otherwise returns the first item in the FocusedPane /// </summary> public CurveItem FocusedItem { get { return focusedItem; } } private PaneList paneList; public PaneList PaneList { get { return paneList; } set { paneList = value; Refresh(); } } private ZedGraph.PaneLayout paneLayout; public ZedGraph.PaneLayout PaneListLayout { get { return paneLayout; } set { ZedGraph.PaneLayout oldLayout = paneLayout; paneLayout = value; if( oldLayout != paneLayout ) Refresh(); } } /// <summary> /// If true, the legend will always be shown in all panes in this GraphForm. /// If false, the legend will never be shown in any pane in this GraphForm. /// If null, the legend will be shown if there is more than one but less than 10 items in a pane. /// </summary> public bool? ShowPaneLegends { get; set; } public GraphForm(Manager manager) { InitializeComponent(); this.manager = manager; paneList = new PaneList(); paneLayout = PaneLayout.SingleColumn; msGraphControl.BorderStyle = BorderStyle.None; msGraphControl.MasterPane.InnerPaneGap = 1; msGraphControl.MouseDownEvent += new ZedGraphControl.ZedMouseEventHandler( msGraphControl_MouseDownEvent ); msGraphControl.MouseMoveEvent += new ZedGraphControl.ZedMouseEventHandler( msGraphControl_MouseMoveEvent ); msGraphControl.ZoomButtons = MouseButtons.Left; msGraphControl.ZoomModifierKeys = Keys.None; msGraphControl.ZoomButtons2 = MouseButtons.None; msGraphControl.UnzoomButtons = new MSGraphControl.MouseButtonClicks( MouseButtons.Middle ); msGraphControl.UnzoomModifierKeys = Keys.None; msGraphControl.UnzoomButtons2 = new MSGraphControl.MouseButtonClicks( MouseButtons.None ); msGraphControl.UnzoomAllButtons = new MSGraphControl.MouseButtonClicks( MouseButtons.Left, 2 ); msGraphControl.UnzoomAllButtons2 = new MSGraphControl.MouseButtonClicks( MouseButtons.None ); msGraphControl.PanButtons = MouseButtons.Left; msGraphControl.PanModifierKeys = Keys.Control; msGraphControl.PanButtons2 = MouseButtons.None; msGraphControl.ContextMenuBuilder += new MSGraphControl.ContextMenuBuilderEventHandler( GraphForm_ContextMenuBuilder ); ContextMenuStrip dummyMenu = new ContextMenuStrip(); dummyMenu.Opening += new CancelEventHandler( foo_Opening ); TabPageContextMenuStrip = dummyMenu; } void foo_Opening( object sender, CancelEventArgs e ) { // close the active form when the tab page strip is right-clicked Close(); } bool msGraphControl_MouseMoveEvent( ZedGraphControl sender, MouseEventArgs e ) { MSGraphPane hoverPane = sender.MasterPane.FindPane( e.Location ) as MSGraphPane; if( hoverPane == null ) return false; CurveItem nearestCurve; int nearestIndex; //change the cursor if the mouse is sufficiently close to a point if( hoverPane.FindNearestPoint( e.Location, out nearestCurve, out nearestIndex ) ) { msGraphControl.Cursor = Cursors.SizeAll; } else { msGraphControl.Cursor = Cursors.Default; } return false; } bool msGraphControl_MouseDownEvent( ZedGraphControl sender, MouseEventArgs e ) { // keep track of MSGraphItem nearest the last left click Point pos = MousePosition; focusedPane = sender.MasterPane.FindPane( e.Location ) as MSGraphPane; if( focusedPane == null ) return false; CurveItem nearestCurve; int nearestIndex; focusedPane.FindNearestPoint( e.Location, out nearestCurve, out nearestIndex ); if( nearestCurve == null ) setFocusedItem( sender.MasterPane[0].CurveList[0] ); else setFocusedItem( nearestCurve ); return false; } void GraphForm_ContextMenuBuilder( ZedGraphControl sender, ContextMenuStrip menuStrip, Point mousePt, MSGraphControl.ContextMenuObjectState objState ) { if( sender.MasterPane.PaneList.Count > 1 ) { ToolStripMenuItem layoutMenu = new ToolStripMenuItem( "Stack Layout", null, new ToolStripItem[] { new ToolStripMenuItem("Single Column", null, GraphForm_StackLayoutSingleColumn), new ToolStripMenuItem("Single Row", null, GraphForm_StackLayoutSingleRow), new ToolStripMenuItem("Grid", null, GraphForm_StackLayoutGrid) } ); menuStrip.Items.Add( layoutMenu ); ToolStripMenuItem syncMenuItem = new ToolStripMenuItem( "Synchronize Zoom/Pan", null, GraphForm_SyncZoomPan ); syncMenuItem.Checked = msGraphControl.IsSynchronizeXAxes; menuStrip.Items.Add( syncMenuItem ); } menuStrip.Items.Add(new ToolStripMenuItem("Show Data Processing", Properties.Resources.DataProcessing, GraphForm_ShowDataProcessing)); menuStrip.Items.Add(new ToolStripMenuItem("Show Annotation", Properties.Resources.Annotation, GraphForm_ShowAnnotation)); } void GraphForm_StackLayoutSingleColumn( object sender, EventArgs e ) { PaneListLayout = PaneLayout.SingleColumn; } void GraphForm_StackLayoutSingleRow( object sender, EventArgs e ) { PaneListLayout = PaneLayout.SingleRow; } void GraphForm_StackLayoutGrid( object sender, EventArgs e ) { PaneListLayout = PaneLayout.ForceSquare; } void GraphForm_SyncZoomPan( object sender, EventArgs e ) { msGraphControl.IsSynchronizeXAxes = !msGraphControl.IsSynchronizeXAxes; } void GraphForm_ShowDataProcessing (object sender, EventArgs e) { manager.ShowDataProcessing(); } void GraphForm_ShowAnnotation (object sender, EventArgs e) { manager.ShowAnnotationForm(); } public override void Refresh() { MasterPane mp = msGraphControl.MasterPane; mp.Border.IsVisible = false; //pane.Chart.Border.IsVisible = false; if( mp.PaneList.Count != paneList.Count ) { mp.PaneList.Clear(); foreach( Pane logicalPane in paneList ) { MSGraphPane pane = new MSGraphPane(); pane.Border.IsVisible = false; pane.IsFontsScaled = false; mp.Add( pane ); } //mp.SetLayout( msGraphControl.CreateGraphics(), paneLayout ); } else { for( int i=0; i < paneList.Count; ++i ) { MSGraphPane pane = mp.PaneList[i] as MSGraphPane; pane.Border.IsVisible = false; pane.CurveList.Clear(); pane.GraphObjList.Clear(); } } for( int i = 0; i < paneList.Count; ++i ) { Pane logicalPane = paneList[i]; MSGraphPane pane = mp.PaneList[i] as MSGraphPane; pane.IsFontsScaled = false; pane.Border.IsVisible = false; bool needSourceNamePrefix = logicalPane.Select(o => o.Source).Distinct().Count() > 1; int maxAutoLegendItems = needSourceNamePrefix ? 5 : 10; foreach( GraphItem item in logicalPane.Take(logicalPane.Count-1) ) { //item.AddSourceToId = needSourceNamePrefix; msGraphControl.AddGraphItem( pane, item, false ); } //logicalPane.Last().AddSourceToId = needSourceNamePrefix; msGraphControl.AddGraphItem(pane, logicalPane.Last(), true); if( mp.PaneList.Count > 1 ) { //if( i < paneList.Count - 1 ) { pane.XAxis.Title.IsVisible = false; pane.XAxis.Scale.IsVisible = false; pane.Margin.Bottom = 0; pane.Margin.Top = 2; }/* else { pane.XAxis.Title.IsVisible = true; pane.XAxis.Scale.IsVisible = true; }*/ pane.YAxis.Title.IsVisible = false; pane.YAxis.Scale.IsVisible = false; pane.YAxis.Scale.SetupScaleData( pane, pane.YAxis ); } else { pane.XAxis.IsVisible = true; pane.XAxis.Title.IsVisible = true; pane.XAxis.Scale.IsVisible = true; pane.YAxis.Title.IsVisible = true; pane.YAxis.Scale.IsVisible = true; } if( logicalPane.Count == 1 ) { pane.Legend.IsVisible = false; } else { pane.Legend.IsVisible = ShowPaneLegends ?? (logicalPane.Count < maxAutoLegendItems); pane.Legend.Position = ZedGraph.LegendPos.TopCenter; ZedGraph.ColorSymbolRotator rotator = new ColorSymbolRotator(); foreach( CurveItem item in pane.CurveList ) { item.Color = rotator.NextColor; } } if (paneList.Count > 0 && paneList[0].Count > 0) { this.Text = paneList[0][0].Id; if (paneList[0][0].IsMassSpectrum) this.TabText = (paneList[0][0] as MassSpectrum).AbbreviatedId; else this.TabText = this.Text; } if (pane.XAxis.Scale.MaxAuto) { using (Graphics g = msGraphControl.CreateGraphics()) { if (msGraphControl.IsSynchronizeXAxes || msGraphControl.IsSynchronizeYAxes) { foreach (GraphPane p in msGraphControl.MasterPane.PaneList) { p.XAxis.ResetAutoScale(p, g); p.X2Axis.ResetAutoScale(p, g); foreach (YAxis axis in p.YAxisList) axis.ResetAutoScale(p, g); foreach (Y2Axis axis in p.Y2AxisList) axis.ResetAutoScale(p, g); } } else { pane.XAxis.ResetAutoScale(pane, g); pane.X2Axis.ResetAutoScale(pane, g); foreach (YAxis axis in pane.YAxisList) axis.ResetAutoScale(pane, g); foreach (Y2Axis axis in pane.Y2AxisList) axis.ResetAutoScale(pane, g); } } //msGraphControl.RestoreScale(pane); } else pane.AxisChange(); } mp.SetLayout( msGraphControl.CreateGraphics(), paneLayout ); /*if( isOverlay ) { pane.Legend.IsVisible = true; pane.Legend.Position = ZedGraph.LegendPos.TopCenter; for( int i = 0; i < pane.CurveList.Count; ++i ) { pane.CurveList[i].Color = overlayColors[i]; ( pane.CurveList[i] as ZedGraph.LineItem ).Line.Width = 2; } } else { pane.Legend.IsVisible = false; currentGraphItem = chromatogram; }*/ //msGraphControl.RestoreScale( pane ); //msGraphControl.ZoomOutAll( pane ); /*bool isScaleAuto = !pane.IsZoomed; if( isScaleAuto ) pointList.SetScale( bins, pointList[0].X, pointList[pointList.Count - 1].X ); else pointList.SetScale( bins, pane.XAxis.Scale.Min, pane.XAxis.Scale.Max );*/ // String.Format( "{0} - {1}", currentDataSource.Name, chromatogram.Id ) if( mp.PaneList.Count > 0 && ( focusedPane == null || !mp.PaneList.Contains( focusedPane ) ) ) focusedPane = mp.PaneList[0] as MSGraphPane; if( mp.PaneList.Count > 0 && mp.PaneList[0].CurveList.Count > 0 && ( focusedItem == null || //!focusedPane.CurveList.Contains( focusedItem ) ) ) // somehow focusedItem.Tag can be the same as one of focusedPane.CurveList's Tags, but Contains returns false !focusedPane.CurveList.Any(o => o.Tag == focusedItem.Tag))) setFocusedItem( mp.PaneList[0].CurveList[0] ); msGraphControl.Refresh(); } private Color[] overlayColors = new Color[] { Color.Red, Color.Blue, Color.Green, Color.Purple, Color.Brown, Color.Magenta, Color.Cyan, Color.LightGreen, Color.Beige, Color.DarkRed, Color.DarkBlue, Color.DarkGreen, Color.DeepPink }; private void GraphForm_ResizeBegin( object sender, EventArgs e ) { SuspendLayout(); msGraphControl.Visible = false; } private void GraphForm_ResizeEnd( object sender, EventArgs e ) { ResumeLayout(); msGraphControl.Visible = true; Refresh(); } } /// <summary> /// A list of GraphItems. /// </summary> public class Pane : List<GraphItem> { } /// <summary> /// A list of GraphForm.Panes. /// </summary> public class PaneList : List<Pane> { } public static class Extensions { /// <summary> /// Converts the integer X and Y coordinates into a floating-point PointF. /// </summary> public static PointF ToPointF( this Point point ) { return new PointF( (float) point.X, (float) point.Y ); } } }
using System; using System.Reflection; using System.Linq.Expressions; using UnityEditor; //using EditorGUIUtility=UnityEditor.EditorGUIUtility; namespace UnityEngine.Experimental.Rendering.HDPipeline { [CustomEditor(typeof(HDRenderPipeline))] public class HDRenderPipelineInspector : Editor { private class Styles { public readonly GUIContent settingsLabel = new GUIContent("Settings"); // Rendering Settings public readonly GUIContent renderingSettingsLabel = new GUIContent("Rendering Settings"); public readonly GUIContent useForwardRenderingOnly = new GUIContent("Use Forward Rendering Only"); public readonly GUIContent useDepthPrepass = new GUIContent("Use Depth Prepass"); // Texture Settings public readonly GUIContent textureSettings = new GUIContent("Texture Settings"); public readonly GUIContent spotCookieSize = new GUIContent("Spot cookie size"); public readonly GUIContent pointCookieSize = new GUIContent("Point cookie size"); public readonly GUIContent reflectionCubemapSize = new GUIContent("Reflection cubemap size"); public readonly GUIContent sssSettings = new GUIContent("Subsurface Scattering Settings"); // Shadow Settings public readonly GUIContent shadowSettings = new GUIContent("Shadow Settings"); public readonly GUIContent shadowsAtlasWidth = new GUIContent("Atlas width"); public readonly GUIContent shadowsAtlasHeight = new GUIContent("Atlas height"); // Subsurface Scattering Settings public readonly GUIContent[] sssProfiles = new GUIContent[SubsurfaceScatteringSettings.maxNumProfiles] { new GUIContent("Profile #0"), new GUIContent("Profile #1"), new GUIContent("Profile #2"), new GUIContent("Profile #3"), new GUIContent("Profile #4"), new GUIContent("Profile #5"), new GUIContent("Profile #6"), new GUIContent("Profile #7") }; public readonly GUIContent sssNumProfiles = new GUIContent("Number of profiles"); // Tile pass Settings public readonly GUIContent tileLightLoopSettings = new GUIContent("Tile Light Loop Settings"); public readonly string[] tileLightLoopDebugTileFlagStrings = new string[] { "Punctual Light", "Area Light", "Env Light"}; public readonly GUIContent splitLightEvaluation = new GUIContent("Split light and reflection evaluation", "Toggle"); public readonly GUIContent bigTilePrepass = new GUIContent("Enable big tile prepass", "Toggle"); public readonly GUIContent clustered = new GUIContent("Enable clustered", "Toggle"); public readonly GUIContent enableTileAndCluster = new GUIContent("Enable Tile/clustered", "Toggle"); public readonly GUIContent enableComputeLightEvaluation = new GUIContent("Enable Compute Light Evaluation", "Toggle"); // Sky Settings public readonly GUIContent skyParams = new GUIContent("Sky Settings"); // Debug Display Settings public readonly GUIContent debugging = new GUIContent("Debugging"); public readonly GUIContent debugOverlayRatio = new GUIContent("Overlay Ratio"); // Material debug public readonly GUIContent materialDebugLabel = new GUIContent("Material Debug"); public readonly GUIContent debugViewMaterial = new GUIContent("DebugView Material", "Display various properties of Materials."); public readonly GUIContent debugViewEngine = new GUIContent("DebugView Engine", "Display various properties of Materials."); public readonly GUIContent debugViewMaterialVarying = new GUIContent("DebugView Attributes", "Display varying input of Materials."); public readonly GUIContent debugViewMaterialGBuffer = new GUIContent("DebugView GBuffer", "Display GBuffer properties."); // Rendering Debug public readonly GUIContent renderingDebugSettings = new GUIContent("Rendering Debug"); public readonly GUIContent displayOpaqueObjects = new GUIContent("Display Opaque Objects", "Toggle opaque objects rendering on and off."); public readonly GUIContent displayTransparentObjects = new GUIContent("Display Transparent Objects", "Toggle transparent objects rendering on and off."); public readonly GUIContent enableDistortion = new GUIContent("Enable Distortion"); public readonly GUIContent enableSSS = new GUIContent("Enable Subsurface Scattering"); // Lighting Debug public readonly GUIContent lightingDebugSettings = new GUIContent("Lighting Debug"); public readonly GUIContent shadowDebugEnable = new GUIContent("Enable Shadows"); public readonly GUIContent lightingVisualizationMode = new GUIContent("Lighting Debug Mode"); public readonly GUIContent[] debugViewLightingStrings = { new GUIContent("None"), new GUIContent("Diffuse Lighting"), new GUIContent("Specular Lighting"), new GUIContent("Visualize Cascades") }; public readonly int[] debugViewLightingValues = { (int)DebugLightingMode.None, (int)DebugLightingMode.DiffuseLighting, (int)DebugLightingMode.SpecularLighting, (int)DebugLightingMode.VisualizeCascade }; public readonly GUIContent shadowDebugVisualizationMode = new GUIContent("Shadow Maps Debug Mode"); public readonly GUIContent shadowDebugVisualizeShadowIndex = new GUIContent("Visualize Shadow Index"); public readonly GUIContent lightingDebugOverrideSmoothness = new GUIContent("Override Smoothness"); public readonly GUIContent lightingDebugOverrideSmoothnessValue = new GUIContent("Smoothness Value"); public readonly GUIContent lightingDebugAlbedo = new GUIContent("Lighting Debug Albedo"); public readonly GUIContent lightingDisplaySkyReflection = new GUIContent("Display Sky Reflection"); public readonly GUIContent lightingDisplaySkyReflectionMipmap = new GUIContent("Reflection Mipmap"); } private static Styles s_Styles = null; private static Styles styles { get { if (s_Styles == null) s_Styles = new Styles(); return s_Styles; } } // Display Debug SerializedProperty m_ShowMaterialDebug = null; SerializedProperty m_ShowLightingDebug = null; SerializedProperty m_ShowRenderingDebug = null; SerializedProperty m_DebugOverlayRatio = null; // Rendering Debug SerializedProperty m_DisplayOpaqueObjects = null; SerializedProperty m_DisplayTransparentObjects = null; SerializedProperty m_EnableDistortion = null; SerializedProperty m_EnableSSS = null; // Lighting debug SerializedProperty m_DebugShadowEnabled = null; SerializedProperty m_ShadowDebugMode = null; SerializedProperty m_ShadowDebugShadowMapIndex = null; SerializedProperty m_LightingDebugOverrideSmoothness = null; SerializedProperty m_LightingDebugOverrideSmoothnessValue = null; SerializedProperty m_LightingDebugAlbedo = null; SerializedProperty m_LightingDebugDisplaySkyReflection = null; SerializedProperty m_LightingDebugDisplaySkyReflectionMipmap = null; // Rendering Settings SerializedProperty m_RenderingUseForwardOnly = null; SerializedProperty m_RenderingUseDepthPrepass = null; // Subsurface Scattering Settings SerializedProperty m_Profiles = null; SerializedProperty m_NumProfiles = null; private void InitializeProperties() { // DebugDisplay debug m_DebugOverlayRatio = FindProperty(x => x.debugDisplaySettings.debugOverlayRatio); m_ShowLightingDebug = FindProperty(x => x.debugDisplaySettings.displayLightingDebug); m_ShowRenderingDebug = FindProperty(x => x.debugDisplaySettings.displayRenderingDebug); m_ShowMaterialDebug = FindProperty(x => x.debugDisplaySettings.displayMaterialDebug); // Rendering debug m_DisplayOpaqueObjects = FindProperty(x => x.debugDisplaySettings.renderingDebugSettings.displayOpaqueObjects); m_DisplayTransparentObjects = FindProperty(x => x.debugDisplaySettings.renderingDebugSettings.displayTransparentObjects); m_EnableDistortion = FindProperty(x => x.debugDisplaySettings.renderingDebugSettings.enableDistortion); m_EnableSSS = FindProperty(x => x.debugDisplaySettings.renderingDebugSettings.enableSSS); // Lighting debug m_DebugShadowEnabled = FindProperty(x => x.debugDisplaySettings.lightingDebugSettings.enableShadows); m_ShadowDebugMode = FindProperty(x => x.debugDisplaySettings.lightingDebugSettings.shadowDebugMode); m_ShadowDebugShadowMapIndex = FindProperty(x => x.debugDisplaySettings.lightingDebugSettings.shadowMapIndex); m_LightingDebugOverrideSmoothness = FindProperty(x => x.debugDisplaySettings.lightingDebugSettings.overrideSmoothness); m_LightingDebugOverrideSmoothnessValue = FindProperty(x => x.debugDisplaySettings.lightingDebugSettings.overrideSmoothnessValue); m_LightingDebugAlbedo = FindProperty(x => x.debugDisplaySettings.lightingDebugSettings.debugLightingAlbedo); m_LightingDebugDisplaySkyReflection = FindProperty(x => x.debugDisplaySettings.lightingDebugSettings.displaySkyReflection); m_LightingDebugDisplaySkyReflectionMipmap = FindProperty(x => x.debugDisplaySettings.lightingDebugSettings.skyReflectionMipmap); // Rendering settings m_RenderingUseForwardOnly = FindProperty(x => x.renderingSettings.useForwardRenderingOnly); m_RenderingUseDepthPrepass = FindProperty(x => x.renderingSettings.useDepthPrepass); // Subsurface Scattering Settings m_Profiles = FindProperty(x => x.sssSettings.profiles); m_NumProfiles = m_Profiles.FindPropertyRelative("Array.size"); } SerializedProperty FindProperty<TValue>(Expression<Func<HDRenderPipeline, TValue>> expr) { var path = Utilities.GetFieldPath(expr); return serializedObject.FindProperty(path); } static void HackSetDirty(RenderPipelineAsset asset) { EditorUtility.SetDirty(asset); var method = typeof(RenderPipelineAsset).GetMethod("OnValidate", BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Instance); if (method != null) method.Invoke(asset, new object[0]); } private void DebuggingUI(HDRenderPipeline renderContext, HDRenderPipelineInstance renderpipelineInstance) { EditorGUILayout.LabelField(styles.debugging); // Debug Display settings EditorGUI.indentLevel++; m_DebugOverlayRatio.floatValue = EditorGUILayout.Slider(styles.debugOverlayRatio, m_DebugOverlayRatio.floatValue, 0.1f, 1.0f); EditorGUILayout.Space(); RenderingDebugSettingsUI(renderContext); MaterialDebugSettingsUI(renderContext); LightingDebugSettingsUI(renderContext, renderpipelineInstance); EditorGUILayout.Space(); EditorGUI.indentLevel--; } private void MaterialDebugSettingsUI(HDRenderPipeline renderContext) { HDRenderPipeline hdPipe = target as HDRenderPipeline; m_ShowMaterialDebug.boolValue = EditorGUILayout.Foldout(m_ShowMaterialDebug.boolValue, styles.materialDebugLabel); if (!m_ShowMaterialDebug.boolValue) return; EditorGUI.indentLevel++; bool dirty = false; EditorGUI.BeginChangeCheck(); int value = EditorGUILayout.IntPopup(styles.debugViewMaterial, hdPipe.debugDisplaySettings.materialDebugSettings.debugViewMaterial, DebugDisplaySettings.debugViewMaterialStrings, DebugDisplaySettings.debugViewMaterialValues); if (EditorGUI.EndChangeCheck()) { hdPipe.debugDisplaySettings.SetDebugViewMaterial(value); dirty = true; } EditorGUI.BeginChangeCheck(); value = EditorGUILayout.IntPopup(styles.debugViewEngine, hdPipe.debugDisplaySettings.materialDebugSettings.debugViewEngine, DebugDisplaySettings.debugViewEngineStrings, DebugDisplaySettings.debugViewEngineValues); if (EditorGUI.EndChangeCheck()) { hdPipe.debugDisplaySettings.SetDebugViewEngine(value); dirty = true; } EditorGUI.BeginChangeCheck(); value = EditorGUILayout.IntPopup(styles.debugViewMaterialVarying, (int)hdPipe.debugDisplaySettings.materialDebugSettings.debugViewVarying, DebugDisplaySettings.debugViewMaterialVaryingStrings, DebugDisplaySettings.debugViewMaterialVaryingValues); if (EditorGUI.EndChangeCheck()) { hdPipe.debugDisplaySettings.SetDebugViewVarying((Attributes.DebugViewVarying)value); dirty = true; } EditorGUI.BeginChangeCheck(); value = EditorGUILayout.IntPopup(styles.debugViewMaterialGBuffer, (int)hdPipe.debugDisplaySettings.materialDebugSettings.debugViewGBuffer, DebugDisplaySettings.debugViewMaterialGBufferStrings, DebugDisplaySettings.debugViewMaterialGBufferValues); if (EditorGUI.EndChangeCheck()) { hdPipe.debugDisplaySettings.SetDebugViewGBuffer(value); dirty = true; } if(dirty) HackSetDirty(renderContext); // Repaint EditorGUI.indentLevel--; } private void RenderingDebugSettingsUI(HDRenderPipeline renderContext) { m_ShowRenderingDebug.boolValue = EditorGUILayout.Foldout(m_ShowRenderingDebug.boolValue, styles.renderingDebugSettings); if (!m_ShowRenderingDebug.boolValue) return; EditorGUI.indentLevel++; EditorGUILayout.PropertyField(m_DisplayOpaqueObjects, styles.displayOpaqueObjects); EditorGUILayout.PropertyField(m_DisplayTransparentObjects, styles.displayTransparentObjects); EditorGUILayout.PropertyField(m_EnableDistortion, styles.enableDistortion); EditorGUILayout.PropertyField(m_EnableSSS, styles.enableSSS); EditorGUI.indentLevel--; } private void SssSettingsUI(HDRenderPipeline pipe) { EditorGUILayout.Space(); EditorGUILayout.LabelField(styles.sssSettings); EditorGUI.BeginChangeCheck(); EditorGUI.indentLevel++; EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(m_NumProfiles, styles.sssNumProfiles); for (int i = 0, n = Math.Min(m_Profiles.arraySize, SubsurfaceScatteringSettings.maxNumProfiles); i < n; i++) { SerializedProperty profile = m_Profiles.GetArrayElementAtIndex(i); EditorGUILayout.PropertyField(profile, styles.sssProfiles[i]); } EditorGUI.indentLevel--; } private void LightingDebugSettingsUI(HDRenderPipeline renderContext, HDRenderPipelineInstance renderpipelineInstance) { m_ShowLightingDebug.boolValue = EditorGUILayout.Foldout(m_ShowLightingDebug.boolValue, styles.lightingDebugSettings); if (!m_ShowLightingDebug.boolValue) return; HDRenderPipeline hdPipe = target as HDRenderPipeline; bool dirty = false; EditorGUI.BeginChangeCheck(); EditorGUI.indentLevel++; EditorGUILayout.PropertyField(m_DebugShadowEnabled, styles.shadowDebugEnable); EditorGUILayout.PropertyField(m_ShadowDebugMode, styles.shadowDebugVisualizationMode); if (!m_ShadowDebugMode.hasMultipleDifferentValues) { if ((ShadowMapDebugMode)m_ShadowDebugMode.intValue == ShadowMapDebugMode.VisualizeShadowMap) { EditorGUILayout.IntSlider(m_ShadowDebugShadowMapIndex, 0, renderpipelineInstance.GetCurrentShadowCount() - 1, styles.shadowDebugVisualizeShadowIndex); } } if (EditorGUI.EndChangeCheck()) { dirty = true; } EditorGUI.BeginChangeCheck(); int value = EditorGUILayout.IntPopup(styles.lightingVisualizationMode, (int)hdPipe.debugDisplaySettings.lightingDebugSettings.debugLightingMode, styles.debugViewLightingStrings, styles.debugViewLightingValues); if (EditorGUI.EndChangeCheck()) { hdPipe.debugDisplaySettings.SetDebugLightingMode((DebugLightingMode)value); dirty = true; } EditorGUI.BeginChangeCheck(); if (hdPipe.debugDisplaySettings.GetDebugLightingMode() == DebugLightingMode.DiffuseLighting) { EditorGUI.indentLevel++; EditorGUILayout.PropertyField(m_LightingDebugAlbedo, styles.lightingDebugAlbedo); EditorGUI.indentLevel--; } if (hdPipe.debugDisplaySettings.GetDebugLightingMode() == DebugLightingMode.SpecularLighting) { EditorGUI.indentLevel++; EditorGUILayout.PropertyField(m_LightingDebugOverrideSmoothness, styles.lightingDebugOverrideSmoothness); if (!m_LightingDebugOverrideSmoothness.hasMultipleDifferentValues && m_LightingDebugOverrideSmoothness.boolValue == true) { EditorGUI.indentLevel++; EditorGUILayout.PropertyField(m_LightingDebugOverrideSmoothnessValue, styles.lightingDebugOverrideSmoothnessValue); EditorGUI.indentLevel--; } EditorGUI.indentLevel--; } EditorGUILayout.PropertyField(m_LightingDebugDisplaySkyReflection, styles.lightingDisplaySkyReflection); if (!m_LightingDebugDisplaySkyReflection.hasMultipleDifferentValues && m_LightingDebugDisplaySkyReflection.boolValue == true) { EditorGUI.indentLevel++; EditorGUILayout.PropertyField(m_LightingDebugDisplaySkyReflectionMipmap, styles.lightingDisplaySkyReflectionMipmap); EditorGUI.indentLevel--; } EditorGUI.indentLevel--; if (EditorGUI.EndChangeCheck()) { dirty = true; } if(dirty) HackSetDirty(renderContext); } private void SettingsUI(HDRenderPipeline renderContext) { EditorGUILayout.LabelField(styles.settingsLabel); EditorGUI.indentLevel++; EditorGUI.BeginChangeCheck(); renderContext.lightLoopProducer = (LightLoopProducer)EditorGUILayout.ObjectField(new GUIContent("Light Loop"), renderContext.lightLoopProducer, typeof(LightLoopProducer), false); if (EditorGUI.EndChangeCheck()) { HackSetDirty(renderContext); // Repaint } SssSettingsUI(renderContext); ShadowSettingsUI(renderContext); TextureSettingsUI(renderContext); RendereringSettingsUI(renderContext); //TilePassUI(renderContext); EditorGUI.indentLevel--; } private void ShadowSettingsUI(HDRenderPipeline renderContext) { EditorGUILayout.Space(); var shadowSettings = renderContext.shadowSettings; EditorGUILayout.LabelField(styles.shadowSettings); EditorGUI.indentLevel++; EditorGUI.BeginChangeCheck(); shadowSettings.shadowAtlasWidth = Mathf.Max(0, EditorGUILayout.IntField(styles.shadowsAtlasWidth, shadowSettings.shadowAtlasWidth)); shadowSettings.shadowAtlasHeight = Mathf.Max(0, EditorGUILayout.IntField(styles.shadowsAtlasHeight, shadowSettings.shadowAtlasHeight)); if (EditorGUI.EndChangeCheck()) { HackSetDirty(renderContext); // Repaint } EditorGUI.indentLevel--; } private void RendereringSettingsUI(HDRenderPipeline renderContext) { EditorGUILayout.Space(); EditorGUILayout.LabelField(styles.renderingSettingsLabel); EditorGUI.indentLevel++; EditorGUILayout.PropertyField(m_RenderingUseDepthPrepass, styles.useDepthPrepass); EditorGUILayout.PropertyField(m_RenderingUseForwardOnly, styles.useForwardRenderingOnly); EditorGUI.indentLevel--; } private void TextureSettingsUI(HDRenderPipeline renderContext) { EditorGUILayout.Space(); var textureSettings = renderContext.textureSettings; EditorGUILayout.LabelField(styles.textureSettings); EditorGUI.indentLevel++; EditorGUI.BeginChangeCheck(); textureSettings.spotCookieSize = Mathf.NextPowerOfTwo(Mathf.Clamp(EditorGUILayout.IntField(styles.spotCookieSize, textureSettings.spotCookieSize), 16, 1024)); textureSettings.pointCookieSize = Mathf.NextPowerOfTwo(Mathf.Clamp(EditorGUILayout.IntField(styles.pointCookieSize, textureSettings.pointCookieSize), 16, 1024)); textureSettings.reflectionCubemapSize = Mathf.NextPowerOfTwo(Mathf.Clamp(EditorGUILayout.IntField(styles.reflectionCubemapSize, textureSettings.reflectionCubemapSize), 64, 1024)); if (EditorGUI.EndChangeCheck()) { renderContext.textureSettings = textureSettings; HackSetDirty(renderContext); // Repaint } EditorGUI.indentLevel--; } /* private void TilePassUI(HDRenderPipeline renderContext) { EditorGUILayout.Space(); // TODO: we should call a virtual method or something similar to setup the UI, inspector should not know about it var tilePass = renderContext.tileSettings; if (tilePass != null) { EditorGUILayout.LabelField(styles.tileLightLoopSettings); EditorGUI.indentLevel++; EditorGUI.BeginChangeCheck(); tilePass.enableBigTilePrepass = EditorGUILayout.Toggle(styles.bigTilePrepass, tilePass.enableBigTilePrepass); tilePass.enableClustered = EditorGUILayout.Toggle(styles.clustered, tilePass.enableClustered); if (EditorGUI.EndChangeCheck()) { HackSetDirty(renderContext); // Repaint // SetAssetDirty will tell renderloop to rebuild renderContext.DestroyCreatedInstances(); } EditorGUI.BeginChangeCheck(); tilePass.debugViewTilesFlags = EditorGUILayout.MaskField("DebugView Tiles", tilePass.debugViewTilesFlags, styles.tileLightLoopDebugTileFlagStrings); tilePass.enableSplitLightEvaluation = EditorGUILayout.Toggle(styles.splitLightEvaluation, tilePass.enableSplitLightEvaluation); tilePass.enableTileAndCluster = EditorGUILayout.Toggle(styles.enableTileAndCluster, tilePass.enableTileAndCluster); tilePass.enableComputeLightEvaluation = EditorGUILayout.Toggle(styles.enableComputeLightEvaluation, tilePass.enableComputeLightEvaluation); if (EditorGUI.EndChangeCheck()) { HackSetDirty(renderContext); // Repaint UnityEditorInternal.InternalEditorUtility.RepaintAllViews(); } EditorGUI.indentLevel--; } }*/ public void OnEnable() { InitializeProperties(); } public override void OnInspectorGUI() { var renderContext = target as HDRenderPipeline; HDRenderPipelineInstance renderpipelineInstance = UnityEngine.Experimental.Rendering.RenderPipelineManager.currentPipeline as HDRenderPipelineInstance; if (!renderContext || renderpipelineInstance == null) return; serializedObject.Update(); DebuggingUI(renderContext, renderpipelineInstance); SettingsUI(renderContext); serializedObject.ApplyModifiedProperties(); } } }
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 RisEstudioComiteEtica class. /// </summary> [Serializable] public partial class RisEstudioComiteEticaCollection : ActiveList<RisEstudioComiteEtica, RisEstudioComiteEticaCollection> { public RisEstudioComiteEticaCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>RisEstudioComiteEticaCollection</returns> public RisEstudioComiteEticaCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { RisEstudioComiteEtica 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 RIS_EstudioComiteEtica table. /// </summary> [Serializable] public partial class RisEstudioComiteEtica : ActiveRecord<RisEstudioComiteEtica>, IActiveRecord { #region .ctors and Default Settings public RisEstudioComiteEtica() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public RisEstudioComiteEtica(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public RisEstudioComiteEtica(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public RisEstudioComiteEtica(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("RIS_EstudioComiteEtica", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdEstudioComiteEtica = new TableSchema.TableColumn(schema); colvarIdEstudioComiteEtica.ColumnName = "idEstudioComiteEtica"; colvarIdEstudioComiteEtica.DataType = DbType.Int32; colvarIdEstudioComiteEtica.MaxLength = 0; colvarIdEstudioComiteEtica.AutoIncrement = true; colvarIdEstudioComiteEtica.IsNullable = false; colvarIdEstudioComiteEtica.IsPrimaryKey = true; colvarIdEstudioComiteEtica.IsForeignKey = false; colvarIdEstudioComiteEtica.IsReadOnly = false; colvarIdEstudioComiteEtica.DefaultSetting = @""; colvarIdEstudioComiteEtica.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEstudioComiteEtica); TableSchema.TableColumn colvarIdEstudio = new TableSchema.TableColumn(schema); colvarIdEstudio.ColumnName = "idEstudio"; colvarIdEstudio.DataType = DbType.Int32; colvarIdEstudio.MaxLength = 0; colvarIdEstudio.AutoIncrement = false; colvarIdEstudio.IsNullable = false; colvarIdEstudio.IsPrimaryKey = false; colvarIdEstudio.IsForeignKey = false; colvarIdEstudio.IsReadOnly = false; colvarIdEstudio.DefaultSetting = @""; colvarIdEstudio.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEstudio); TableSchema.TableColumn colvarIdComiteEtica = new TableSchema.TableColumn(schema); colvarIdComiteEtica.ColumnName = "idComiteEtica"; colvarIdComiteEtica.DataType = DbType.Int32; colvarIdComiteEtica.MaxLength = 0; colvarIdComiteEtica.AutoIncrement = false; colvarIdComiteEtica.IsNullable = false; colvarIdComiteEtica.IsPrimaryKey = false; colvarIdComiteEtica.IsForeignKey = false; colvarIdComiteEtica.IsReadOnly = false; colvarIdComiteEtica.DefaultSetting = @""; colvarIdComiteEtica.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdComiteEtica); TableSchema.TableColumn colvarDictamen = new TableSchema.TableColumn(schema); colvarDictamen.ColumnName = "dictamen"; colvarDictamen.DataType = DbType.AnsiString; colvarDictamen.MaxLength = 100; colvarDictamen.AutoIncrement = false; colvarDictamen.IsNullable = false; colvarDictamen.IsPrimaryKey = false; colvarDictamen.IsForeignKey = false; colvarDictamen.IsReadOnly = false; colvarDictamen.DefaultSetting = @""; colvarDictamen.ForeignKeyTableName = ""; schema.Columns.Add(colvarDictamen); TableSchema.TableColumn colvarFechaDictamen = new TableSchema.TableColumn(schema); colvarFechaDictamen.ColumnName = "fechaDictamen"; colvarFechaDictamen.DataType = DbType.DateTime; colvarFechaDictamen.MaxLength = 0; colvarFechaDictamen.AutoIncrement = false; colvarFechaDictamen.IsNullable = false; colvarFechaDictamen.IsPrimaryKey = false; colvarFechaDictamen.IsForeignKey = false; colvarFechaDictamen.IsReadOnly = false; colvarFechaDictamen.DefaultSetting = @""; colvarFechaDictamen.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaDictamen); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("RIS_EstudioComiteEtica",schema); } } #endregion #region Props [XmlAttribute("IdEstudioComiteEtica")] [Bindable(true)] public int IdEstudioComiteEtica { get { return GetColumnValue<int>(Columns.IdEstudioComiteEtica); } set { SetColumnValue(Columns.IdEstudioComiteEtica, value); } } [XmlAttribute("IdEstudio")] [Bindable(true)] public int IdEstudio { get { return GetColumnValue<int>(Columns.IdEstudio); } set { SetColumnValue(Columns.IdEstudio, value); } } [XmlAttribute("IdComiteEtica")] [Bindable(true)] public int IdComiteEtica { get { return GetColumnValue<int>(Columns.IdComiteEtica); } set { SetColumnValue(Columns.IdComiteEtica, value); } } [XmlAttribute("Dictamen")] [Bindable(true)] public string Dictamen { get { return GetColumnValue<string>(Columns.Dictamen); } set { SetColumnValue(Columns.Dictamen, value); } } [XmlAttribute("FechaDictamen")] [Bindable(true)] public DateTime FechaDictamen { get { return GetColumnValue<DateTime>(Columns.FechaDictamen); } set { SetColumnValue(Columns.FechaDictamen, value); } } #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(int varIdEstudio,int varIdComiteEtica,string varDictamen,DateTime varFechaDictamen) { RisEstudioComiteEtica item = new RisEstudioComiteEtica(); item.IdEstudio = varIdEstudio; item.IdComiteEtica = varIdComiteEtica; item.Dictamen = varDictamen; item.FechaDictamen = varFechaDictamen; 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 varIdEstudioComiteEtica,int varIdEstudio,int varIdComiteEtica,string varDictamen,DateTime varFechaDictamen) { RisEstudioComiteEtica item = new RisEstudioComiteEtica(); item.IdEstudioComiteEtica = varIdEstudioComiteEtica; item.IdEstudio = varIdEstudio; item.IdComiteEtica = varIdComiteEtica; item.Dictamen = varDictamen; item.FechaDictamen = varFechaDictamen; 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 IdEstudioComiteEticaColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdEstudioColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdComiteEticaColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn DictamenColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn FechaDictamenColumn { get { return Schema.Columns[4]; } } #endregion #region Columns Struct public struct Columns { public static string IdEstudioComiteEtica = @"idEstudioComiteEtica"; public static string IdEstudio = @"idEstudio"; public static string IdComiteEtica = @"idComiteEtica"; public static string Dictamen = @"dictamen"; public static string FechaDictamen = @"fechaDictamen"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
#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; using System.Text; #if !NETMF using System.Xml; #endif using log4net.Core; using log4net.Util; #if !NETMF namespace log4net.Layout { /// <summary> /// Layout that formats the log events as XML elements. /// \todo This whole class has been missed out as we don't have an XMLWriter class that works in NETMF. Need to come up with an alternate solution. /// </summary> /// <remarks> /// <para> /// The output of the <see cref="XmlLayout" /> consists of a series of /// log4net:event elements. It does not output a complete well-formed XML /// file. The output is designed to be included as an <em>external entity</em> /// in a separate file to form a correct XML file. /// </para> /// <para> /// For example, if <c>abc</c> is the name of the file where /// the <see cref="XmlLayout" /> output goes, then a well-formed XML file would /// be: /// </para> /// <code lang="XML"> /// &lt;?xml version="1.0" ?&gt; /// /// &lt;!DOCTYPE log4net:events SYSTEM "log4net-events.dtd" [&lt;!ENTITY data SYSTEM "abc"&gt;]&gt; /// /// &lt;log4net:events version="1.2" xmlns:log4net="http://logging.apache.org/log4net/schemas/log4net-events-1.2&gt; /// &amp;data; /// &lt;/log4net:events&gt; /// </code> /// <para> /// This approach enforces the independence of the <see cref="XmlLayout" /> /// and the appender where it is embedded. /// </para> /// <para> /// The <c>version</c> attribute helps components to correctly /// interpret output generated by <see cref="XmlLayout" />. The value of /// this attribute should be "1.2" for release 1.2 and later. /// </para> /// <para> /// Alternatively the <c>Header</c> and <c>Footer</c> properties can be /// configured to output the correct XML header, open tag and close tag. /// When setting the <c>Header</c> and <c>Footer</c> properties it is essential /// that the underlying data store not be appendable otherwise the data /// will become invalid XML. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public class XmlLayout : XmlLayoutBase { #region Public Instance Constructors /// <summary> /// Constructs an XmlLayout /// </summary> public XmlLayout() : base() { } /// <summary> /// Constructs an XmlLayout. /// </summary> /// <remarks> /// <para> /// The <b>LocationInfo</b> option takes a boolean value. By /// default, it is set to false which means there will be no location /// information output by this layout. If the the option is set to /// true, then the file name and line number of the statement /// at the origin of the log statement will be output. /// </para> /// <para> /// If you are embedding this layout within an SmtpAppender /// then make sure to set the <b>LocationInfo</b> option of that /// appender as well. /// </para> /// </remarks> public XmlLayout(bool locationInfo) : base(locationInfo) { } #endregion Public Instance Constructors #region Public Instance Properties /// <summary> /// The prefix to use for all element names /// </summary> /// <remarks> /// <para> /// The default prefix is <b>log4net</b>. Set this property /// to change the prefix. If the prefix is set to an empty string /// then no prefix will be written. /// </para> /// </remarks> public string Prefix { get { return m_prefix; } set { m_prefix = value; } } /// <summary> /// Set whether or not to base64 encode the message. /// </summary> /// <remarks> /// <para> /// By default the log message will be written as text to the xml /// output. This can cause problems when the message contains binary /// data. By setting this to true the contents of the message will be /// base64 encoded. If this is set then invalid character replacement /// (see <see cref="XmlLayoutBase.InvalidCharReplacement"/>) will not be performed /// on the log message. /// </para> /// </remarks> public bool Base64EncodeMessage { get {return m_base64Message;} set {m_base64Message=value;} } /// <summary> /// Set whether or not to base64 encode the property values. /// </summary> /// <remarks> /// <para> /// By default the properties will be written as text to the xml /// output. This can cause problems when one or more properties contain /// binary data. By setting this to true the values of the properties /// will be base64 encoded. If this is set then invalid character replacement /// (see <see cref="XmlLayoutBase.InvalidCharReplacement"/>) will not be performed /// on the property values. /// </para> /// </remarks> public bool Base64EncodeProperties { get {return m_base64Properties;} set {m_base64Properties=value;} } #endregion Public Instance Properties #region Implementation of IOptionHandler /// <summary> /// Initialize layout options /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// <para> /// Builds a cache of the element names /// </para> /// </remarks> override public void ActivateOptions() { base.ActivateOptions(); // Cache the full element names including the prefix if (m_prefix != null && m_prefix.Length > 0) { m_elmEvent = m_prefix + ":" + ELM_EVENT; m_elmMessage = m_prefix + ":" + ELM_MESSAGE; m_elmProperties = m_prefix + ":" + ELM_PROPERTIES; m_elmData = m_prefix + ":" + ELM_DATA; m_elmException = m_prefix + ":" + ELM_EXCEPTION; m_elmLocation = m_prefix + ":" + ELM_LOCATION; } } #endregion Implementation of IOptionHandler #region Override implementation of XMLLayoutBase /// <summary> /// Does the actual writing of the XML. /// </summary> /// <param name="writer">The writer to use to output the event to.</param> /// <param name="loggingEvent">The event to write.</param> /// <remarks> /// <para> /// Override the base class <see cref="XmlLayoutBase.FormatXml"/> method /// to write the <see cref="LoggingEvent"/> to the <see cref="XmlWriter"/>. /// </para> /// </remarks> override protected void FormatXml(XmlWriter writer, LoggingEvent loggingEvent) { writer.WriteStartElement(m_elmEvent); writer.WriteAttributeString(ATTR_LOGGER, loggingEvent.LoggerName); #if NET_2_0 || NETCF_2_0 || MONO_2_0 writer.WriteAttributeString(ATTR_TIMESTAMP, XmlConvert.ToString(loggingEvent.TimeStamp, XmlDateTimeSerializationMode.Local)); #else writer.WriteAttributeString(ATTR_TIMESTAMP, XmlConvert.ToString(loggingEvent.TimeStamp)); #endif writer.WriteAttributeString(ATTR_LEVEL, loggingEvent.Level.DisplayName); writer.WriteAttributeString(ATTR_THREAD, loggingEvent.ThreadName); if (loggingEvent.Domain != null && loggingEvent.Domain.Length > 0) { writer.WriteAttributeString(ATTR_DOMAIN, loggingEvent.Domain); } if (loggingEvent.Identity != null && loggingEvent.Identity.Length > 0) { writer.WriteAttributeString(ATTR_IDENTITY, loggingEvent.Identity); } if (loggingEvent.UserName != null && loggingEvent.UserName.Length > 0) { writer.WriteAttributeString(ATTR_USERNAME, loggingEvent.UserName); } // Append the message text writer.WriteStartElement(m_elmMessage); if (!this.Base64EncodeMessage) { Transform.WriteEscapedXmlString(writer, loggingEvent.RenderedMessage, this.InvalidCharReplacement); } else { byte[] messageBytes = Encoding.UTF8.GetBytes(loggingEvent.RenderedMessage); string base64Message = Convert.ToBase64String(messageBytes, 0, messageBytes.Length); Transform.WriteEscapedXmlString(writer, base64Message,this.InvalidCharReplacement); } writer.WriteEndElement(); PropertiesDictionary properties = loggingEvent.GetProperties(); // Append the properties text if (properties.Count > 0) { writer.WriteStartElement(m_elmProperties); foreach(System.Collections.DictionaryEntry entry in properties) { writer.WriteStartElement(m_elmData); writer.WriteAttributeString(ATTR_NAME, Transform.MaskXmlInvalidCharacters((string)entry.Key,this.InvalidCharReplacement)); // Use an ObjectRenderer to convert the object to a string string valueStr =null; if (!this.Base64EncodeProperties) { valueStr = Transform.MaskXmlInvalidCharacters(loggingEvent.Repository.RendererMap.FindAndRender(entry.Value),this.InvalidCharReplacement); } else { byte[] propertyValueBytes = Encoding.UTF8.GetBytes(loggingEvent.Repository.RendererMap.FindAndRender(entry.Value)); valueStr = Convert.ToBase64String(propertyValueBytes, 0, propertyValueBytes.Length); } writer.WriteAttributeString(ATTR_VALUE, valueStr); writer.WriteEndElement(); } writer.WriteEndElement(); } string exceptionStr = loggingEvent.GetExceptionString(); if (exceptionStr != null && exceptionStr.Length > 0) { // Append the stack trace line writer.WriteStartElement(m_elmException); Transform.WriteEscapedXmlString(writer, exceptionStr,this.InvalidCharReplacement); writer.WriteEndElement(); } if (LocationInfo) { LocationInfo locationInfo = loggingEvent.LocationInformation; writer.WriteStartElement(m_elmLocation); writer.WriteAttributeString(ATTR_CLASS, locationInfo.ClassName); writer.WriteAttributeString(ATTR_METHOD, locationInfo.MethodName); writer.WriteAttributeString(ATTR_FILE, locationInfo.FileName); writer.WriteAttributeString(ATTR_LINE, locationInfo.LineNumber); writer.WriteEndElement(); } writer.WriteEndElement(); } #endregion Override implementation of XMLLayoutBase #region Private Instance Fields /// <summary> /// The prefix to use for all generated element names /// </summary> private string m_prefix = PREFIX; private string m_elmEvent = ELM_EVENT; private string m_elmMessage = ELM_MESSAGE; private string m_elmData = ELM_DATA; private string m_elmProperties = ELM_PROPERTIES; private string m_elmException = ELM_EXCEPTION; private string m_elmLocation = ELM_LOCATION; private bool m_base64Message=false; private bool m_base64Properties=false; #endregion Private Instance Fields #region Private Static Fields private const string PREFIX = "log4net"; private const string ELM_EVENT = "event"; private const string ELM_MESSAGE = "message"; private const string ELM_PROPERTIES = "properties"; private const string ELM_GLOBAL_PROPERTIES = "global-properties"; private const string ELM_DATA = "data"; private const string ELM_EXCEPTION = "exception"; private const string ELM_LOCATION = "locationInfo"; private const string ATTR_LOGGER = "logger"; private const string ATTR_TIMESTAMP = "timestamp"; private const string ATTR_LEVEL = "level"; private const string ATTR_THREAD = "thread"; private const string ATTR_DOMAIN = "domain"; private const string ATTR_IDENTITY = "identity"; private const string ATTR_USERNAME = "username"; private const string ATTR_CLASS = "class"; private const string ATTR_METHOD = "method"; private const string ATTR_FILE = "file"; private const string ATTR_LINE = "line"; private const string ATTR_NAME = "name"; private const string ATTR_VALUE = "value"; #endregion Private Static Fields } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Net.Test.Common; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Http.Functional.Tests { public class HttpClientMiniStress { private static bool HttpStressEnabled => Configuration.Http.StressEnabled; [ConditionalTheory(nameof(HttpStressEnabled))] [MemberData(nameof(GetStressOptions))] public void SingleClient_ManyGets_Sync(int numRequests, int dop, HttpCompletionOption completionOption) { string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz"); using (var client = new HttpClient()) { Parallel.For(0, numRequests, new ParallelOptions { MaxDegreeOfParallelism = dop, TaskScheduler = new ThreadPerTaskScheduler() }, _ => { CreateServerAndGet(client, completionOption, responseText); }); } } [ConditionalTheory(nameof(HttpStressEnabled))] public async Task SingleClient_ManyGets_Async(int numRequests, int dop, HttpCompletionOption completionOption) { string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz"); using (var client = new HttpClient()) { await ForCountAsync(numRequests, dop, i => CreateServerAndGetAsync(client, completionOption, responseText)); } } [ConditionalTheory(nameof(HttpStressEnabled))] [MemberData(nameof(GetStressOptions))] public void ManyClients_ManyGets(int numRequests, int dop, HttpCompletionOption completionOption) { string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz"); Parallel.For(0, numRequests, new ParallelOptions { MaxDegreeOfParallelism = dop, TaskScheduler = new ThreadPerTaskScheduler() }, _ => { using (var client = new HttpClient()) { CreateServerAndGet(client, completionOption, responseText); } }); } [ConditionalTheory(nameof(HttpStressEnabled))] [MemberData(nameof(PostStressOptions))] public async Task ManyClients_ManyPosts_Async(int numRequests, int dop, int numBytes) { string responseText = CreateResponse(""); await ForCountAsync(numRequests, dop, async i => { using (HttpClient client = new HttpClient()) { await CreateServerAndPostAsync(client, numBytes, responseText); } }); } [ConditionalTheory(nameof(HttpStressEnabled))] [InlineData(1000000)] public void CreateAndDestroyManyClients(int numClients) { for (int i = 0; i < numClients; i++) { new HttpClient().Dispose(); } } [ConditionalTheory(nameof(HttpStressEnabled))] [InlineData(5000)] public async Task MakeAndFaultManyRequests(int numRequests) { await LoopbackServer.CreateServerAsync(async (server, url) => { using (var client = new HttpClient()) { client.Timeout = Timeout.InfiniteTimeSpan; var ep = (IPEndPoint)server.LocalEndPoint; Task<string>[] tasks = (from i in Enumerable.Range(0, numRequests) select client.GetStringAsync($"http://{ep.Address}:{ep.Port}")) .ToArray(); Assert.All(tasks, t => Assert.Equal(TaskStatus.WaitingForActivation, t.Status)); server.Dispose(); foreach (Task<string> task in tasks) { await Assert.ThrowsAnyAsync<HttpRequestException>(() => task); } } }, new LoopbackServer.Options { ListenBacklog = numRequests }); } public static IEnumerable<object[]> GetStressOptions() { foreach (int numRequests in new[] { 5000 }) // number of requests foreach (int dop in new[] { 1, 32 }) // number of threads foreach (var completionoption in new[] { HttpCompletionOption.ResponseContentRead, HttpCompletionOption.ResponseHeadersRead }) yield return new object[] { numRequests, dop, completionoption }; } private static void CreateServerAndGet(HttpClient client, HttpCompletionOption completionOption, string responseText) { LoopbackServer.CreateServerAsync((server, url) => { Task<HttpResponseMessage> getAsync = client.GetAsync(url, completionOption); LoopbackServer.AcceptSocketAsync(server, (s, stream, reader, writer) => { while (!string.IsNullOrEmpty(reader.ReadLine())) ; writer.Write(responseText); s.Shutdown(SocketShutdown.Send); return Task.CompletedTask; }).GetAwaiter().GetResult(); getAsync.GetAwaiter().GetResult().Dispose(); return Task.CompletedTask; }).GetAwaiter().GetResult(); } private static async Task CreateServerAndGetAsync(HttpClient client, HttpCompletionOption completionOption, string responseText) { await LoopbackServer.CreateServerAsync(async (server, url) => { Task<HttpResponseMessage> getAsync = client.GetAsync(url, completionOption); await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) => { while (!string.IsNullOrEmpty(await reader.ReadLineAsync().ConfigureAwait(false))) ; await writer.WriteAsync(responseText).ConfigureAwait(false); s.Shutdown(SocketShutdown.Send); }); (await getAsync.ConfigureAwait(false)).Dispose(); }); } public static IEnumerable<object[]> PostStressOptions() { foreach (int numRequests in new[] { 5000 }) // number of requests foreach (int dop in new[] { 1, 32 }) // number of threads foreach (int numBytes in new[] { 0, 100 }) // number of bytes to post yield return new object[] { numRequests, dop, numBytes }; } private static async Task CreateServerAndPostAsync(HttpClient client, int numBytes, string responseText) { await LoopbackServer.CreateServerAsync(async (server, url) => { var content = new ByteArrayContent(new byte[numBytes]); Task<HttpResponseMessage> postAsync = client.PostAsync(url, content); await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) => { while (!string.IsNullOrEmpty(await reader.ReadLineAsync().ConfigureAwait(false))) ; for (int i = 0; i < numBytes; i++) Assert.NotEqual(-1, reader.Read()); await writer.WriteAsync(responseText).ConfigureAwait(false); s.Shutdown(SocketShutdown.Send); }); (await postAsync.ConfigureAwait(false)).Dispose(); }); } [ConditionalFact(nameof(HttpStressEnabled))] public async Task UnreadResponseMessage_Collectible() { await LoopbackServer.CreateServerAsync(async (server, url) => { using (var client = new HttpClient()) { Func<Task<WeakReference>> getAsync = async () => new WeakReference(await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead)); Task<WeakReference> wrt = getAsync(); await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) => { while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ; await writer.WriteAsync(CreateResponse(new string('a', 32 * 1024))); WeakReference wr = wrt.GetAwaiter().GetResult(); Assert.True(SpinWait.SpinUntil(() => { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); return !wr.IsAlive; }, 10 * 1000), "Response object should have been collected"); }); } }); } private static string CreateResponse(string asciiBody) => $"HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "Content-Type: text/plain\r\n" + $"Content-Length: {asciiBody.Length}\r\n" + "\r\n" + $"{asciiBody}\r\n"; private static Task ForCountAsync(int count, int dop, Func<int, Task> bodyAsync) { var sched = new ThreadPerTaskScheduler(); int nextAvailableIndex = 0; return Task.WhenAll(Enumerable.Range(0, dop).Select(_ => Task.Factory.StartNew(async delegate { int index; while ((index = Interlocked.Increment(ref nextAvailableIndex) - 1) < count) { try { await bodyAsync(index); } catch { Volatile.Write(ref nextAvailableIndex, count); // avoid any further iterations throw; } } }, CancellationToken.None, TaskCreationOptions.None, sched).Unwrap())); } private sealed class ThreadPerTaskScheduler : TaskScheduler { protected override void QueueTask(Task task) => Task.Factory.StartNew(() => TryExecuteTask(task), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) => TryExecuteTask(task); protected override IEnumerable<Task> GetScheduledTasks() => null; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Xml; using System.Text.RegularExpressions; using System.Text; using Microsoft.Build.BuildEngine.Shared; namespace Microsoft.Build.BuildEngine { /// <summary> /// This class is used by the regular expression search/replace function to replace item references of the form /// @(itemtype->transform, separator) with the correct string. /// </summary> /// <owner>RGoel, SumedhK</owner> internal class ItemExpander { #region Regular expressions for item vectors /************************************************************************************************************************** * WARNING: The regular expressions below MUST be kept in sync with the expressions in the ProjectWriter class -- if the * description of an item vector changes, the expressions must be updated in both places. *************************************************************************************************************************/ // the leading characters that indicate the start of an item vector internal const string itemVectorPrefix = "@("; // complete description of an item vector, including the optional transform expression and separator specification private const string itemVectorSpecification = @"@\(\s* (?<TYPE>" + ProjectWriter.itemTypeOrMetadataNameSpecification + @") (?<TRANSFORM_SPECIFICATION>\s*->\s*'(?<TRANSFORM>[^']*)')? (?<SEPARATOR_SPECIFICATION>\s*,\s*'(?<SEPARATOR>[^']*)')? \s*\)"; // description of an item vector, including the optional transform expression, but not the separator specification private const string itemVectorWithoutSeparatorSpecification = @"@\(\s* (?<TYPE>" + ProjectWriter.itemTypeOrMetadataNameSpecification + @") (?<TRANSFORM_SPECIFICATION>\s*->\s*'(?<TRANSFORM>[^']*)')? \s*\)"; // regular expression used to match item vectors, including those embedded in strings internal static readonly Regex itemVectorPattern = new Regex(itemVectorSpecification, RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture); // regular expression used to match a list of item vectors that have no separator specification -- the item vectors // themselves may be optionally separated by semi-colons, or they might be all jammed together internal static readonly Regex listOfItemVectorsWithoutSeparatorsPattern = new Regex(@"^\s*(;\s*)*(" + itemVectorWithoutSeparatorSpecification + @"\s*(;\s*)*)+$", RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture); // the leading characters that indicate the start of an item metadata reference internal const string itemMetadataPrefix = "%("; // complete description of an item metadata reference, including the optional qualifying item type private const string itemMetadataSpecification = @"%\(\s* (?<ITEM_SPECIFICATION>(?<TYPE>" + ProjectWriter.itemTypeOrMetadataNameSpecification + @")\s*\.\s*)? (?<NAME>" + ProjectWriter.itemTypeOrMetadataNameSpecification + @") \s*\)"; // regular expression used to match item metadata references embedded in strings internal static readonly Regex itemMetadataPattern = new Regex(itemMetadataSpecification, RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture); // description of an item vector with a transform, split into two halves along the transform expression private const string itemVectorWithTransformLHS = @"@\(\s*" + ProjectWriter.itemTypeOrMetadataNameSpecification + @"\s*->\s*'[^']*"; private const string itemVectorWithTransformRHS = @"[^']*'(\s*,\s*'[^']*')?\s*\)"; // PERF WARNING: this Regex is complex and tends to run slowly // regular expression used to match item metadata references outside of item vector transforms internal static readonly Regex nonTransformItemMetadataPattern = new Regex(@"((?<=" + itemVectorWithTransformLHS + @")" + itemMetadataSpecification + @"(?!" + itemVectorWithTransformRHS + @")) | ((?<!" + itemVectorWithTransformLHS + @")" + itemMetadataSpecification + @"(?=" + itemVectorWithTransformRHS + @")) | ((?<!" + itemVectorWithTransformLHS + @")" + itemMetadataSpecification + @"(?!" + itemVectorWithTransformRHS + @"))", RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture); /************************************************************************************************************************** * WARNING: The regular expressions above MUST be kept in sync with the expressions in the ProjectWriter class. *************************************************************************************************************************/ #endregion #region Member data // When using this class to replace the item vector specification with the actual // list of items, we use this table to get the items private ReadOnlyLookup readOnlyLookup; // used when expanding item metadata during transforms private BuildItem itemUnderTransformation; // the XML node whose contents are being operated on by this class private XmlNode parentNode; #endregion #region Constructors /// <summary> /// Constructor, which captures the hashtable of items to use when expanding the item reference. /// </summary> private ItemExpander ( XmlNode parentNode, ReadOnlyLookup readOnlyLookup ) { this.parentNode = parentNode; this.readOnlyLookup = readOnlyLookup; } #endregion #region Methods /// <summary> /// Expands all item vectors embedded in the given string. /// </summary> /// <owner>SumedhK</owner> /// <param name="s"></param> /// <param name="parentNode"></param> /// <param name="itemsByType"></param> /// <returns>Given string, with embedded item vectors expanded.</returns> internal static string ExpandEmbeddedItemVectors(string s, XmlNode parentNode, ReadOnlyLookup readOnlyLookup) { // Before we do the expensive RegEx stuff, at least make sure there's // an @ sign in the expression somewhere. If not, skip all the hard work. if (s.IndexOf('@') != -1) { ItemExpander itemExpander = new ItemExpander(parentNode, readOnlyLookup); return itemVectorPattern.Replace(s, new MatchEvaluator(itemExpander.ExpandItemVector)); } else { return s; } } /// <summary> /// Attempts to extract the items in the given item vector. Item vectors embedded in strings, and item vectors with /// separator specifications are considered invalid, because it is not clear if those item vectors are meant to be lists /// or strings -- if the latter, the ExpandEmbeddedItemVectors() method should be used instead. /// </summary> /// <owner>SumedhK;RGoel</owner> /// <param name="itemVectorExpression"></param> /// <param name="parentNode"></param> /// <param name="itemsByType"></param> /// <returns>a virtual BuildItemGroup containing the items resulting from the expression, or null if the expression was invalid.</returns> internal static BuildItemGroup ItemizeItemVector ( string itemVectorExpression, XmlNode parentNode, ReadOnlyLookup readOnlyLookup ) { Match throwAwayMatch; return ItemExpander.ItemizeItemVector(itemVectorExpression, parentNode, readOnlyLookup, out throwAwayMatch); } /// <summary> /// Attempts to extract the items in the given item vector expression. Item vectors embedded in strings, /// and item vectors with separator specifications are considered invalid, because it is not clear /// if those item vectors are meant to be lists or strings -- if the latter, the ExpandEmbeddedItemVectors() /// method should be used instead. /// </summary> /// <param name="itemVectorExpression"></param> /// <param name="parentNode"></param> /// <param name="readOnlyLookup"></param> /// <param name="itemVectorMatch"></param> /// <returns>a virtual BuildItemGroup containing the items resulting from the expression, or null if the expression was invalid.</returns> /// <owner>SumedhK;RGoel</owner> internal static BuildItemGroup ItemizeItemVector ( string itemVectorExpression, XmlNode parentNode, ReadOnlyLookup readOnlyLookup, out Match itemVectorMatch ) { BuildItemGroup items = null; itemVectorMatch = GetItemVectorMatches(itemVectorExpression); if (itemVectorMatch?.Success == true) { // The method above reports a match if there are any // valid @(itemlist) references in the given expression. // If the passed-in expression contains exactly one item list reference, // with nothing else concatenated to the beginning or end, then proceed // with itemizing it, otherwise error. ProjectErrorUtilities.VerifyThrowInvalidProject(itemVectorMatch.Value == itemVectorExpression, parentNode, "EmbeddedItemVectorCannotBeItemized", itemVectorExpression); ItemExpander itemExpander = new ItemExpander(parentNode, readOnlyLookup); // If the reference contains a separator, we need to flatten the list into a scalar and then create // an item group with a single item. This is necessary for VSWhidbey 525917 - basically we need this // to be able to convert item lists with user specified separators into properties. if (itemVectorMatch.Groups["SEPARATOR_SPECIFICATION"].Length > 0) { string expandedItemVector = itemExpander.ExpandItemVector(itemVectorMatch); string itemType = itemVectorMatch.Groups["TYPE"].Value; items = new BuildItemGroup(); if (expandedItemVector.Length > 0) { items.AddNewItem(itemType, expandedItemVector); } } else { items = itemExpander.ItemizeItemVector(itemVectorMatch); } ErrorUtilities.VerifyThrow(items != null, "ItemizeItemVector shouldn't give us null."); } return items; } /// <summary> /// Returns true if the expression contains an item vector pattern, else returns false. /// </summary> internal static bool ExpressionContainsItemVector(string expression) { Match itemVectorMatch = GetItemVectorMatches(expression); if (itemVectorMatch?.Success == true) { return true; } return false; } /// <summary> /// Returns matches to an item expression pattern in the expression. /// </summary> private static Match GetItemVectorMatches(string expression) { Match itemVectorMatch = null; // Before we do the expensive RegEx stuff, at least make sure there's // an @ sign in the expression somewhere. If not, skip all the hard work. if (expression.IndexOf('@') != -1) { itemVectorMatch = itemVectorPattern.Match(expression); } return itemVectorMatch; } /// <summary> /// Extracts the items in the given item vector. /// </summary> /// <owner>SumedhK</owner> /// <param name="itemVector"></param> /// <returns>The contents of the item vector (with transforms applied).</returns> private BuildItemGroup ItemizeItemVector(Match itemVector) { ErrorUtilities.VerifyThrow(itemVector.Success, "Need a valid item vector."); string itemType = itemVector.Groups["TYPE"].Value; string transform = (itemVector.Groups["TRANSFORM_SPECIFICATION"].Length > 0) ? itemVector.Groups["TRANSFORM"].Value : null; BuildItemGroup items = null; if (readOnlyLookup != null) { items = readOnlyLookup.GetItems(itemType); } if (items == null) { items = new BuildItemGroup(); } else { items = items.Clone(transform != null /* deep clone on transforms because we're actually creating new items */); } if (transform != null) { foreach (BuildItem item in items) { itemUnderTransformation = item; item.SetFinalItemSpecEscaped(itemMetadataPattern.Replace(transform, new MatchEvaluator(ExpandItemMetadata))); } } return items; } /// <summary> /// Expands a single item vector. /// /// Item vectors are composed of a name, a transform, and a separator i.e. /// /// @(&lt;name&gt;->'&lt;transform&gt;','&lt;separator&gt;') /// /// If a separator is not specified it defaults to a semi-colon. The transform expression is also optional, but if /// specified, it allows each item in the vector to have its item-spec converted to a different form. The transform /// expression can reference any custom metadata defined on the item, as well as the pre-defined item-spec modifiers. /// /// NOTE: /// 1) white space between &lt;name&gt;, &lt;transform&gt; and &lt;separator&gt; is ignored /// i.e. @(&lt;name&gt;, '&lt;separator&gt;') is valid /// 2) the separator is not restricted to be a single character, it can be a string /// 3) the separator can be an empty string i.e. @(&lt;name&gt;,'') /// 4) specifying an empty transform is NOT the same as specifying no transform -- the former will reduce all item-specs /// to empty strings /// </summary> /// <remarks>This is the MatchEvaluator delegate passed to Regex.Replace().</remarks> /// <example> /// if @(files) is a vector for the files a.txt and b.txt, then: /// /// "my list: @(files)" expands to "my list: a.txt;b.txt" /// /// "my list: @(files,' ')" expands to "my list: a.txt b.txt" /// /// "my list: @(files, '')" expands to "my list: a.txtb.txt" /// /// "my list: @(files, '; ')" expands to "my list: a.txt; b.txt" /// /// "my list: @(files->'%(Filename)')" expands to "my list: a;b" /// /// "my list: @(files -> 'temp\%(Filename).xml', ' ') expands to "my list: temp\a.xml temp\b.xml" /// /// "my list: @(files->'') expands to "my list: ;" /// </example> /// <owner>SumedhK</owner> /// <param name="itemVector"></param> /// <param name="isUnknownItemType">(out) true if the referenced item does not exist</param> /// <returns>expanded item vector</returns> private string ExpandItemVector(Match itemVector) { ErrorUtilities.VerifyThrow(itemVector.Success, "Need a valid item vector."); string separator = (itemVector.Groups["SEPARATOR_SPECIFICATION"].Length != 0) ? itemVector.Groups["SEPARATOR"].Value : ";"; BuildItemGroup items = ItemizeItemVector(itemVector); if (items.Count > 0) { StringBuilder expandedItemVector = new StringBuilder(); for (int i = 0; i < items.Count; i++) { expandedItemVector.Append(items[i].FinalItemSpecEscaped); if (i < (items.Count - 1)) { expandedItemVector.Append(separator); } } return expandedItemVector.ToString(); } else { return String.Empty; } } /// <summary> /// Retrieves the value of the given metadata for the item currently being transformed. /// </summary> /// <remarks>This method is a MatchEvaluator delegate passed to Regex.Replace().</remarks> /// <owner>SumedhK</owner> /// <param name="itemMetadataMatch"></param> /// <returns>item metadata value</returns> private string ExpandItemMetadata(Match itemMetadataMatch) { ErrorUtilities.VerifyThrow(itemUnderTransformation != null, "Need item to get metadata value from."); string itemMetadataName = itemMetadataMatch.Groups["NAME"].Value; ProjectErrorUtilities.VerifyThrowInvalidProject(itemMetadataMatch.Groups["ITEM_SPECIFICATION"].Length == 0, parentNode, "QualifiedMetadataInTransformNotAllowed", itemMetadataMatch.Value, itemMetadataName); string itemMetadataValue = null; try { itemMetadataValue = itemUnderTransformation.GetEvaluatedMetadataEscaped(itemMetadataName); } catch (InvalidOperationException e) { ProjectErrorUtilities.VerifyThrowInvalidProject(false, parentNode, "CannotEvaluateItemMetadata", itemMetadataName, e.Message); } return itemMetadataValue; } #endregion } }
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 ND.MCJ.DataService.Areas.HelpPage.Models; namespace ND.MCJ.DataService.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); } } } }
using BlackBox.Service; using IFC2X3; using System; using EbInstanceModel; using System.Collections.Generic; namespace BlackBox.Predefined { /// <summary> /// Cut cope. /// </summary> public class BbCutCope : BbFeature { private IfcOpeningElement _ifcOpeningElement; private IfcRelVoidsElement _ifcRelVoidsElement; [EarlyBindingInstance] public override IfcObject IfcObject { get { return _ifcOpeningElement; } protected set { var a = value as IfcOpeningElement; if (a != null) _ifcOpeningElement = a; } } [EarlyBindingInstance] public IfcRelVoidsElement IfcRelVoidsElement { get { return _ifcRelVoidsElement; } } BbCutCope( BbElement hostElement, double copeWidth, double copeDepth, double copeRadius, SemCopeLocation copeLocation) { BbCopeProfile profile = BbCopeProfile.Create(copeWidth, copeDepth, copeRadius, copeLocation); var mainPart = hostElement as BbPiece; if (mainPart == null) return; BbPosition3D pos; switch (copeLocation) { case SemCopeLocation.BottomLeft: pos = BbPosition3D.Create( BbCoordinate3D.Create(new double[] { mainPart.Profile.Width / 2, -mainPart.Profile.Depth / 2, 0 }), BbHeaderSetting.Setting3D.XAxisMinus, BbHeaderSetting.Setting3D.ZAxis); break; case SemCopeLocation.BottomRight: pos = BbPosition3D.Create( BbCoordinate3D.Create(new double[] { mainPart.Profile.Width / 2, - mainPart.Profile.Depth / 2, mainPart.Length }), BbHeaderSetting.Setting3D.XAxisMinus, BbHeaderSetting.Setting3D.ZAxis); break; case SemCopeLocation.TopRight: pos = BbPosition3D.Create( BbCoordinate3D.Create(new double[] { mainPart.Profile.Width / 2, mainPart.Profile.Depth / 2, mainPart.Length }), BbHeaderSetting.Setting3D.XAxisMinus, BbHeaderSetting.Setting3D.ZAxis); break; default: // TopLeft pos = BbPosition3D.Create( BbCoordinate3D.Create(new double[] { mainPart.Profile.Width / 2, mainPart.Profile.Depth / 2, 0 }), BbHeaderSetting.Setting3D.XAxisMinus, BbHeaderSetting.Setting3D.ZAxis); break; } ObjectBbLocalPlacement = BbLocalPlacement3D.Create( hostElement.ObjectBbLocalPlacement, pos); BbExtrudedGeometry bbExtrudedGeometry = BbExtrudedGeometry.Create( profile, BbHeaderSetting.Setting3D.DefaultBbPosition3D, BbHeaderSetting.Setting3D.ZAxis, mainPart.Profile.Width); _ifcOpeningElement = new IfcOpeningElement { GlobalId = IfcGloballyUniqueId.NewGuid(), OwnerHistory = hostElement.IfcObject.OwnerHistory, // Name = // Description = ObjectType = "Opening", ObjectPlacement = ObjectBbLocalPlacement.IfcLocalPlacement, Representation = bbExtrudedGeometry.IfcProductDefinitionShape, }; _ifcRelVoidsElement = new IfcRelVoidsElement { GlobalId = IfcGloballyUniqueId.NewGuid(), OwnerHistory = hostElement.IfcObject.OwnerHistory, Name = "Cope", RelatingBuildingElement = hostElement.IfcObject as IfcElement, RelatedOpeningElement = _ifcOpeningElement, }; } public BbCutCope( BbElement hostElement, double copeWidth, double copeDepth, double copeRadius, double[] position) { BbCopeProfile profile = BbCopeProfile.Create(copeWidth, copeDepth, copeRadius); var mainPart = hostElement as BbPiece; if (mainPart == null) return; BbPosition3D pos = BbPosition3D.Create( BbCoordinate3D.Create(position), BbHeaderSetting.Setting3D.XAxisMinus, BbHeaderSetting.Setting3D.ZAxis); ObjectBbLocalPlacement = BbLocalPlacement3D.Create( hostElement.ObjectBbLocalPlacement, pos); BbExtrudedGeometry bbExtrudedGeometry = BbExtrudedGeometry.Create( profile, BbHeaderSetting.Setting3D.DefaultBbPosition3D, BbHeaderSetting.Setting3D.ZAxis, mainPart.Profile.Width); _ifcOpeningElement = new IfcOpeningElement { GlobalId = IfcGloballyUniqueId.NewGuid(), OwnerHistory = hostElement.IfcObject.OwnerHistory, // Name = // Description = ObjectType = "Opening", ObjectPlacement = ObjectBbLocalPlacement.IfcLocalPlacement, Representation = bbExtrudedGeometry.IfcProductDefinitionShape, }; _ifcRelVoidsElement = new IfcRelVoidsElement { GlobalId = IfcGloballyUniqueId.NewGuid(), OwnerHistory = hostElement.IfcObject.OwnerHistory, Name = "Cope", RelatingBuildingElement = hostElement.IfcObject as IfcElement, RelatedOpeningElement = _ifcOpeningElement, }; } public BbCutCope( BbElement hostElement, BbProfile profile, double length, double[] zAxis, double[] xAxis, double[] extrudeDirection, double[] position) { //ObjectLocalPlacement = new LocalPlacement3D(hostElement.ObjectLocalPlacement, new Position3D(position)); /// from main piece BbPosition3D pos = BbPosition3D.Create( BbCoordinate3D.Create(position), BbDirection3D.Create(zAxis), BbDirection3D.Create(xAxis)); ObjectBbLocalPlacement = BbLocalPlacement3D.Create( hostElement.ObjectBbLocalPlacement, pos); BbDirection3D exDir; if (Math.Round(extrudeDirection[0], 8) == 0.0 && Math.Round(extrudeDirection[0], 8) == 0 && Math.Round(extrudeDirection[0], 8) == 1) { exDir = BbHeaderSetting.Setting3D.ZAxis; } else { exDir = BbDirection3D.Create(extrudeDirection); } BbExtrudedGeometry bbExtrudedGeometry = BbExtrudedGeometry.Create( profile, BbHeaderSetting.Setting3D.DefaultBbPosition3D, exDir, length); _ifcOpeningElement = new IfcOpeningElement { GlobalId = IfcGloballyUniqueId.NewGuid(), OwnerHistory = hostElement.IfcObject.OwnerHistory, // Name = // Description = ObjectType = "Opening", ObjectPlacement = ObjectBbLocalPlacement.IfcLocalPlacement, Representation = bbExtrudedGeometry.IfcProductDefinitionShape, }; _ifcRelVoidsElement = new IfcRelVoidsElement { GlobalId = IfcGloballyUniqueId.NewGuid(), OwnerHistory = hostElement.IfcObject.OwnerHistory, Name = "Cope", RelatingBuildingElement = hostElement.IfcObject as IfcElement, RelatedOpeningElement = _ifcOpeningElement, }; } private BbCutCope() { } public static BbCutCope Create(BbElement hostElement, BbProfile profile, double length, double[] zAxis, double[] xAxis, double[] extrudeDirection, double[] position) { var cutCope = new BbCutCope(hostElement, profile, length, zAxis, xAxis, extrudeDirection, position); BbInstanceDB.AddToExport(cutCope); return cutCope; } public static BbCutCope Create(BbElement hostElement, double copeWidth, double copeDepth, double copeRadius, double[] position) { var cutCope = new BbCutCope(hostElement, copeWidth, copeDepth, copeRadius, position); BbInstanceDB.AddToExport(cutCope); return cutCope; } public static BbCutCope Create(BbElement hostElement, double copeWidth, double copeDepth, double copeRadius, SemCopeLocation copeLocation) { var cutCope = new BbCutCope(hostElement, copeWidth, copeDepth, copeRadius, copeLocation); BbInstanceDB.AddToExport(cutCope); return cutCope; } public static BbCutCope Create(BbElement hostElement, double copeWidth, double copeDepth, double copeRadius, SemCopeLocation copeLocation, BbPropertySet bbPropertySet, double chamferLength, double chamferDepth, double flangeChamferLength, double flangeChamferWidth, double flangeNotchLength, double flangeNotchWidth, double flangeNotchRadius, double notchLength, double notchDepth, double notchRadius) { var cutCope = new BbCutCope(hostElement, copeWidth, copeDepth, copeRadius, copeLocation); cutCope.AddCutCopeProperty(bbPropertySet, chamferLength, chamferDepth, flangeChamferLength, flangeChamferWidth, flangeNotchLength, flangeNotchWidth, flangeNotchRadius, notchLength, notchDepth, notchRadius); BbInstanceDB.AddToExport(cutCope); return cutCope; } public void AddCutCopeProperty(BbPropertySet bbPropertySet, double chamferLength, double chamferDepth, double flangeChamferLength, double flangeChamferWidth, double flangeNotchLength, double flangeNotchWidth, double flangeNotchRadius, double notchLength, double notchDepth, double notchRadius ) { bbPropertySet.AddProperty(BbSingleProperty.Create("ChamferLength", chamferLength, typeof(IfcPositiveLengthMeasure))); bbPropertySet.AddProperty(BbSingleProperty.Create("ChamferDepth", chamferDepth, typeof(IfcPositiveLengthMeasure))); bbPropertySet.AddProperty(BbSingleProperty.Create("FlangeChamferLength", flangeChamferLength, typeof(IfcPositiveLengthMeasure))); bbPropertySet.AddProperty(BbSingleProperty.Create("FlangeChamferWidth", flangeChamferWidth, typeof(IfcPositiveLengthMeasure))); bbPropertySet.AddProperty(BbSingleProperty.Create("FlangeNotchLength", flangeNotchLength, typeof(IfcPositiveLengthMeasure))); bbPropertySet.AddProperty(BbSingleProperty.Create("FlangeNotchWidth", flangeNotchWidth, typeof(IfcPositiveLengthMeasure))); bbPropertySet.AddProperty(BbSingleProperty.Create("FlangeNotchRadius", flangeNotchRadius, typeof(IfcPositiveLengthMeasure))); bbPropertySet.AddProperty(BbSingleProperty.Create("NotchLength", notchLength, typeof(IfcPositiveLengthMeasure))); bbPropertySet.AddProperty(BbSingleProperty.Create("NotchDepth", notchDepth, typeof(IfcPositiveLengthMeasure))); bbPropertySet.AddProperty(BbSingleProperty.Create("NotchRadius", notchRadius, typeof(IfcPositiveLengthMeasure))); } public static ICollection<BbCutCope> Retrieve(BbElement element) { var ret = new List<BbCutCope>(); //if (!EarlyBindingInstanceModel.TheModel.DataByType.ContainsKey("IfcRelVoidsElement")) return null; var collection = EarlyBindingInstanceModel.GetDataByType("IfcRelVoidsElement").Values; //if (collection.Count != 1) throw new NotImplementedException(); foreach (var item in collection) { var theItem = item as IfcRelVoidsElement; if (theItem == null) continue; // need modification //if (theItem.RelatingBuildingElement.EIN == element.IfcObject.EIN) //{ // var OpeningElement = theItem.RelatedOpeningElement as IfcOpeningElement; // if (theItem.Name == "Cope") // { // var semCutCope = new BbCutCope { ifcOpeningElement = OpeningElement, ifcRelVoidsElement = theItem }; // //BbInstanceDB.Add(semCutCope); // ret.Add(semCutCope); // // Retrieve localPlacement of BbCutCope // var placement = semCutCope.ifcOpeningElement.ObjectPlacement as IfcLocalPlacement; // var objectLocalPlacement = new BbLocalPlacement3D { IfcLocalPlacement = placement }; // semCutCope.ObjectBbLocalPlacement = objectLocalPlacement; // //Retrieve related Sems // var semPosition3D = BbFeature.RetrievePosition(semCutCope); // var semExtrudedGeometry = BbExtrudedGeometry.RetrieveFromFeature(semCutCope); // var semCopeProfile = BbCopeProfile.Retrieve(semExtrudedGeometry); // } //} } return ret; } } }
// Copyright 2018 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 gaxres = Google.Api.Gax.ResourceNames; using pb = Google.Protobuf; using pbwkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; 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.ErrorReporting.V1Beta1 { /// <summary> /// Settings for a <see cref="ErrorStatsServiceClient"/>. /// </summary> public sealed partial class ErrorStatsServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary> /// Get a new instance of the default <see cref="ErrorStatsServiceSettings"/>. /// </summary> /// <returns> /// A new instance of the default <see cref="ErrorStatsServiceSettings"/>. /// </returns> public static ErrorStatsServiceSettings GetDefault() => new ErrorStatsServiceSettings(); /// <summary> /// Constructs a new <see cref="ErrorStatsServiceSettings"/> object with default settings. /// </summary> public ErrorStatsServiceSettings() { } private ErrorStatsServiceSettings(ErrorStatsServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); ListGroupStatsSettings = existing.ListGroupStatsSettings; ListEventsSettings = existing.ListEventsSettings; DeleteEventsSettings = existing.DeleteEventsSettings; OnCopy(existing); } partial void OnCopy(ErrorStatsServiceSettings existing); /// <summary> /// The filter specifying which RPC <see cref="grpccore::StatusCode"/>s are eligible for retry /// for "Idempotent" <see cref="ErrorStatsServiceClient"/> RPC methods. /// </summary> /// <remarks> /// The eligible RPC <see cref="grpccore::StatusCode"/>s for retry for "Idempotent" RPC methods are: /// <list type="bullet"> /// <item><description><see cref="grpccore::StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="grpccore::StatusCode.Unavailable"/></description></item> /// </list> /// </remarks> public static sys::Predicate<grpccore::RpcException> IdempotentRetryFilter { get; } = gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.DeadlineExceeded, grpccore::StatusCode.Unavailable); /// <summary> /// The filter specifying which RPC <see cref="grpccore::StatusCode"/>s are eligible for retry /// for "NonIdempotent" <see cref="ErrorStatsServiceClient"/> RPC methods. /// </summary> /// <remarks> /// There are no RPC <see cref="grpccore::StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods. /// </remarks> public static sys::Predicate<grpccore::RpcException> NonIdempotentRetryFilter { get; } = gaxgrpc::RetrySettings.FilterForStatusCodes(); /// <summary> /// "Default" retry backoff for <see cref="ErrorStatsServiceClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" retry backoff for <see cref="ErrorStatsServiceClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" retry backoff for <see cref="ErrorStatsServiceClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial delay: 100 milliseconds</description></item> /// <item><description>Maximum delay: 60000 milliseconds</description></item> /// <item><description>Delay multiplier: 1.3</description></item> /// </list> /// </remarks> public static gaxgrpc::BackoffSettings GetDefaultRetryBackoff() => new gaxgrpc::BackoffSettings( delay: sys::TimeSpan.FromMilliseconds(100), maxDelay: sys::TimeSpan.FromMilliseconds(60000), delayMultiplier: 1.3 ); /// <summary> /// "Default" timeout backoff for <see cref="ErrorStatsServiceClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" timeout backoff for <see cref="ErrorStatsServiceClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" timeout backoff for <see cref="ErrorStatsServiceClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Maximum timeout: 20000 milliseconds</description></item> /// </list> /// </remarks> public static gaxgrpc::BackoffSettings GetDefaultTimeoutBackoff() => new gaxgrpc::BackoffSettings( delay: sys::TimeSpan.FromMilliseconds(20000), maxDelay: sys::TimeSpan.FromMilliseconds(20000), delayMultiplier: 1.0 ); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ErrorStatsServiceClient.ListGroupStats</c> and <c>ErrorStatsServiceClient.ListGroupStatsAsync</c>. /// </summary> /// <remarks> /// The default <c>ErrorStatsServiceClient.ListGroupStats</c> and /// <c>ErrorStatsServiceClient.ListGroupStatsAsync</c> <see cref="gaxgrpc::RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 20000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="grpccore::StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="grpccore::StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public gaxgrpc::CallSettings ListGroupStatsSettings { get; set; } = gaxgrpc::CallSettings.FromCallTiming( gaxgrpc::CallTiming.FromRetry(new gaxgrpc::RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ErrorStatsServiceClient.ListEvents</c> and <c>ErrorStatsServiceClient.ListEventsAsync</c>. /// </summary> /// <remarks> /// The default <c>ErrorStatsServiceClient.ListEvents</c> and /// <c>ErrorStatsServiceClient.ListEventsAsync</c> <see cref="gaxgrpc::RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 20000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="grpccore::StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="grpccore::StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public gaxgrpc::CallSettings ListEventsSettings { get; set; } = gaxgrpc::CallSettings.FromCallTiming( gaxgrpc::CallTiming.FromRetry(new gaxgrpc::RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ErrorStatsServiceClient.DeleteEvents</c> and <c>ErrorStatsServiceClient.DeleteEventsAsync</c>. /// </summary> /// <remarks> /// The default <c>ErrorStatsServiceClient.DeleteEvents</c> and /// <c>ErrorStatsServiceClient.DeleteEventsAsync</c> <see cref="gaxgrpc::RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 20000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="grpccore::StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="grpccore::StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public gaxgrpc::CallSettings DeleteEventsSettings { get; set; } = gaxgrpc::CallSettings.FromCallTiming( gaxgrpc::CallTiming.FromRetry(new gaxgrpc::RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// Creates a deep clone of this object, with all the same property values. /// </summary> /// <returns>A deep clone of this <see cref="ErrorStatsServiceSettings"/> object.</returns> public ErrorStatsServiceSettings Clone() => new ErrorStatsServiceSettings(this); } /// <summary> /// ErrorStatsService client wrapper, for convenient use. /// </summary> public abstract partial class ErrorStatsServiceClient { /// <summary> /// The default endpoint for the ErrorStatsService service, which is a host of "clouderrorreporting.googleapis.com" and a port of 443. /// </summary> public static gaxgrpc::ServiceEndpoint DefaultEndpoint { get; } = new gaxgrpc::ServiceEndpoint("clouderrorreporting.googleapis.com", 443); /// <summary> /// The default ErrorStatsService scopes. /// </summary> /// <remarks> /// The default ErrorStatsService 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", }); private static readonly gaxgrpc::ChannelPool s_channelPool = new gaxgrpc::ChannelPool(DefaultScopes); /// <summary> /// Asynchronously creates a <see cref="ErrorStatsServiceClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. See the example for how to use custom credentials. /// </summary> /// <example> /// This sample shows how to create a client using default credentials: /// <code> /// using Google.Cloud.ErrorReporting.V1Beta1; /// ... /// // When running on Google Cloud Platform this will use the project Compute Credential. /// // Or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of a JSON /// // credential file to use that credential. /// ErrorStatsServiceClient client = await ErrorStatsServiceClient.CreateAsync(); /// </code> /// This sample shows how to create a client using credentials loaded from a JSON file: /// <code> /// using Google.Cloud.ErrorReporting.V1Beta1; /// using Google.Apis.Auth.OAuth2; /// using Grpc.Auth; /// using Grpc.Core; /// ... /// GoogleCredential cred = GoogleCredential.FromFile("/path/to/credentials.json"); /// Channel channel = new Channel( /// ErrorStatsServiceClient.DefaultEndpoint.Host, ErrorStatsServiceClient.DefaultEndpoint.Port, cred.ToChannelCredentials()); /// ErrorStatsServiceClient client = ErrorStatsServiceClient.Create(channel); /// ... /// // Shutdown the channel when it is no longer required. /// await channel.ShutdownAsync(); /// </code> /// </example> /// <param name="endpoint">Optional <see cref="gaxgrpc::ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="ErrorStatsServiceSettings"/>.</param> /// <returns>The task representing the created <see cref="ErrorStatsServiceClient"/>.</returns> public static async stt::Task<ErrorStatsServiceClient> CreateAsync(gaxgrpc::ServiceEndpoint endpoint = null, ErrorStatsServiceSettings settings = null) { grpccore::Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false); return Create(channel, settings); } /// <summary> /// Synchronously creates a <see cref="ErrorStatsServiceClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. See the example for how to use custom credentials. /// </summary> /// <example> /// This sample shows how to create a client using default credentials: /// <code> /// using Google.Cloud.ErrorReporting.V1Beta1; /// ... /// // When running on Google Cloud Platform this will use the project Compute Credential. /// // Or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of a JSON /// // credential file to use that credential. /// ErrorStatsServiceClient client = ErrorStatsServiceClient.Create(); /// </code> /// This sample shows how to create a client using credentials loaded from a JSON file: /// <code> /// using Google.Cloud.ErrorReporting.V1Beta1; /// using Google.Apis.Auth.OAuth2; /// using Grpc.Auth; /// using Grpc.Core; /// ... /// GoogleCredential cred = GoogleCredential.FromFile("/path/to/credentials.json"); /// Channel channel = new Channel( /// ErrorStatsServiceClient.DefaultEndpoint.Host, ErrorStatsServiceClient.DefaultEndpoint.Port, cred.ToChannelCredentials()); /// ErrorStatsServiceClient client = ErrorStatsServiceClient.Create(channel); /// ... /// // Shutdown the channel when it is no longer required. /// channel.ShutdownAsync().Wait(); /// </code> /// </example> /// <param name="endpoint">Optional <see cref="gaxgrpc::ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="ErrorStatsServiceSettings"/>.</param> /// <returns>The created <see cref="ErrorStatsServiceClient"/>.</returns> public static ErrorStatsServiceClient Create(gaxgrpc::ServiceEndpoint endpoint = null, ErrorStatsServiceSettings settings = null) { grpccore::Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint); return Create(channel, settings); } /// <summary> /// Creates a <see cref="ErrorStatsServiceClient"/> which uses the specified channel for remote operations. /// </summary> /// <param name="channel">The <see cref="grpccore::Channel"/> for remote operations. Must not be null.</param> /// <param name="settings">Optional <see cref="ErrorStatsServiceSettings"/>.</param> /// <returns>The created <see cref="ErrorStatsServiceClient"/>.</returns> public static ErrorStatsServiceClient Create(grpccore::Channel channel, ErrorStatsServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(channel, nameof(channel)); return Create(new grpccore::DefaultCallInvoker(channel), settings); } /// <summary> /// Creates a <see cref="ErrorStatsServiceClient"/> 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="ErrorStatsServiceSettings"/>.</param> /// <returns>The created <see cref="ErrorStatsServiceClient"/>.</returns> public static ErrorStatsServiceClient Create(grpccore::CallInvoker callInvoker, ErrorStatsServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpccore::Interceptors.Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpccore::Interceptors.CallInvokerExtensions.Intercept(callInvoker, interceptor); } ErrorStatsService.ErrorStatsServiceClient grpcClient = new ErrorStatsService.ErrorStatsServiceClient(callInvoker); return new ErrorStatsServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create(gaxgrpc::ServiceEndpoint, ErrorStatsServiceSettings)"/> /// and <see cref="CreateAsync(gaxgrpc::ServiceEndpoint, ErrorStatsServiceSettings)"/>. Channels which weren't automatically /// created are not affected. /// </summary> /// <remarks>After calling this method, further calls to <see cref="Create(gaxgrpc::ServiceEndpoint, ErrorStatsServiceSettings)"/> /// and <see cref="CreateAsync(gaxgrpc::ServiceEndpoint, ErrorStatsServiceSettings)"/> 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() => s_channelPool.ShutdownChannelsAsync(); /// <summary> /// The underlying gRPC ErrorStatsService client. /// </summary> public virtual ErrorStatsService.ErrorStatsServiceClient GrpcClient { get { throw new sys::NotImplementedException(); } } /// <summary> /// Lists the specified groups. /// </summary> /// <param name="projectName"> /// [Required] The resource name of the Google Cloud Platform project. Written /// as &lt;code&gt;projects/&lt;/code&gt; plus the /// &lt;a href="https://support.google.com/cloud/answer/6158840"&gt;Google Cloud /// Platform project ID&lt;/a&gt;. /// /// Example: &lt;code&gt;projects/my-project-123&lt;/code&gt;. /// </param> /// <param name="timeRange"> /// [Optional] List data for the given time range. /// If not set a default time range is used. The field time_range_begin /// in the response will specify the beginning of this time range. /// Only &lt;code&gt;ErrorGroupStats&lt;/code&gt; with a non-zero count in the given time /// range are returned, unless the request contains an explicit group_id list. /// If a group_id list is given, also &lt;code&gt;ErrorGroupStats&lt;/code&gt; with zero /// occurrences are returned. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="ErrorGroupStats"/> resources. /// </returns> public virtual gax::PagedAsyncEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStatsAsync( gaxres::ProjectName projectName, QueryTimeRange timeRange, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListGroupStatsAsync( new ListGroupStatsRequest { ProjectNameAsProjectName = gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName)), TimeRange = gax::GaxPreconditions.CheckNotNull(timeRange, nameof(timeRange)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists the specified groups. /// </summary> /// <param name="projectName"> /// [Required] The resource name of the Google Cloud Platform project. Written /// as &lt;code&gt;projects/&lt;/code&gt; plus the /// &lt;a href="https://support.google.com/cloud/answer/6158840"&gt;Google Cloud /// Platform project ID&lt;/a&gt;. /// /// Example: &lt;code&gt;projects/my-project-123&lt;/code&gt;. /// </param> /// <param name="timeRange"> /// [Optional] List data for the given time range. /// If not set a default time range is used. The field time_range_begin /// in the response will specify the beginning of this time range. /// Only &lt;code&gt;ErrorGroupStats&lt;/code&gt; with a non-zero count in the given time /// range are returned, unless the request contains an explicit group_id list. /// If a group_id list is given, also &lt;code&gt;ErrorGroupStats&lt;/code&gt; with zero /// occurrences are returned. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="ErrorGroupStats"/> resources. /// </returns> public virtual gax::PagedEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStats( gaxres::ProjectName projectName, QueryTimeRange timeRange, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListGroupStats( new ListGroupStatsRequest { ProjectNameAsProjectName = gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName)), TimeRange = gax::GaxPreconditions.CheckNotNull(timeRange, nameof(timeRange)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists the specified groups. /// </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="ErrorGroupStats"/> resources. /// </returns> public virtual gax::PagedAsyncEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStatsAsync( ListGroupStatsRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Lists the specified groups. /// </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="ErrorGroupStats"/> resources. /// </returns> public virtual gax::PagedEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStats( ListGroupStatsRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Lists the specified events. /// </summary> /// <param name="projectName"> /// [Required] The resource name of the Google Cloud Platform project. Written /// as `projects/` plus the /// [Google Cloud Platform project /// ID](https://support.google.com/cloud/answer/6158840). /// Example: `projects/my-project-123`. /// </param> /// <param name="groupId"> /// [Required] The group for which events shall be returned. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="ErrorEvent"/> resources. /// </returns> public virtual gax::PagedAsyncEnumerable<ListEventsResponse, ErrorEvent> ListEventsAsync( gaxres::ProjectName projectName, string groupId, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListEventsAsync( new ListEventsRequest { ProjectNameAsProjectName = gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName)), GroupId = gax::GaxPreconditions.CheckNotNullOrEmpty(groupId, nameof(groupId)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists the specified events. /// </summary> /// <param name="projectName"> /// [Required] The resource name of the Google Cloud Platform project. Written /// as `projects/` plus the /// [Google Cloud Platform project /// ID](https://support.google.com/cloud/answer/6158840). /// Example: `projects/my-project-123`. /// </param> /// <param name="groupId"> /// [Required] The group for which events shall be returned. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="ErrorEvent"/> resources. /// </returns> public virtual gax::PagedEnumerable<ListEventsResponse, ErrorEvent> ListEvents( gaxres::ProjectName projectName, string groupId, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListEvents( new ListEventsRequest { ProjectNameAsProjectName = gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName)), GroupId = gax::GaxPreconditions.CheckNotNullOrEmpty(groupId, nameof(groupId)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists the specified events. /// </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="ErrorEvent"/> resources. /// </returns> public virtual gax::PagedAsyncEnumerable<ListEventsResponse, ErrorEvent> ListEventsAsync( ListEventsRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Lists the specified events. /// </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="ErrorEvent"/> resources. /// </returns> public virtual gax::PagedEnumerable<ListEventsResponse, ErrorEvent> ListEvents( ListEventsRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="projectName"> /// [Required] The resource name of the Google Cloud Platform project. Written /// as `projects/` plus the /// [Google Cloud Platform project /// ID](https://support.google.com/cloud/answer/6158840). /// Example: `projects/my-project-123`. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<DeleteEventsResponse> DeleteEventsAsync( gaxres::ProjectName projectName, gaxgrpc::CallSettings callSettings = null) => DeleteEventsAsync( new DeleteEventsRequest { ProjectNameAsProjectName = gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName)), }, callSettings); /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="projectName"> /// [Required] The resource name of the Google Cloud Platform project. Written /// as `projects/` plus the /// [Google Cloud Platform project /// ID](https://support.google.com/cloud/answer/6158840). /// Example: `projects/my-project-123`. /// </param> /// <param name="cancellationToken"> /// A <see cref="st::CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<DeleteEventsResponse> DeleteEventsAsync( gaxres::ProjectName projectName, st::CancellationToken cancellationToken) => DeleteEventsAsync( projectName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="projectName"> /// [Required] The resource name of the Google Cloud Platform project. Written /// as `projects/` plus the /// [Google Cloud Platform project /// ID](https://support.google.com/cloud/answer/6158840). /// Example: `projects/my-project-123`. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual DeleteEventsResponse DeleteEvents( gaxres::ProjectName projectName, gaxgrpc::CallSettings callSettings = null) => DeleteEvents( new DeleteEventsRequest { ProjectNameAsProjectName = gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName)), }, callSettings); /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<DeleteEventsResponse> DeleteEventsAsync( DeleteEventsRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="cancellationToken"> /// A <see cref="st::CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<DeleteEventsResponse> DeleteEventsAsync( DeleteEventsRequest request, st::CancellationToken cancellationToken) => DeleteEventsAsync( request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual DeleteEventsResponse DeleteEvents( DeleteEventsRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } } /// <summary> /// ErrorStatsService client wrapper implementation, for convenient use. /// </summary> public sealed partial class ErrorStatsServiceClientImpl : ErrorStatsServiceClient { private readonly gaxgrpc::ApiCall<ListGroupStatsRequest, ListGroupStatsResponse> _callListGroupStats; private readonly gaxgrpc::ApiCall<ListEventsRequest, ListEventsResponse> _callListEvents; private readonly gaxgrpc::ApiCall<DeleteEventsRequest, DeleteEventsResponse> _callDeleteEvents; /// <summary> /// Constructs a client wrapper for the ErrorStatsService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="ErrorStatsServiceSettings"/> used within this client </param> public ErrorStatsServiceClientImpl(ErrorStatsService.ErrorStatsServiceClient grpcClient, ErrorStatsServiceSettings settings) { GrpcClient = grpcClient; ErrorStatsServiceSettings effectiveSettings = settings ?? ErrorStatsServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callListGroupStats = clientHelper.BuildApiCall<ListGroupStatsRequest, ListGroupStatsResponse>( GrpcClient.ListGroupStatsAsync, GrpcClient.ListGroupStats, effectiveSettings.ListGroupStatsSettings); _callListEvents = clientHelper.BuildApiCall<ListEventsRequest, ListEventsResponse>( GrpcClient.ListEventsAsync, GrpcClient.ListEvents, effectiveSettings.ListEventsSettings); _callDeleteEvents = clientHelper.BuildApiCall<DeleteEventsRequest, DeleteEventsResponse>( GrpcClient.DeleteEventsAsync, GrpcClient.DeleteEvents, effectiveSettings.DeleteEventsSettings); Modify_ApiCall(ref _callListGroupStats); Modify_ListGroupStatsApiCall(ref _callListGroupStats); Modify_ApiCall(ref _callListEvents); Modify_ListEventsApiCall(ref _callListEvents); Modify_ApiCall(ref _callDeleteEvents); Modify_DeleteEventsApiCall(ref _callDeleteEvents); OnConstruction(grpcClient, effectiveSettings, clientHelper); } // Partial methods are named to (mostly) ensure there cannot be conflicts with RPC method names. // Partial methods called for every ApiCall on construction. // Allows modification of all the underlying ApiCall objects. partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, pb::IMessage<TRequest> where TResponse : class, pb::IMessage<TResponse>; // Partial methods called for each ApiCall on construction. // Allows per-RPC-method modification of the underlying ApiCall object. partial void Modify_ListGroupStatsApiCall(ref gaxgrpc::ApiCall<ListGroupStatsRequest, ListGroupStatsResponse> call); partial void Modify_ListEventsApiCall(ref gaxgrpc::ApiCall<ListEventsRequest, ListEventsResponse> call); partial void Modify_DeleteEventsApiCall(ref gaxgrpc::ApiCall<DeleteEventsRequest, DeleteEventsResponse> call); partial void OnConstruction(ErrorStatsService.ErrorStatsServiceClient grpcClient, ErrorStatsServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary> /// The underlying gRPC ErrorStatsService client. /// </summary> public override ErrorStatsService.ErrorStatsServiceClient GrpcClient { get; } // Partial methods called on each request. // Allows per-RPC-call modification to the request and CallSettings objects, // before the underlying RPC is performed. partial void Modify_ListGroupStatsRequest(ref ListGroupStatsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_ListEventsRequest(ref ListEventsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_DeleteEventsRequest(ref DeleteEventsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Lists the specified groups. /// </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="ErrorGroupStats"/> resources. /// </returns> public override gax::PagedAsyncEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStatsAsync( ListGroupStatsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListGroupStatsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<ListGroupStatsRequest, ListGroupStatsResponse, ErrorGroupStats>(_callListGroupStats, request, callSettings); } /// <summary> /// Lists the specified groups. /// </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="ErrorGroupStats"/> resources. /// </returns> public override gax::PagedEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStats( ListGroupStatsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListGroupStatsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<ListGroupStatsRequest, ListGroupStatsResponse, ErrorGroupStats>(_callListGroupStats, request, callSettings); } /// <summary> /// Lists the specified events. /// </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="ErrorEvent"/> resources. /// </returns> public override gax::PagedAsyncEnumerable<ListEventsResponse, ErrorEvent> ListEventsAsync( ListEventsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListEventsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<ListEventsRequest, ListEventsResponse, ErrorEvent>(_callListEvents, request, callSettings); } /// <summary> /// Lists the specified events. /// </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="ErrorEvent"/> resources. /// </returns> public override gax::PagedEnumerable<ListEventsResponse, ErrorEvent> ListEvents( ListEventsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListEventsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<ListEventsRequest, ListEventsResponse, ErrorEvent>(_callListEvents, request, callSettings); } /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override stt::Task<DeleteEventsResponse> DeleteEventsAsync( DeleteEventsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteEventsRequest(ref request, ref callSettings); return _callDeleteEvents.Async(request, callSettings); } /// <summary> /// Deletes all error events of a given project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override DeleteEventsResponse DeleteEvents( DeleteEventsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteEventsRequest(ref request, ref callSettings); return _callDeleteEvents.Sync(request, callSettings); } } // Partial classes to enable page-streaming public partial class ListGroupStatsRequest : gaxgrpc::IPageRequest { } public partial class ListGroupStatsResponse : gaxgrpc::IPageResponse<ErrorGroupStats> { /// <summary> /// Returns an enumerator that iterates through the resources in this response. /// </summary> public scg::IEnumerator<ErrorGroupStats> GetEnumerator() => ErrorGroupStats.GetEnumerator(); /// <inheritdoc/> sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } public partial class ListEventsRequest : gaxgrpc::IPageRequest { } public partial class ListEventsResponse : gaxgrpc::IPageResponse<ErrorEvent> { /// <summary> /// Returns an enumerator that iterates through the resources in this response. /// </summary> public scg::IEnumerator<ErrorEvent> GetEnumerator() => ErrorEvents.GetEnumerator(); /// <inheritdoc/> sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using Amazon.Route53; using Amazon.Route53.Model; namespace Amazon.Route53 { /// <summary> /// Interface for accessing AmazonRoute53. /// /// /// </summary> public interface AmazonRoute53 : IDisposable { #region ListResourceRecordSets /// <summary> /// <para>Imagine all the resource record sets in a zone listed out in front of you. Imagine them sorted lexicographically first by DNS name /// (with the labels reversed, like "com.amazon.www" for example), and secondarily, lexicographically by record type. This operation retrieves /// at most MaxItems resource record sets from this list, in order, starting at a position specified by the Name and Type arguments:</para> /// <ul> /// <li>If both Name and Type are omitted, this means start the results at the first RRSET in the HostedZone.</li> /// <li>If Name is specified but Type is omitted, this means start the results at the first RRSET in the list whose name is greater than or /// equal to Name. </li> /// <li>If both Name and Type are specified, this means start the results at the first RRSET in the list whose name is greater than or equal to /// Name and whose type is greater than or equal to Type.</li> /// <li>It is an error to specify the Type but not the Name.</li> /// /// </ul> /// <para>Use ListResourceRecordSets to retrieve a single known record set by specifying the record set's name and type, and setting MaxItems = /// 1</para> <para>To retrieve all the records in a HostedZone, first pause any processes making calls to ChangeResourceRecordSets. Initially /// call ListResourceRecordSets without a Name and Type to get the first page of record sets. For subsequent calls, set Name and Type to the /// NextName and NextType values returned by the previous response. </para> <para>In the presence of concurrent ChangeResourceRecordSets calls, /// there is no consistency of results across calls to ListResourceRecordSets. The only way to get a consistent multi-page snapshot of all /// RRSETs in a zone is to stop making changes while pagination is in progress.</para> <para>However, the results from ListResourceRecordSets /// are consistent within a page. If MakeChange calls are taking place concurrently, the result of each one will either be completely visible in /// your results or not at all. You will not see partial changes, or changes that do not ultimately succeed. (This follows from the fact that /// MakeChange is atomic) </para> <para>The results from ListResourceRecordSets are strongly consistent with ChangeResourceRecordSets. To be /// precise, if a single process makes a call to ChangeResourceRecordSets and receives a successful response, the effects of that change will be /// visible in a subsequent call to ListResourceRecordSets by that process.</para> /// </summary> /// /// <param name="listResourceRecordSetsRequest">Container for the necessary parameters to execute the ListResourceRecordSets service method on /// AmazonRoute53.</param> /// /// <returns>The response from the ListResourceRecordSets service method, as returned by AmazonRoute53.</returns> /// /// <exception cref="InvalidInputException"/> /// <exception cref="NoSuchHostedZoneException"/> ListResourceRecordSetsResponse ListResourceRecordSets(ListResourceRecordSetsRequest listResourceRecordSetsRequest); /// <summary> /// Initiates the asynchronous execution of the ListResourceRecordSets operation. /// <seealso cref="Amazon.Route53.AmazonRoute53.ListResourceRecordSets"/> /// </summary> /// /// <param name="listResourceRecordSetsRequest">Container for the necessary parameters to execute the ListResourceRecordSets operation on /// AmazonRoute53.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndListResourceRecordSets operation.</returns> IAsyncResult BeginListResourceRecordSets(ListResourceRecordSetsRequest listResourceRecordSetsRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the ListResourceRecordSets operation. /// <seealso cref="Amazon.Route53.AmazonRoute53.ListResourceRecordSets"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListResourceRecordSets.</param> /// /// <returns>Returns a ListResourceRecordSetsResult from AmazonRoute53.</returns> ListResourceRecordSetsResponse EndListResourceRecordSets(IAsyncResult asyncResult); #endregion #region ChangeResourceRecordSets /// <summary> /// <para>Use this action to create or change your authoritative DNS information. To use this action, send a <c>POST</c> request to the /// <c>2012-12-12/hostedzone/hosted Zone ID/rrset</c> resource. The request body must include an XML document with a /// <c>ChangeResourceRecordSetsRequest</c> element.</para> <para>Changes are a list of change items and are considered transactional. For more /// information on transactional changes, also known as change batches, see Creating, Changing, and Deleting Resource Record Sets Using the /// Route 53 API in the <i>Amazon Route 53 Developer Guide</i> .</para> <para><b>IMPORTANT:</b>Due to the nature of transactional changes, you /// cannot delete the same resource record set more than once in a single change batch. If you attempt to delete the same change batch more than /// once, Route 53 returns an InvalidChangeBatch error.</para> <para>In response to a <c>ChangeResourceRecordSets</c> request, your DNS data is /// changed on all Route 53 DNS servers. Initially, the status of a change is <c>PENDING</c> . This means the change has not yet propagated to /// all the authoritative Route 53 DNS servers. When the change is propagated to all hosts, the change returns a status of <c>INSYNC</c> /// .</para> <para>Note the following limitations on a <c>ChangeResourceRecordSets</c> request:</para> <para>- A request cannot contain more /// than 100 Change elements.</para> <para>- A request cannot contain more than 1000 ResourceRecord elements.</para> <para>The sum of the number /// of characters (including spaces) in all <c>Value</c> elements in a request cannot exceed 32,000 characters.</para> /// </summary> /// /// <param name="changeResourceRecordSetsRequest">Container for the necessary parameters to execute the ChangeResourceRecordSets service method /// on AmazonRoute53.</param> /// /// <returns>The response from the ChangeResourceRecordSets service method, as returned by AmazonRoute53.</returns> /// /// <exception cref="InvalidInputException"/> /// <exception cref="NoSuchHostedZoneException"/> /// <exception cref="InvalidChangeBatchException"/> /// <exception cref="NoSuchHealthCheckException"/> /// <exception cref="PriorRequestNotCompleteException"/> ChangeResourceRecordSetsResponse ChangeResourceRecordSets(ChangeResourceRecordSetsRequest changeResourceRecordSetsRequest); /// <summary> /// Initiates the asynchronous execution of the ChangeResourceRecordSets operation. /// <seealso cref="Amazon.Route53.AmazonRoute53.ChangeResourceRecordSets"/> /// </summary> /// /// <param name="changeResourceRecordSetsRequest">Container for the necessary parameters to execute the ChangeResourceRecordSets operation on /// AmazonRoute53.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndChangeResourceRecordSets operation.</returns> IAsyncResult BeginChangeResourceRecordSets(ChangeResourceRecordSetsRequest changeResourceRecordSetsRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the ChangeResourceRecordSets operation. /// <seealso cref="Amazon.Route53.AmazonRoute53.ChangeResourceRecordSets"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginChangeResourceRecordSets.</param> /// /// <returns>Returns a ChangeResourceRecordSetsResult from AmazonRoute53.</returns> ChangeResourceRecordSetsResponse EndChangeResourceRecordSets(IAsyncResult asyncResult); #endregion #region CreateHostedZone /// <summary> /// <para> This action creates a new hosted zone.</para> <para>To create a new hosted zone, send a <c>POST</c> request to the /// <c>2012-12-12/hostedzone</c> resource. The request body must include an XML document with a <c>CreateHostedZoneRequest</c> element. The /// response returns the <c>CreateHostedZoneResponse</c> element that contains metadata about the hosted zone.</para> <para>Route 53 /// automatically creates a default SOA record and four NS records for the zone. The NS records in the hosted zone are the name servers you give /// your registrar to delegate your domain to. For more information about SOA and NS records, see NS and SOA Records that Route 53 Creates for a /// Hosted Zone in the <i>Amazon Route 53 Developer Guide</i> .</para> <para>When you create a zone, its initial status is <c>PENDING</c> . This /// means that it is not yet available on all DNS servers. The status of the zone changes to <c>INSYNC</c> when the NS and SOA records are /// available on all Route 53 DNS servers. </para> /// </summary> /// /// <param name="createHostedZoneRequest">Container for the necessary parameters to execute the CreateHostedZone service method on /// AmazonRoute53.</param> /// /// <returns>The response from the CreateHostedZone service method, as returned by AmazonRoute53.</returns> /// /// <exception cref="HostedZoneAlreadyExistsException"/> /// <exception cref="InvalidInputException"/> /// <exception cref="InvalidDomainNameException"/> /// <exception cref="TooManyHostedZonesException"/> /// <exception cref="DelegationSetNotAvailableException"/> CreateHostedZoneResponse CreateHostedZone(CreateHostedZoneRequest createHostedZoneRequest); /// <summary> /// Initiates the asynchronous execution of the CreateHostedZone operation. /// <seealso cref="Amazon.Route53.AmazonRoute53.CreateHostedZone"/> /// </summary> /// /// <param name="createHostedZoneRequest">Container for the necessary parameters to execute the CreateHostedZone operation on /// AmazonRoute53.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateHostedZone /// operation.</returns> IAsyncResult BeginCreateHostedZone(CreateHostedZoneRequest createHostedZoneRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the CreateHostedZone operation. /// <seealso cref="Amazon.Route53.AmazonRoute53.CreateHostedZone"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateHostedZone.</param> /// /// <returns>Returns a CreateHostedZoneResult from AmazonRoute53.</returns> CreateHostedZoneResponse EndCreateHostedZone(IAsyncResult asyncResult); #endregion #region GetHealthCheck /// <summary> /// <para> To retrieve the health check, send a <c>GET</c> request to the <c>2012-12-12/healthcheck/health check ID </c> resource. </para> /// </summary> /// /// <param name="getHealthCheckRequest">Container for the necessary parameters to execute the GetHealthCheck service method on /// AmazonRoute53.</param> /// /// <returns>The response from the GetHealthCheck service method, as returned by AmazonRoute53.</returns> /// /// <exception cref="InvalidInputException"/> /// <exception cref="NoSuchHealthCheckException"/> GetHealthCheckResponse GetHealthCheck(GetHealthCheckRequest getHealthCheckRequest); /// <summary> /// Initiates the asynchronous execution of the GetHealthCheck operation. /// <seealso cref="Amazon.Route53.AmazonRoute53.GetHealthCheck"/> /// </summary> /// /// <param name="getHealthCheckRequest">Container for the necessary parameters to execute the GetHealthCheck operation on AmazonRoute53.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetHealthCheck /// operation.</returns> IAsyncResult BeginGetHealthCheck(GetHealthCheckRequest getHealthCheckRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the GetHealthCheck operation. /// <seealso cref="Amazon.Route53.AmazonRoute53.GetHealthCheck"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetHealthCheck.</param> /// /// <returns>Returns a GetHealthCheckResult from AmazonRoute53.</returns> GetHealthCheckResponse EndGetHealthCheck(IAsyncResult asyncResult); #endregion #region CreateHealthCheck /// <summary> /// <para> This action creates a new health check.</para> <para> To create a new health check, send a <c>POST</c> request to the /// <c>2012-12-12/healthcheck</c> resource. The request body must include an XML document with a <c>CreateHealthCheckRequest</c> element. The /// response returns the <c>CreateHealthCheckResponse</c> element that contains metadata about the health check.</para> /// </summary> /// /// <param name="createHealthCheckRequest">Container for the necessary parameters to execute the CreateHealthCheck service method on /// AmazonRoute53.</param> /// /// <returns>The response from the CreateHealthCheck service method, as returned by AmazonRoute53.</returns> /// /// <exception cref="InvalidInputException"/> /// <exception cref="HealthCheckAlreadyExistsException"/> /// <exception cref="TooManyHealthChecksException"/> CreateHealthCheckResponse CreateHealthCheck(CreateHealthCheckRequest createHealthCheckRequest); /// <summary> /// Initiates the asynchronous execution of the CreateHealthCheck operation. /// <seealso cref="Amazon.Route53.AmazonRoute53.CreateHealthCheck"/> /// </summary> /// /// <param name="createHealthCheckRequest">Container for the necessary parameters to execute the CreateHealthCheck operation on /// AmazonRoute53.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateHealthCheck /// operation.</returns> IAsyncResult BeginCreateHealthCheck(CreateHealthCheckRequest createHealthCheckRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the CreateHealthCheck operation. /// <seealso cref="Amazon.Route53.AmazonRoute53.CreateHealthCheck"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateHealthCheck.</param> /// /// <returns>Returns a CreateHealthCheckResult from AmazonRoute53.</returns> CreateHealthCheckResponse EndCreateHealthCheck(IAsyncResult asyncResult); #endregion #region GetChange /// <summary> /// <para> This action returns the current status of a change batch request. The status is one of the following values:</para> <para>- /// <c>PENDING</c> indicates that the changes in this request have not replicated to all Route 53 DNS servers. This is the initial status of all /// change batch requests.</para> <para>- <c>INSYNC</c> indicates that the changes have replicated to all Amazon Route 53 DNS servers. </para> /// </summary> /// /// <param name="getChangeRequest">Container for the necessary parameters to execute the GetChange service method on AmazonRoute53.</param> /// /// <returns>The response from the GetChange service method, as returned by AmazonRoute53.</returns> /// /// <exception cref="NoSuchChangeException"/> /// <exception cref="InvalidInputException"/> GetChangeResponse GetChange(GetChangeRequest getChangeRequest); /// <summary> /// Initiates the asynchronous execution of the GetChange operation. /// <seealso cref="Amazon.Route53.AmazonRoute53.GetChange"/> /// </summary> /// /// <param name="getChangeRequest">Container for the necessary parameters to execute the GetChange operation on AmazonRoute53.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetChange /// operation.</returns> IAsyncResult BeginGetChange(GetChangeRequest getChangeRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the GetChange operation. /// <seealso cref="Amazon.Route53.AmazonRoute53.GetChange"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetChange.</param> /// /// <returns>Returns a GetChangeResult from AmazonRoute53.</returns> GetChangeResponse EndGetChange(IAsyncResult asyncResult); #endregion #region DeleteHealthCheck /// <summary> /// <para>This action deletes a health check. To delete a health check, send a <c>DELETE</c> request to the <c>2012-12-12/healthcheck/health /// check ID </c> resource.</para> <para><b>IMPORTANT:</b> You can delete a health check only if there are no resource record sets associated /// with this health check. If resource record sets are associated with this health check, you must disassociate them before you can delete your /// health check. If you try to delete a health check that is associated with resource record sets, Route 53 will deny your request with a /// HealthCheckInUse error. For information about disassociating the records from your health check, see ChangeResourceRecordSets.</para> /// </summary> /// /// <param name="deleteHealthCheckRequest">Container for the necessary parameters to execute the DeleteHealthCheck service method on /// AmazonRoute53.</param> /// /// <returns>The response from the DeleteHealthCheck service method, as returned by AmazonRoute53.</returns> /// /// <exception cref="InvalidInputException"/> /// <exception cref="HealthCheckInUseException"/> /// <exception cref="NoSuchHealthCheckException"/> DeleteHealthCheckResponse DeleteHealthCheck(DeleteHealthCheckRequest deleteHealthCheckRequest); /// <summary> /// Initiates the asynchronous execution of the DeleteHealthCheck operation. /// <seealso cref="Amazon.Route53.AmazonRoute53.DeleteHealthCheck"/> /// </summary> /// /// <param name="deleteHealthCheckRequest">Container for the necessary parameters to execute the DeleteHealthCheck operation on /// AmazonRoute53.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteHealthCheck /// operation.</returns> IAsyncResult BeginDeleteHealthCheck(DeleteHealthCheckRequest deleteHealthCheckRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DeleteHealthCheck operation. /// <seealso cref="Amazon.Route53.AmazonRoute53.DeleteHealthCheck"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteHealthCheck.</param> /// /// <returns>Returns a DeleteHealthCheckResult from AmazonRoute53.</returns> DeleteHealthCheckResponse EndDeleteHealthCheck(IAsyncResult asyncResult); #endregion #region GetHostedZone /// <summary> /// <para> To retrieve the delegation set for a hosted zone, send a <c>GET</c> request to the <c>2012-12-12/hostedzone/hosted zone ID </c> /// resource. The delegation set is the four Route 53 name servers that were assigned to the hosted zone when you created it.</para> /// </summary> /// /// <param name="getHostedZoneRequest">Container for the necessary parameters to execute the GetHostedZone service method on /// AmazonRoute53.</param> /// /// <returns>The response from the GetHostedZone service method, as returned by AmazonRoute53.</returns> /// /// <exception cref="InvalidInputException"/> /// <exception cref="NoSuchHostedZoneException"/> GetHostedZoneResponse GetHostedZone(GetHostedZoneRequest getHostedZoneRequest); /// <summary> /// Initiates the asynchronous execution of the GetHostedZone operation. /// <seealso cref="Amazon.Route53.AmazonRoute53.GetHostedZone"/> /// </summary> /// /// <param name="getHostedZoneRequest">Container for the necessary parameters to execute the GetHostedZone operation on AmazonRoute53.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetHostedZone /// operation.</returns> IAsyncResult BeginGetHostedZone(GetHostedZoneRequest getHostedZoneRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the GetHostedZone operation. /// <seealso cref="Amazon.Route53.AmazonRoute53.GetHostedZone"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetHostedZone.</param> /// /// <returns>Returns a GetHostedZoneResult from AmazonRoute53.</returns> GetHostedZoneResponse EndGetHostedZone(IAsyncResult asyncResult); #endregion #region ListHostedZones /// <summary> /// <para> To retrieve a list of your hosted zones, send a <c>GET</c> request to the <c>2012-12-12/hostedzone</c> resource. The response to this /// request includes a <c>HostedZones</c> element with zero, one, or multiple <c>HostedZone</c> child elements. By default, the list of hosted /// zones is displayed on a single page. You can control the length of the page that is displayed by using the <c>MaxItems</c> parameter. You /// can use the <c>Marker</c> parameter to control the hosted zone that the list begins with. </para> <para><b>NOTE:</b> Amazon Route 53 returns /// a maximum of 100 items. If you set MaxItems to a value greater than 100, Amazon Route 53 returns only the first 100.</para> /// </summary> /// /// <param name="listHostedZonesRequest">Container for the necessary parameters to execute the ListHostedZones service method on /// AmazonRoute53.</param> /// /// <returns>The response from the ListHostedZones service method, as returned by AmazonRoute53.</returns> /// /// <exception cref="InvalidInputException"/> ListHostedZonesResponse ListHostedZones(ListHostedZonesRequest listHostedZonesRequest); /// <summary> /// Initiates the asynchronous execution of the ListHostedZones operation. /// <seealso cref="Amazon.Route53.AmazonRoute53.ListHostedZones"/> /// </summary> /// /// <param name="listHostedZonesRequest">Container for the necessary parameters to execute the ListHostedZones operation on /// AmazonRoute53.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListHostedZones /// operation.</returns> IAsyncResult BeginListHostedZones(ListHostedZonesRequest listHostedZonesRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the ListHostedZones operation. /// <seealso cref="Amazon.Route53.AmazonRoute53.ListHostedZones"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListHostedZones.</param> /// /// <returns>Returns a ListHostedZonesResult from AmazonRoute53.</returns> ListHostedZonesResponse EndListHostedZones(IAsyncResult asyncResult); /// <summary> /// <para> To retrieve a list of your hosted zones, send a <c>GET</c> request to the <c>2012-12-12/hostedzone</c> resource. The response to this /// request includes a <c>HostedZones</c> element with zero, one, or multiple <c>HostedZone</c> child elements. By default, the list of hosted /// zones is displayed on a single page. You can control the length of the page that is displayed by using the <c>MaxItems</c> parameter. You /// can use the <c>Marker</c> parameter to control the hosted zone that the list begins with. </para> <para><b>NOTE:</b> Amazon Route 53 returns /// a maximum of 100 items. If you set MaxItems to a value greater than 100, Amazon Route 53 returns only the first 100.</para> /// </summary> /// /// <returns>The response from the ListHostedZones service method, as returned by AmazonRoute53.</returns> /// /// <exception cref="InvalidInputException"/> ListHostedZonesResponse ListHostedZones(); #endregion #region DeleteHostedZone /// <summary> /// <para>This action deletes a hosted zone. To delete a hosted zone, send a <c>DELETE</c> request to the <c>2012-12-12/hostedzone/hosted zone /// ID </c> resource.</para> <para>For more information about deleting a hosted zone, see Deleting a Hosted Zone in the <i>Amazon Route 53 /// Developer Guide</i> .</para> <para><b>IMPORTANT:</b> You can delete a hosted zone only if there are no resource record sets other than the /// default SOA record and NS resource record sets. If your hosted zone contains other resource record sets, you must delete them before you can /// delete your hosted zone. If you try to delete a hosted zone that contains other resource record sets, Route 53 will deny your request with a /// HostedZoneNotEmpty error. For information about deleting records from your hosted zone, see ChangeResourceRecordSets.</para> /// </summary> /// /// <param name="deleteHostedZoneRequest">Container for the necessary parameters to execute the DeleteHostedZone service method on /// AmazonRoute53.</param> /// /// <returns>The response from the DeleteHostedZone service method, as returned by AmazonRoute53.</returns> /// /// <exception cref="HostedZoneNotEmptyException"/> /// <exception cref="InvalidInputException"/> /// <exception cref="NoSuchHostedZoneException"/> /// <exception cref="PriorRequestNotCompleteException"/> DeleteHostedZoneResponse DeleteHostedZone(DeleteHostedZoneRequest deleteHostedZoneRequest); /// <summary> /// Initiates the asynchronous execution of the DeleteHostedZone operation. /// <seealso cref="Amazon.Route53.AmazonRoute53.DeleteHostedZone"/> /// </summary> /// /// <param name="deleteHostedZoneRequest">Container for the necessary parameters to execute the DeleteHostedZone operation on /// AmazonRoute53.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteHostedZone /// operation.</returns> IAsyncResult BeginDeleteHostedZone(DeleteHostedZoneRequest deleteHostedZoneRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DeleteHostedZone operation. /// <seealso cref="Amazon.Route53.AmazonRoute53.DeleteHostedZone"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteHostedZone.</param> /// /// <returns>Returns a DeleteHostedZoneResult from AmazonRoute53.</returns> DeleteHostedZoneResponse EndDeleteHostedZone(IAsyncResult asyncResult); #endregion #region ListHealthChecks /// <summary> /// <para> To retrieve a list of your health checks, send a <c>GET</c> request to the <c>2012-12-12/healthcheck</c> resource. The response to /// this request includes a <c>HealthChecks</c> element with zero, one, or multiple <c>HealthCheck</c> child elements. By default, the list of /// health checks is displayed on a single page. You can control the length of the page that is displayed by using the <c>MaxItems</c> /// parameter. You can use the <c>Marker</c> parameter to control the health check that the list begins with. </para> <para><b>NOTE:</b> Amazon /// Route 53 returns a maximum of 100 items. If you set MaxItems to a value greater than 100, Amazon Route 53 returns only the first 100.</para> /// </summary> /// /// <param name="listHealthChecksRequest">Container for the necessary parameters to execute the ListHealthChecks service method on /// AmazonRoute53.</param> /// /// <returns>The response from the ListHealthChecks service method, as returned by AmazonRoute53.</returns> /// /// <exception cref="InvalidInputException"/> ListHealthChecksResponse ListHealthChecks(ListHealthChecksRequest listHealthChecksRequest); /// <summary> /// Initiates the asynchronous execution of the ListHealthChecks operation. /// <seealso cref="Amazon.Route53.AmazonRoute53.ListHealthChecks"/> /// </summary> /// /// <param name="listHealthChecksRequest">Container for the necessary parameters to execute the ListHealthChecks operation on /// AmazonRoute53.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListHealthChecks /// operation.</returns> IAsyncResult BeginListHealthChecks(ListHealthChecksRequest listHealthChecksRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the ListHealthChecks operation. /// <seealso cref="Amazon.Route53.AmazonRoute53.ListHealthChecks"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListHealthChecks.</param> /// /// <returns>Returns a ListHealthChecksResult from AmazonRoute53.</returns> ListHealthChecksResponse EndListHealthChecks(IAsyncResult asyncResult); /// <summary> /// <para> To retrieve a list of your health checks, send a <c>GET</c> request to the <c>2012-12-12/healthcheck</c> resource. The response to /// this request includes a <c>HealthChecks</c> element with zero, one, or multiple <c>HealthCheck</c> child elements. By default, the list of /// health checks is displayed on a single page. You can control the length of the page that is displayed by using the <c>MaxItems</c> /// parameter. You can use the <c>Marker</c> parameter to control the health check that the list begins with. </para> <para><b>NOTE:</b> Amazon /// Route 53 returns a maximum of 100 items. If you set MaxItems to a value greater than 100, Amazon Route 53 returns only the first 100.</para> /// </summary> /// /// <returns>The response from the ListHealthChecks service method, as returned by AmazonRoute53.</returns> /// /// <exception cref="InvalidInputException"/> ListHealthChecksResponse ListHealthChecks(); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // System.Net.HttpListenerRequest // // Authors: // Gonzalo Paniagua Javier (gonzalo.mono@gmail.com) // Marek Safar (marek.safar@gmail.com) // // Copyright (c) 2005 Novell, Inc. (http://www.novell.com) // Copyright (c) 2011-2012 Xamarin, Inc. (http://xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Net.WebSockets; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace System.Net { public sealed partial class HttpListenerRequest { private class Context : TransportContext { public override ChannelBinding GetChannelBinding(ChannelBindingKind kind) { throw new NotImplementedException(); } } private string[] _acceptTypes; private long _contentLength; private bool _clSet; private CookieCollection _cookies; private WebHeaderCollection _headers; private string _method; private Stream _inputStream; private Version _version; private NameValueCollection _queryString; // check if null is ok, check if read-only, check case-sensitiveness private string _rawUrl; private Uri _url; private Uri _referrer; private string[] _userLanguages; private HttpListenerContext _context; private bool _isChunked; private bool _kaSet; private bool _keepAlive; private static byte[] s_100continue = Encoding.ASCII.GetBytes("HTTP/1.1 100 Continue\r\n\r\n"); internal HttpListenerRequest(HttpListenerContext context) { _context = context; _headers = new WebHeaderCollection(); _version = HttpVersion.Version10; } private static char[] s_separators = new char[] { ' ' }; internal void SetRequestLine(string req) { string[] parts = req.Split(s_separators, 3); if (parts.Length != 3) { _context.ErrorMessage = "Invalid request line (parts)."; return; } _method = parts[0]; foreach (char c in _method) { int ic = (int)c; if ((ic >= 'A' && ic <= 'Z') || (ic > 32 && c < 127 && c != '(' && c != ')' && c != '<' && c != '<' && c != '>' && c != '@' && c != ',' && c != ';' && c != ':' && c != '\\' && c != '"' && c != '/' && c != '[' && c != ']' && c != '?' && c != '=' && c != '{' && c != '}')) continue; _context.ErrorMessage = "(Invalid verb)"; return; } _rawUrl = parts[1]; if (parts[2].Length != 8 || !parts[2].StartsWith("HTTP/")) { _context.ErrorMessage = "Invalid request line (version)."; return; } try { _version = new Version(parts[2].Substring(5)); if (_version.Major < 1) throw new Exception(); } catch { _context.ErrorMessage = "Invalid request line (version)."; return; } } private void CreateQueryString(string query) { _queryString = new NameValueCollection(); Helpers.FillFromString(_queryString, Url.Query, true, ContentEncoding); } private static bool MaybeUri(string s) { int p = s.IndexOf(':'); if (p == -1) return false; if (p >= 10) return false; return IsPredefinedScheme(s.Substring(0, p)); } private static bool IsPredefinedScheme(string scheme) { if (scheme == null || scheme.Length < 3) return false; char c = scheme[0]; if (c == 'h') return (scheme == "http" || scheme == "https"); if (c == 'f') return (scheme == "file" || scheme == "ftp"); if (c == 'n') { c = scheme[1]; if (c == 'e') return (scheme == "news" || scheme == "net.pipe" || scheme == "net.tcp"); if (scheme == "nntp") return true; return false; } if ((c == 'g' && scheme == "gopher") || (c == 'm' && scheme == "mailto")) return true; return false; } internal void FinishInitialization() { string host = UserHostName; if (_version > HttpVersion.Version10 && (host == null || host.Length == 0)) { _context.ErrorMessage = "Invalid host name"; return; } string path; Uri raw_uri = null; if (MaybeUri(_rawUrl.ToLowerInvariant()) && Uri.TryCreate(_rawUrl, UriKind.Absolute, out raw_uri)) path = raw_uri.PathAndQuery; else path = _rawUrl; if ((host == null || host.Length == 0)) host = UserHostAddress; if (raw_uri != null) host = raw_uri.Host; int colon = host.IndexOf(':'); if (colon >= 0) host = host.Substring(0, colon); string base_uri = String.Format("{0}://{1}:{2}", (IsSecureConnection) ? "https" : "http", host, LocalEndPoint.Port); if (!Uri.TryCreate(base_uri + path, UriKind.Absolute, out _url)) { _context.ErrorMessage = WebUtility.HtmlEncode("Invalid url: " + base_uri + path); return; } CreateQueryString(_url.Query); _url = HttpListenerRequestUriBuilder.GetRequestUri(_rawUrl, _url.Scheme, _url.Authority, _url.LocalPath, _url.Query); if (_version >= HttpVersion.Version11) { string t_encoding = Headers["Transfer-Encoding"]; _isChunked = (t_encoding != null && string.Equals(t_encoding, "chunked", StringComparison.OrdinalIgnoreCase)); // 'identity' is not valid! if (t_encoding != null && !_isChunked) { _context.Connection.SendError(null, 501); return; } } if (!_isChunked && !_clSet) { if (string.Equals(_method, "POST", StringComparison.OrdinalIgnoreCase) || string.Equals(_method, "PUT", StringComparison.OrdinalIgnoreCase)) { _context.Connection.SendError(null, 411); return; } } if (String.Compare(Headers["Expect"], "100-continue", StringComparison.OrdinalIgnoreCase) == 0) { HttpResponseStream output = _context.Connection.GetResponseStream(); output.InternalWrite(s_100continue, 0, s_100continue.Length); } } internal static string Unquote(String str) { int start = str.IndexOf('\"'); int end = str.LastIndexOf('\"'); if (start >= 0 && end >= 0) str = str.Substring(start + 1, end - 1); return str.Trim(); } internal void AddHeader(string header) { int colon = header.IndexOf(':'); if (colon == -1 || colon == 0) { _context.ErrorMessage = HttpStatusDescription.Get(400); _context.ErrorStatus = 400; return; } string name = header.Substring(0, colon).Trim(); string val = header.Substring(colon + 1).Trim(); string lower = name.ToLower(CultureInfo.InvariantCulture); _headers.Set(name, val); switch (lower) { case "accept-language": _userLanguages = Helpers.ParseMultivalueHeader(val); break; case "accept": _acceptTypes = Helpers.ParseMultivalueHeader(val); break; case "content-length": try { _contentLength = long.Parse(val.Trim()); if (_contentLength < 0) _context.ErrorMessage = "Invalid Content-Length."; _clSet = true; } catch { _context.ErrorMessage = "Invalid Content-Length."; } break; case "referer": try { _referrer = new Uri(val, UriKind.RelativeOrAbsolute); } catch { _referrer = null; } break; case "cookie": if (_cookies == null) _cookies = new CookieCollection(); string[] cookieStrings = val.Split(new char[] { ',', ';' }); Cookie current = null; int version = 0; foreach (string cookieString in cookieStrings) { string str = cookieString.Trim(); if (str.Length == 0) continue; if (str.StartsWith("$Version")) { version = Int32.Parse(Unquote(str.Substring(str.IndexOf('=') + 1))); } else if (str.StartsWith("$Path")) { if (current != null) current.Path = str.Substring(str.IndexOf('=') + 1).Trim(); } else if (str.StartsWith("$Domain")) { if (current != null) current.Domain = str.Substring(str.IndexOf('=') + 1).Trim(); } else if (str.StartsWith("$Port")) { if (current != null) current.Port = str.Substring(str.IndexOf('=') + 1).Trim(); } else { if (current != null) { _cookies.Add(current); } current = new Cookie(); int idx = str.IndexOf('='); if (idx > 0) { current.Name = str.Substring(0, idx).Trim(); current.Value = str.Substring(idx + 1).Trim(); } else { current.Name = str.Trim(); current.Value = String.Empty; } current.Version = version; } } if (current != null) { _cookies.Add(current); } break; } } // returns true is the stream could be reused. internal bool FlushInput() { if (!HasEntityBody) return true; int length = 2048; if (_contentLength > 0) length = (int)Math.Min(_contentLength, (long)length); byte[] bytes = new byte[length]; while (true) { try { IAsyncResult ares = InputStream.BeginRead(bytes, 0, length, null, null); if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne(1000)) return false; if (InputStream.EndRead(ares) <= 0) return true; } catch (ObjectDisposedException) { _inputStream = null; return true; } catch { return false; } } } public string[] AcceptTypes { get { return _acceptTypes; } } public int ClientCertificateError { get { HttpConnection cnc = _context.Connection; if (cnc.ClientCertificate == null) return 0; int[] errors = cnc.ClientCertificateErrors; if (errors != null && errors.Length > 0) return errors[0]; return 0; } } public long ContentLength64 { get { if (_isChunked) _contentLength = -1; return _contentLength; } } public string ContentType { get { return _headers["content-type"]; } } public CookieCollection Cookies { get { if (_cookies == null) _cookies = new CookieCollection(); return _cookies; } } public bool HasEntityBody { get { return (_contentLength > 0 || _isChunked); } } public NameValueCollection Headers { get { return _headers; } } public string HttpMethod { get { return _method; } } public Stream InputStream { get { if (_inputStream == null) { if (_isChunked || _contentLength > 0) _inputStream = _context.Connection.GetRequestStream(_isChunked, _contentLength); else _inputStream = Stream.Null; } return _inputStream; } } public bool IsAuthenticated { get { return false; } } public bool IsLocal { get { return LocalEndPoint.Address.Equals(RemoteEndPoint.Address); } } public bool IsSecureConnection { get { return _context.Connection.IsSecure; } } public bool KeepAlive { get { if (_kaSet) return _keepAlive; _kaSet = true; // 1. Connection header // 2. Protocol (1.1 == keep-alive by default) // 3. Keep-Alive header string cnc = _headers["Connection"]; if (!String.IsNullOrEmpty(cnc)) { _keepAlive = (0 == String.Compare(cnc, "keep-alive", StringComparison.OrdinalIgnoreCase)); } else if (_version == HttpVersion.Version11) { _keepAlive = true; } else { cnc = _headers["keep-alive"]; if (!String.IsNullOrEmpty(cnc)) _keepAlive = (0 != String.Compare(cnc, "closed", StringComparison.OrdinalIgnoreCase)); } return _keepAlive; } } public IPEndPoint LocalEndPoint { get { return _context.Connection.LocalEndPoint; } } public Version ProtocolVersion { get { return _version; } } public NameValueCollection QueryString { get { return _queryString; } } public string RawUrl { get { return _rawUrl; } } public IPEndPoint RemoteEndPoint { get { return _context.Connection.RemoteEndPoint; } } public Guid RequestTraceIdentifier { get { return Guid.Empty; } } public Uri Url { get { return _url; } } public Uri UrlReferrer { get { return _referrer; } } public string UserAgent { get { return _headers["user-agent"]; } } public string UserHostAddress { get { return LocalEndPoint.ToString(); } } public string UserHostName { get { return _headers["host"]; } } public string[] UserLanguages { get { return _userLanguages; } } public IAsyncResult BeginGetClientCertificate(AsyncCallback requestCallback, object state) { Task<X509Certificate2> getClientCertificate = new Task<X509Certificate2>(() => GetClientCertificate()); return TaskToApm.Begin(getClientCertificate, requestCallback, state); } public X509Certificate2 EndGetClientCertificate(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); return TaskToApm.End<X509Certificate2>(asyncResult); } public X509Certificate2 GetClientCertificate() { return _context.Connection.ClientCertificate; } public string ServiceName { get { return null; } } public TransportContext TransportContext { get { return new Context(); } } public bool IsWebSocketRequest { get { if (string.IsNullOrEmpty(Headers[HttpKnownHeaderNames.Connection]) || string.IsNullOrEmpty(Headers[HttpKnownHeaderNames.Upgrade])) { return false; } bool foundConnectionUpgradeHeader = false; foreach (string connection in Headers.GetValues(HttpKnownHeaderNames.Connection)) { if (string.Equals(connection, HttpKnownHeaderNames.Upgrade, StringComparison.OrdinalIgnoreCase)) { foundConnectionUpgradeHeader = true; break; } } if (!foundConnectionUpgradeHeader) { return false; } foreach (string upgrade in Headers.GetValues(HttpKnownHeaderNames.Upgrade)) { if (string.Equals(upgrade, HttpWebSocket.WebSocketUpgradeToken, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } } public Task<X509Certificate2> GetClientCertificateAsync() { return Task<X509Certificate2>.Factory.FromAsync(BeginGetClientCertificate, EndGetClientCertificate, null); } } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Grpc.Core; using Grpc.Core.Internal; using Grpc.Core.Profiling; using Grpc.Core.Utils; using NUnit.Framework; namespace Grpc.Core.Tests { public class ClientServerTest { const string Host = "127.0.0.1"; MockServiceHelper helper; Server server; Channel channel; [SetUp] public void Init() { helper = new MockServiceHelper(Host); server = helper.GetServer(); server.Start(); channel = helper.GetChannel(); } [TearDown] public void Cleanup() { channel.ShutdownAsync().Wait(); server.ShutdownAsync().Wait(); } [Test] public async Task UnaryCall() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { return request; }); Assert.AreEqual("ABC", Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "ABC")); Assert.AreEqual("ABC", await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "ABC")); } [Test] public void UnaryCall_ServerHandlerThrows() { helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) => { throw new Exception("This was thrown on purpose by a test"); }); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unknown, ex.Status.StatusCode); var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unknown, ex2.Status.StatusCode); } [Test] public void UnaryCall_ServerHandlerThrowsRpcException() { helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) => { throw new RpcException(new Status(StatusCode.Unauthenticated, "")); }); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode); var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode); } [Test] public void UnaryCall_ServerHandlerSetsStatus() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { context.Status = new Status(StatusCode.Unauthenticated, ""); return ""; }); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode); var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode); } [Test] public async Task ClientStreamingCall() { helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) => { string result = ""; await requestStream.ForEachAsync(async (request) => { result += request; }); await Task.Delay(100); return result; }); var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall()); await call.RequestStream.WriteAllAsync(new string[] { "A", "B", "C" }); Assert.AreEqual("ABC", await call.ResponseAsync); Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode); Assert.IsNotNull(call.GetTrailers()); } [Test] public async Task ServerStreamingCall() { helper.ServerStreamingHandler = new ServerStreamingServerMethod<string, string>(async (request, responseStream, context) => { await responseStream.WriteAllAsync(request.Split(new []{' '})); context.ResponseTrailers.Add("xyz", ""); }); var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), "A B C"); CollectionAssert.AreEqual(new string[] { "A", "B", "C" }, await call.ResponseStream.ToListAsync()); Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode); Assert.IsNotNull("xyz", call.GetTrailers()[0].Key); } [Test] public async Task ServerStreamingCall_EndOfStreamIsIdempotent() { helper.ServerStreamingHandler = new ServerStreamingServerMethod<string, string>(async (request, responseStream, context) => { }); var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), ""); Assert.IsFalse(await call.ResponseStream.MoveNext()); Assert.IsFalse(await call.ResponseStream.MoveNext()); } [Test] public async Task ServerStreamingCall_ErrorCanBeAwaitedTwice() { helper.ServerStreamingHandler = new ServerStreamingServerMethod<string, string>(async (request, responseStream, context) => { context.Status = new Status(StatusCode.InvalidArgument, ""); }); var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), ""); var ex = Assert.ThrowsAsync<RpcException>(async () => await call.ResponseStream.MoveNext()); Assert.AreEqual(StatusCode.InvalidArgument, ex.Status.StatusCode); // attempting MoveNext again should result in throwing the same exception. var ex2 = Assert.ThrowsAsync<RpcException>(async () => await call.ResponseStream.MoveNext()); Assert.AreEqual(StatusCode.InvalidArgument, ex2.Status.StatusCode); } [Test] public async Task DuplexStreamingCall() { helper.DuplexStreamingHandler = new DuplexStreamingServerMethod<string, string>(async (requestStream, responseStream, context) => { while (await requestStream.MoveNext()) { await responseStream.WriteAsync(requestStream.Current); } context.ResponseTrailers.Add("xyz", "xyz-value"); }); var call = Calls.AsyncDuplexStreamingCall(helper.CreateDuplexStreamingCall()); await call.RequestStream.WriteAllAsync(new string[] { "A", "B", "C" }); CollectionAssert.AreEqual(new string[] { "A", "B", "C" }, await call.ResponseStream.ToListAsync()); Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode); Assert.IsNotNull("xyz-value", call.GetTrailers()[0].Value); } [Test] public async Task ClientStreamingCall_CancelAfterBegin() { var barrier = new TaskCompletionSource<object>(); helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) => { barrier.SetResult(null); await requestStream.ToListAsync(); return ""; }); var cts = new CancellationTokenSource(); var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall(new CallOptions(cancellationToken: cts.Token))); await barrier.Task; // make sure the handler has started. cts.Cancel(); try { // cannot use Assert.ThrowsAsync because it uses Task.Wait and would deadlock. await call.ResponseAsync; Assert.Fail(); } catch (RpcException ex) { Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode); } } [Test] public async Task ClientStreamingCall_ServerSideReadAfterCancelNotificationReturnsNull() { var handlerStartedBarrier = new TaskCompletionSource<object>(); var cancelNotificationReceivedBarrier = new TaskCompletionSource<object>(); var successTcs = new TaskCompletionSource<string>(); helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) => { handlerStartedBarrier.SetResult(null); // wait for cancellation to be delivered. context.CancellationToken.Register(() => cancelNotificationReceivedBarrier.SetResult(null)); await cancelNotificationReceivedBarrier.Task; var moveNextResult = await requestStream.MoveNext(); successTcs.SetResult(!moveNextResult ? "SUCCESS" : "FAIL"); return ""; }); var cts = new CancellationTokenSource(); var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall(new CallOptions(cancellationToken: cts.Token))); await handlerStartedBarrier.Task; cts.Cancel(); try { await call.ResponseAsync; Assert.Fail(); } catch (RpcException ex) { Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode); } Assert.AreEqual("SUCCESS", await successTcs.Task); } [Test] public async Task AsyncUnaryCall_EchoMetadata() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { foreach (Metadata.Entry metadataEntry in context.RequestHeaders) { if (metadataEntry.Key != "user-agent") { context.ResponseTrailers.Add(metadataEntry); } } return ""; }); var headers = new Metadata { { "ascii-header", "abcdefg" }, { "binary-header-bin", new byte[] { 1, 2, 3, 0, 0xff } } }; var call = Calls.AsyncUnaryCall(helper.CreateUnaryCall(new CallOptions(headers: headers)), "ABC"); await call; Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode); var trailers = call.GetTrailers(); Assert.AreEqual(2, trailers.Count); Assert.AreEqual(headers[0].Key, trailers[0].Key); Assert.AreEqual(headers[0].Value, trailers[0].Value); Assert.AreEqual(headers[1].Key, trailers[1].Key); CollectionAssert.AreEqual(headers[1].ValueBytes, trailers[1].ValueBytes); } [Test] public void UnknownMethodHandler() { var nonexistentMethod = new Method<string, string>( MethodType.Unary, MockServiceHelper.ServiceName, "NonExistentMethod", Marshallers.StringMarshaller, Marshallers.StringMarshaller); var callDetails = new CallInvocationDetails<string, string>(channel, nonexistentMethod, new CallOptions()); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(callDetails, "abc")); Assert.AreEqual(StatusCode.Unimplemented, ex.Status.StatusCode); } [Test] public void StatusDetailIsUtf8() { // some japanese and chinese characters var nonAsciiString = "\u30a1\u30a2\u30a3 \u62b5\u6297\u662f\u5f92\u52b3\u7684"; helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { context.Status = new Status(StatusCode.Unknown, nonAsciiString); return ""; }); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unknown, ex.Status.StatusCode); Assert.AreEqual(nonAsciiString, ex.Status.Detail); } [Test] public void ServerCallContext_PeerInfoPresent() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { return context.Peer; }); string peer = Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"); Assert.IsTrue(peer.Contains(Host)); } [Test] public void ServerCallContext_HostAndMethodPresent() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { Assert.IsTrue(context.Host.Contains(Host)); Assert.AreEqual("/tests.Test/Unary", context.Method); return "PASS"; }); Assert.AreEqual("PASS", Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); } [Test] public async Task Channel_WaitForStateChangedAsync() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { return request; }); Assert.ThrowsAsync(typeof(TaskCanceledException), async () => await channel.WaitForStateChangedAsync(channel.State, DateTime.UtcNow.AddMilliseconds(10))); var stateChangedTask = channel.WaitForStateChangedAsync(channel.State); await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc"); await stateChangedTask; Assert.AreEqual(ChannelState.Ready, channel.State); } [Test] public async Task Channel_ConnectAsync() { await channel.ConnectAsync(); Assert.AreEqual(ChannelState.Ready, channel.State); await channel.ConnectAsync(DateTime.UtcNow.AddMilliseconds(1000)); Assert.AreEqual(ChannelState.Ready, channel.State); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using QuantConnect.Data; using QuantConnect.Interfaces; using QuantConnect.Logging; namespace QuantConnect.Lean.Engine.DataFeeds { /// <summary> /// Provides a means of distributing output from enumerators from a dedicated separate thread /// </summary> public class BaseDataExchange { private int _sleepInterval = 1; private volatile bool _isStopping = false; private Func<Exception, bool> _isFatalError; private readonly string _name; private readonly object _enumeratorsWriteLock = new object(); private readonly ConcurrentDictionary<Symbol, DataHandler> _dataHandlers; private ConcurrentDictionary<Symbol, EnumeratorHandler> _enumerators; /// <summary> /// Gets or sets how long this thread will sleep when no data is available /// </summary> public int SleepInterval { get { return _sleepInterval; } set { if (value > -1) _sleepInterval = value; } } /// <summary> /// Gets a name for this exchange /// </summary> public string Name { get { return _name; } } /// <summary> /// Initializes a new instance of the <see cref="BaseDataExchange"/> /// </summary> /// <param name="name">A name for this exchange</param> /// <param name="enumerators">The enumerators to fanout</param> public BaseDataExchange(string name) { _name = name; _isFatalError = x => false; _dataHandlers = new ConcurrentDictionary<Symbol, DataHandler>(); _enumerators = new ConcurrentDictionary<Symbol, EnumeratorHandler>(); } /// <summary> /// Adds the enumerator to this exchange. If it has already been added /// then it will remain registered in the exchange only once /// </summary> /// <param name="handler">The handler to use when this symbol's data is encountered</param> public void AddEnumerator(EnumeratorHandler handler) { _enumerators[handler.Symbol] = handler; } /// <summary> /// Adds the enumerator to this exchange. If it has already been added /// then it will remain registered in the exchange only once /// </summary> /// <param name="symbol">A unique symbol used to identify this enumerator</param> /// <param name="enumerator">The enumerator to be added</param> /// <param name="shouldMoveNext">Function used to determine if move next should be called on this /// enumerator, defaults to always returning true</param> /// <param name="enumeratorFinished">Delegate called when the enumerator move next returns false</param> public void AddEnumerator(Symbol symbol, IEnumerator<BaseData> enumerator, Func<bool> shouldMoveNext = null, Action<EnumeratorHandler> enumeratorFinished = null) { var enumeratorHandler = new EnumeratorHandler(symbol, enumerator, shouldMoveNext); if (enumeratorFinished != null) { enumeratorHandler.EnumeratorFinished += (sender, args) => enumeratorFinished(args); } AddEnumerator(enumeratorHandler); } /// <summary> /// Sets the specified function as the error handler. This function /// returns true if it is a fatal error and queue consumption should /// cease. /// </summary> /// <param name="isFatalError">The error handling function to use when an /// error is encountered during queue consumption. Returns true if queue /// consumption should be stopped, returns false if queue consumption should /// continue</param> public void SetErrorHandler(Func<Exception, bool> isFatalError) { // default to false; _isFatalError = isFatalError ?? (x => false); } /// <summary> /// Sets the specified hander function to handle data for the handler's symbol /// </summary> /// <param name="handler">The handler to use when this symbol's data is encountered</param> /// <returns>An identifier that can be used to remove this handler</returns> public void SetDataHandler(DataHandler handler) { _dataHandlers[handler.Symbol] = handler; } /// <summary> /// Sets the specified hander function to handle data for the handler's symbol /// </summary> /// <param name="symbol">The symbol whose data is to be handled</param> /// <param name="handler">The handler to use when this symbol's data is encountered</param> /// <returns>An identifier that can be used to remove this handler</returns> public void SetDataHandler(Symbol symbol, Action<BaseData> handler) { var dataHandler = new DataHandler(symbol); dataHandler.DataEmitted += (sender, args) => handler(args); SetDataHandler(dataHandler); } /// <summary> /// Adds the specified hander function to handle data for the handler's symbol /// </summary> /// <param name="symbol">The symbol whose data is to be handled</param> /// <param name="handler">The handler to use when this symbol's data is encountered</param> /// <returns>An identifier that can be used to remove this handler</returns> public void AddDataHandler(Symbol symbol, Action<BaseData> handler) { _dataHandlers.AddOrUpdate(symbol, x => { var dataHandler = new DataHandler(symbol); dataHandler.DataEmitted += (sender, args) => handler(args); return dataHandler; }, (x, existingHandler) => { existingHandler.DataEmitted += (sender, args) => handler(args); return existingHandler; }); } /// <summary> /// Removes the handler with the specified identifier /// </summary> /// <param name="symbol">The symbol to remove handlers for</param> public bool RemoveDataHandler(Symbol symbol) { DataHandler handler; return _dataHandlers.TryRemove(symbol, out handler); } /// <summary> /// Removes and returns enumerator handler with the specified symbol. /// The removed handler is returned, null if not found /// </summary> public EnumeratorHandler RemoveEnumerator(Symbol symbol) { EnumeratorHandler handler; if (_enumerators.TryRemove(symbol, out handler)) { handler.OnEnumeratorFinished(); handler.Enumerator.Dispose(); } return handler; } /// <summary> /// Begins consumption of the wrapped <see cref="IDataQueueHandler"/> on /// a separate thread /// </summary> /// <param name="token">A cancellation token used to signal to stop</param> public void Start(CancellationToken? token = null) { Log.Trace("BaseDataExchange({0}) Starting...", Name); _isStopping = false; ConsumeEnumerators(token ?? CancellationToken.None); } /// <summary> /// Ends consumption of the wrapped <see cref="IDataQueueHandler"/> /// </summary> public void Stop() { Log.Trace("BaseDataExchange({0}) Stopping...", Name); _isStopping = true; } /// <summary> Entry point for queue consumption </summary> /// <param name="token">A cancellation token used to signal to stop</param> /// <remarks> This function only returns after <see cref="Stop"/> is called or the token is cancelled</remarks> private void ConsumeEnumerators(CancellationToken token) { while (true) { if (_isStopping || token.IsCancellationRequested) { _isStopping = true; var request = token.IsCancellationRequested ? "Cancellation requested" : "Stop requested"; Log.Trace("BaseDataExchange({0}).ConsumeQueue(): {1}. Exiting...", Name, request); return; } try { // call move next each enumerator and invoke the appropriate handlers var handled = false; foreach (var kvp in _enumerators) { var enumeratorHandler = kvp.Value; var enumerator = enumeratorHandler.Enumerator; // check to see if we should advance this enumerator if (!enumeratorHandler.ShouldMoveNext()) continue; if (!enumerator.MoveNext()) { enumeratorHandler.OnEnumeratorFinished(); enumeratorHandler.Enumerator.Dispose(); _enumerators.TryRemove(enumeratorHandler.Symbol, out enumeratorHandler); continue; } if (enumerator.Current == null) continue; // if the enumerator is configured to handle it, then do it, don't pass to data handlers if (enumeratorHandler.HandlesData) { handled = true; enumeratorHandler.HandleData(enumerator.Current); continue; } // invoke the correct handler DataHandler dataHandler; if (_dataHandlers.TryGetValue(enumerator.Current.Symbol, out dataHandler)) { handled = true; dataHandler.OnDataEmitted(enumerator.Current); } } // if we didn't handle anything on this past iteration, take a nap if (!handled && _sleepInterval != 0) { Thread.Sleep(_sleepInterval); } } catch (Exception err) { Log.Error(err); if (_isFatalError(err)) { Log.Trace("BaseDataExchange({0}).ConsumeQueue(): Fatal error encountered. Exiting...", Name); return; } } } } /// <summary> /// Handler used to handle data emitted from enumerators /// </summary> public class DataHandler { /// <summary> /// Event fired when MoveNext returns true and Current is non-null /// </summary> public event EventHandler<BaseData> DataEmitted; /// <summary> /// The symbol this handler handles /// </summary> public readonly Symbol Symbol; /// <summary> /// Initializes a new instance of the <see cref="DataHandler"/> class /// </summary> /// <param name="symbol">The symbol whose data is to be handled</param> public DataHandler(Symbol symbol) { Symbol = symbol; } /// <summary> /// Event invocator for the <see cref="DataEmitted"/> event /// </summary> /// <param name="data">The data being emitted</param> public void OnDataEmitted(BaseData data) { var handler = DataEmitted; if (handler != null) handler(this, data); } } /// <summary> /// Handler used to manage a single enumerator's move next/end of stream behavior /// </summary> public class EnumeratorHandler { private readonly Func<bool> _shouldMoveNext; private readonly Action<BaseData> _handleData; /// <summary> /// Event fired when MoveNext returns false /// </summary> public event EventHandler<EnumeratorHandler> EnumeratorFinished; /// <summary> /// A unique symbol used to identify this enumerator /// </summary> public readonly Symbol Symbol; /// <summary> /// The enumerator this handler handles /// </summary> public readonly IEnumerator<BaseData> Enumerator; /// <summary> /// Determines whether or not this handler is to be used for handling the /// data emitted. This is useful when enumerators are not for a single symbol, /// such is the case with universe subscriptions /// </summary> public readonly bool HandlesData; /// <summary> /// Initializes a new instance of the <see cref="EnumeratorHandler"/> class /// </summary> /// <param name="symbol">The symbol to identify this enumerator</param> /// <param name="enumerator">The enumeator this handler handles</param> /// <param name="shouldMoveNext">Predicate function used to determine if we should call move next /// on the symbol's enumerator</param> /// <param name="handleData">Handler for data if HandlesData=true</param> public EnumeratorHandler(Symbol symbol, IEnumerator<BaseData> enumerator, Func<bool> shouldMoveNext = null, Action<BaseData> handleData = null) { Symbol = symbol; Enumerator = enumerator; HandlesData = handleData != null; _handleData = handleData ?? (data => { }); _shouldMoveNext = shouldMoveNext ?? (() => true); } /// <summary> /// Initializes a new instance of the <see cref="EnumeratorHandler"/> class /// </summary> /// <param name="symbol">The symbol to identify this enumerator</param> /// <param name="enumerator">The enumeator this handler handles</param> /// <param name="handlesData">True if this handler will handle the data, false otherwise</param> protected EnumeratorHandler(Symbol symbol, IEnumerator<BaseData> enumerator, bool handlesData) { Symbol = symbol; HandlesData = handlesData; Enumerator = enumerator; _handleData = data => { }; _shouldMoveNext = () => true; } /// <summary> /// Event invocator for the <see cref="EnumeratorFinished"/> event /// </summary> public virtual void OnEnumeratorFinished() { var handler = EnumeratorFinished; if (handler != null) handler(this, this); } /// <summary> /// Returns true if this enumerator should move next /// </summary> public virtual bool ShouldMoveNext() { return _shouldMoveNext(); } /// <summary> /// Handles the specified data. /// </summary> /// <param name="data">The data to be handled</param> public virtual void HandleData(BaseData data) { _handleData(data); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.FindSymbols.SymbolTree; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SolutionCrawler; using Roslyn.Utilities; using System.IO; namespace Microsoft.CodeAnalysis.IncrementalCaches { /// <summary> /// Features like add-using want to be able to quickly search symbol indices for projects and /// metadata. However, creating those indices can be expensive. As such, we don't want to /// construct them during the add-using process itself. Instead, we expose this type as an /// Incremental-Analyzer to walk our projects/metadata in the background to keep the indices /// up to date. /// /// We also then export this type as a service that can give back the index for a project or /// metadata dll on request. If the index has been produced then it will be returned and /// can be used by add-using. Otherwise, nothing is returned and no results will be found. /// /// This means that as the project is being indexed, partial results may be returned. However /// once it is fully indexed, then total results will be returned. /// </summary> [Shared] [ExportIncrementalAnalyzerProvider(nameof(SymbolTreeInfoIncrementalAnalyzerProvider), new[] { WorkspaceKind.Host })] [ExportWorkspaceServiceFactory(typeof(ISymbolTreeInfoCacheService))] internal class SymbolTreeInfoIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider, IWorkspaceServiceFactory { private struct ProjectInfo { public readonly VersionStamp VersionStamp; public readonly SymbolTreeInfo SymbolTreeInfo; public ProjectInfo(VersionStamp versionStamp, SymbolTreeInfo info) { VersionStamp = versionStamp; SymbolTreeInfo = info; } } private struct MetadataInfo { public readonly DateTime TimeStamp; /// <summary> /// Note: can be <code>null</code> if were unable to create a SymbolTreeInfo /// (for example, if the metadata was bogus and we couldn't read it in). /// </summary> public readonly SymbolTreeInfo SymbolTreeInfo; /// <summary> /// Note: the Incremental-Analyzer infrastructure guarantees that it will call all the methods /// on <see cref="IncrementalAnalyzer"/> in a serial fashion. As that is the only type that /// reads/writes these <see cref="MetadataInfo"/> objects, we don't need to lock this. /// </summary> public readonly HashSet<ProjectId> ReferencingProjects; public MetadataInfo(DateTime timeStamp, SymbolTreeInfo info, HashSet<ProjectId> referencingProjects) { TimeStamp = timeStamp; SymbolTreeInfo = info; ReferencingProjects = referencingProjects; } } // Concurrent dictionaries so they can be read from the SymbolTreeInfoCacheService while // they are being populated/updated by the IncrementalAnalyzer. private readonly ConcurrentDictionary<ProjectId, ProjectInfo> _projectToInfo = new ConcurrentDictionary<ProjectId, ProjectInfo>(); private readonly ConcurrentDictionary<string, MetadataInfo> _metadataPathToInfo = new ConcurrentDictionary<string, MetadataInfo>(); public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) { var cacheService = workspace.Services.GetService<IWorkspaceCacheService>(); if (cacheService != null) { cacheService.CacheFlushRequested += OnCacheFlushRequested; } return new IncrementalAnalyzer(_projectToInfo, _metadataPathToInfo); } private void OnCacheFlushRequested(object sender, EventArgs e) { // If we hear about low memory conditions, flush our caches. This will degrade the // experience a bit (as we will no longer offer to Add-Using for p2p refs/metadata), // but will be better than OOM'ing. These caches will be regenerated in the future // when the incremental analyzer reanalyzers the projects in teh workspace. _projectToInfo.Clear(); _metadataPathToInfo.Clear(); } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { return new SymbolTreeInfoCacheService(_projectToInfo, _metadataPathToInfo); } private static string GetReferenceKey(PortableExecutableReference reference) { return reference.FilePath ?? reference.Display; } private static bool TryGetLastWriteTime(string path, out DateTime time) { var succeeded = false; time = IOUtilities.PerformIO( () => { var result = File.GetLastWriteTimeUtc(path); succeeded = true; return result; }, default(DateTime)); return succeeded; } private class SymbolTreeInfoCacheService : ISymbolTreeInfoCacheService { private readonly ConcurrentDictionary<ProjectId, ProjectInfo> _projectToInfo; private readonly ConcurrentDictionary<string, MetadataInfo> _metadataPathToInfo; public SymbolTreeInfoCacheService( ConcurrentDictionary<ProjectId, ProjectInfo> projectToInfo, ConcurrentDictionary<string, MetadataInfo> metadataPathToInfo) { _projectToInfo = projectToInfo; _metadataPathToInfo = metadataPathToInfo; } public async Task<SymbolTreeInfo> TryGetMetadataSymbolTreeInfoAsync( Solution solution, PortableExecutableReference reference, CancellationToken cancellationToken) { var key = GetReferenceKey(reference); if (key != null) { if (_metadataPathToInfo.TryGetValue(key, out var metadataInfo)) { if (TryGetLastWriteTime(key, out var writeTime) && writeTime == metadataInfo.TimeStamp) { return metadataInfo.SymbolTreeInfo; } } } // If we didn't have it in our cache, see if we can load it from disk. // Note: pass 'loadOnly' so we only attempt to load from disk, not to actually // try to create the metadata. var info = await SymbolTreeInfo.TryGetInfoForMetadataReferenceAsync( solution, reference, loadOnly: true, cancellationToken: cancellationToken).ConfigureAwait(false); return info; } public async Task<SymbolTreeInfo> TryGetSourceSymbolTreeInfoAsync( Project project, CancellationToken cancellationToken) { if (_projectToInfo.TryGetValue(project.Id, out var projectInfo)) { var version = await project.GetSemanticVersionAsync(cancellationToken).ConfigureAwait(false); if (version == projectInfo.VersionStamp) { return projectInfo.SymbolTreeInfo; } } return null; } } private class IncrementalAnalyzer : IncrementalAnalyzerBase { private readonly ConcurrentDictionary<ProjectId, ProjectInfo> _projectToInfo; private readonly ConcurrentDictionary<string, MetadataInfo> _metadataPathToInfo; public IncrementalAnalyzer( ConcurrentDictionary<ProjectId, ProjectInfo> projectToInfo, ConcurrentDictionary<string, MetadataInfo> metadataPathToInfo) { _projectToInfo = projectToInfo; _metadataPathToInfo = metadataPathToInfo; } public override Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken) { if (!document.SupportsSyntaxTree) { // Not a language we can produce indices for (i.e. TypeScript). Bail immediately. return SpecializedTasks.EmptyTask; } if (bodyOpt != null) { // This was a method level edit. This can't change the symbol tree info // for this project. Bail immediately. return SpecializedTasks.EmptyTask; } return UpdateSymbolTreeInfoAsync(document.Project, cancellationToken); } public override Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken) { return UpdateSymbolTreeInfoAsync(project, cancellationToken); } private async Task UpdateSymbolTreeInfoAsync(Project project, CancellationToken cancellationToken) { if (!project.SupportsCompilation) { return; } // Check the semantic version of this project. The semantic version will change // if any of the source files changed, or if the project version itself changed. // (The latter happens when something happens to the project like metadata // changing on disk). var version = await project.GetSemanticVersionAsync(cancellationToken).ConfigureAwait(false); if (!_projectToInfo.TryGetValue(project.Id, out var projectInfo) || projectInfo.VersionStamp != version) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); // Update the symbol tree infos for metadata and source in parallel. var referencesTask = UpdateReferencesAync(project, compilation, cancellationToken); var projectTask = SymbolTreeInfo.GetInfoForSourceAssemblyAsync(project, cancellationToken); await Task.WhenAll(referencesTask, projectTask).ConfigureAwait(false); // Mark that we're up to date with this project. Future calls with the same // semantic version can bail out immediately. projectInfo = new ProjectInfo(version, await projectTask.ConfigureAwait(false)); _projectToInfo.AddOrUpdate(project.Id, projectInfo, (_1, _2) => projectInfo); } } private Task UpdateReferencesAync(Project project, Compilation compilation, CancellationToken cancellationToken) { // Process all metadata references in parallel. var tasks = project.MetadataReferences.OfType<PortableExecutableReference>() .Select(r => UpdateReferenceAsync(project, compilation, r, cancellationToken)) .ToArray(); return Task.WhenAll(tasks); } private async Task UpdateReferenceAsync( Project project, Compilation compilation, PortableExecutableReference reference, CancellationToken cancellationToken) { var key = GetReferenceKey(reference); if (key == null) { return; } if (!TryGetLastWriteTime(key, out var lastWriteTime)) { // Couldn't get the write time. Just ignore this reference. return; } if (!_metadataPathToInfo.TryGetValue(key, out var metadataInfo) || metadataInfo.TimeStamp == lastWriteTime) { var info = await SymbolTreeInfo.TryGetInfoForMetadataReferenceAsync( project.Solution, reference, loadOnly: false, cancellationToken: cancellationToken).ConfigureAwait(false); // Note, getting the info may fail (for example, bogus metadata). That's ok. // We still want to cache that result so that don't try to continuously produce // this info over and over again. metadataInfo = new MetadataInfo(lastWriteTime, info, metadataInfo.ReferencingProjects ?? new HashSet<ProjectId>()); _metadataPathToInfo.AddOrUpdate(key, metadataInfo, (_1, _2) => metadataInfo); } // Keep track that this dll is referenced by this project. metadataInfo.ReferencingProjects.Add(project.Id); } public override void RemoveProject(ProjectId projectId) { _projectToInfo.TryRemove(projectId, out var info); RemoveMetadataReferences(projectId); } private void RemoveMetadataReferences(ProjectId projectId) { foreach (var kvp in _metadataPathToInfo.ToArray()) { if (kvp.Value.ReferencingProjects.Remove(projectId)) { if (kvp.Value.ReferencingProjects.Count == 0) { // This metadata dll isn't referenced by any project. We can just dump it. _metadataPathToInfo.TryRemove(kvp.Key, out var unneeded); } } } } } } }
using System; using System.Xml; using System.Xml.XPath; using System.Collections.Generic; using System.ComponentModel; using System.IO; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.IO; using Umbraco.Core.Logging; namespace umbraco.cms.businesslogic.packager { /// <summary> /// This is the xml data for installed packages. This is not the same xml as a pckage format! /// </summary> public class data { private static XmlDocument _source; public static XmlDocument Source { get { return _source; } } public static void Reload(string dataSource) { //do some error checking and create the folders/files if they don't exist if (!File.Exists(dataSource)) { if (!Directory.Exists(IOHelper.MapPath(Settings.PackagerRoot))) { Directory.CreateDirectory(IOHelper.MapPath(Settings.PackagerRoot)); } if (!Directory.Exists(IOHelper.MapPath(Settings.PackagesStorage))) { Directory.CreateDirectory(IOHelper.MapPath(Settings.PackagesStorage)); } if (!Directory.Exists(IOHelper.MapPath(Settings.InstalledPackagesStorage))) { Directory.CreateDirectory(IOHelper.MapPath(Settings.InstalledPackagesStorage)); } using (StreamWriter sw = File.CreateText(dataSource)) { sw.Write(umbraco.cms.businesslogic.Packager.FileResources.PackageFiles.Packages); sw.Flush(); } } if (_source == null) { _source = new XmlDocument(); } //error checking here if (File.Exists(dataSource)) { var isEmpty = false; using (var sr = new StreamReader(dataSource)) { if (sr.ReadToEnd().IsNullOrWhiteSpace()) { isEmpty = true; } } if (isEmpty) { File.WriteAllText(dataSource, @"<?xml version=""1.0"" encoding=""utf-8""?><packages></packages>"); } } _source.Load(dataSource); } public static XmlNode GetFromId(int Id, string dataSource, bool reload) { if (reload) Reload(dataSource); return Source.SelectSingleNode("/packages/package [@id = '" + Id.ToString().ToUpper() + "']"); } public static XmlNode GetFromGuid(string guid, string dataSource, bool reload) { if (reload) Reload(dataSource); return Source.SelectSingleNode("/packages/package [@packageGuid = '" + guid + "']"); } public static PackageInstance MakeNew(string Name, string dataSource) { Reload(dataSource); int maxId = 1; // Find max id foreach (XmlNode n in Source.SelectNodes("packages/package")) { if (int.Parse(n.Attributes.GetNamedItem("id").Value) >= maxId) maxId = int.Parse(n.Attributes.GetNamedItem("id").Value) + 1; } XmlElement instance = Source.CreateElement("package"); instance.Attributes.Append(XmlHelper.AddAttribute(Source, "id", maxId.ToString())); instance.Attributes.Append(XmlHelper.AddAttribute(Source, "version", "")); instance.Attributes.Append(XmlHelper.AddAttribute(Source, "url", "")); instance.Attributes.Append(XmlHelper.AddAttribute(Source, "name", Name)); instance.Attributes.Append(XmlHelper.AddAttribute(Source, "folder", Guid.NewGuid().ToString())); instance.Attributes.Append(XmlHelper.AddAttribute(Source, "packagepath", "")); instance.Attributes.Append(XmlHelper.AddAttribute(Source, "repositoryGuid", "")); instance.Attributes.Append(XmlHelper.AddAttribute(Source, "iconUrl", "")); //set to current version instance.Attributes.Append(XmlHelper.AddAttribute(Source, "umbVersion", UmbracoVersion.Current.ToString(3))); instance.Attributes.Append(XmlHelper.AddAttribute(Source, "packageGuid", Guid.NewGuid().ToString())); instance.Attributes.Append(XmlHelper.AddAttribute(Source, "hasUpdate", "false")); instance.Attributes.Append(XmlHelper.AddAttribute(Source, "enableSkins", "false")); instance.Attributes.Append(XmlHelper.AddAttribute(Source, "skinRepoGuid", "")); XmlElement license = Source.CreateElement("license"); license.InnerText = "MIT License"; license.Attributes.Append(XmlHelper.AddAttribute(Source, "url", "http://opensource.org/licenses/MIT")); instance.AppendChild(license); XmlElement author = Source.CreateElement("author"); author.InnerText = ""; author.Attributes.Append(XmlHelper.AddAttribute(Source, "url", "")); instance.AppendChild(author); instance.AppendChild(XmlHelper.AddTextNode(Source, "readme", "")); instance.AppendChild(XmlHelper.AddTextNode(Source, "actions", "")); instance.AppendChild(XmlHelper.AddTextNode(Source, "datatypes", "")); XmlElement content = Source.CreateElement("content"); content.InnerText = ""; content.Attributes.Append(XmlHelper.AddAttribute(Source, "nodeId", "")); content.Attributes.Append(XmlHelper.AddAttribute(Source, "loadChildNodes", "false")); instance.AppendChild(content); instance.AppendChild(XmlHelper.AddTextNode(Source, "templates", "")); instance.AppendChild(XmlHelper.AddTextNode(Source, "stylesheets", "")); instance.AppendChild(XmlHelper.AddTextNode(Source, "documenttypes", "")); instance.AppendChild(XmlHelper.AddTextNode(Source, "macros", "")); instance.AppendChild(XmlHelper.AddTextNode(Source, "files", "")); instance.AppendChild(XmlHelper.AddTextNode(Source, "languages", "")); instance.AppendChild(XmlHelper.AddTextNode(Source, "dictionaryitems", "")); instance.AppendChild(XmlHelper.AddTextNode(Source, "loadcontrol", "")); Source.SelectSingleNode("packages").AppendChild(instance); Source.Save(dataSource); var retVal = data.Package(maxId, dataSource); return retVal; } public static PackageInstance Package(int id, string datasource) { return ConvertXmlToPackage(GetFromId(id, datasource, true)); } public static PackageInstance Package(string guid, string datasource) { XmlNode node = GetFromGuid(guid, datasource, true); if (node != null) return ConvertXmlToPackage(node); else return new PackageInstance(); } public static List<PackageInstance> GetAllPackages(string dataSource) { Reload(dataSource); XmlNodeList nList = data.Source.SelectNodes("packages/package"); List<PackageInstance> retVal = new List<PackageInstance>(); for (int i = 0; i < nList.Count; i++) { try { retVal.Add(ConvertXmlToPackage(nList[i])); } catch (Exception ex) { LogHelper.Error<data>("An error occurred in GetAllPackages", ex); } } return retVal; } private static PackageInstance ConvertXmlToPackage(XmlNode n) { PackageInstance retVal = new PackageInstance(); if (n != null) { retVal.Id = int.Parse(SafeAttribute("id", n)); retVal.Name = SafeAttribute("name", n); retVal.Folder = SafeAttribute("folder", n); retVal.PackagePath = SafeAttribute("packagepath", n); retVal.Version = SafeAttribute("version", n); retVal.Url = SafeAttribute("url", n); retVal.RepositoryGuid = SafeAttribute("repositoryGuid", n); retVal.PackageGuid = SafeAttribute("packageGuid", n); retVal.HasUpdate = bool.Parse(SafeAttribute("hasUpdate", n)); retVal.IconUrl = SafeAttribute("iconUrl", n); var umbVersion = SafeAttribute("umbVersion", n); Version parsedVersion; if (umbVersion.IsNullOrWhiteSpace() == false && Version.TryParse(umbVersion, out parsedVersion)) { retVal.UmbracoVersion = parsedVersion; } bool enableSkins = false; bool.TryParse(SafeAttribute("enableSkins", n), out enableSkins); retVal.EnableSkins = enableSkins; retVal.SkinRepoGuid = string.IsNullOrEmpty(SafeAttribute("skinRepoGuid", n)) ? Guid.Empty : new Guid(SafeAttribute("skinRepoGuid", n)); retVal.License = SafeNodeValue(n.SelectSingleNode("license")); retVal.LicenseUrl = n.SelectSingleNode("license").Attributes.GetNamedItem("url").Value; retVal.Author = SafeNodeValue(n.SelectSingleNode("author")); retVal.AuthorUrl = SafeAttribute("url", n.SelectSingleNode("author")); retVal.Readme = SafeNodeValue(n.SelectSingleNode("readme")); retVal.Actions = SafeNodeInnerXml(n.SelectSingleNode("actions")); retVal.ContentNodeId = SafeAttribute("nodeId", n.SelectSingleNode("content")); retVal.ContentLoadChildNodes = bool.Parse(SafeAttribute("loadChildNodes", n.SelectSingleNode("content"))); retVal.Macros = new List<string>(SafeNodeValue(n.SelectSingleNode("macros")).Trim(',').Split(',')); retVal.Macros = new List<string>(SafeNodeValue(n.SelectSingleNode("macros")).Trim(',').Split(',')); retVal.Templates = new List<string>(SafeNodeValue(n.SelectSingleNode("templates")).Trim(',').Split(',')); retVal.Stylesheets = new List<string>(SafeNodeValue(n.SelectSingleNode("stylesheets")).Trim(',').Split(',')); retVal.Documenttypes = new List<string>(SafeNodeValue(n.SelectSingleNode("documenttypes")).Trim(',').Split(',')); retVal.Languages = new List<string>(SafeNodeValue(n.SelectSingleNode("languages")).Trim(',').Split(',')); retVal.DictionaryItems = new List<string>(SafeNodeValue(n.SelectSingleNode("dictionaryitems")).Trim(',').Split(',')); retVal.DataTypes = new List<string>(SafeNodeValue(n.SelectSingleNode("datatypes")).Trim(',').Split(',')); XmlNodeList xmlFiles = n.SelectNodes("files/file"); retVal.Files = new List<string>(); for (int i = 0; i < xmlFiles.Count; i++) retVal.Files.Add(xmlFiles[i].InnerText); retVal.LoadControl = SafeNodeValue(n.SelectSingleNode("loadcontrol")); } return retVal; } public static void Delete(int Id, string dataSource) { Reload(dataSource); // Remove physical xml file if any //PackageInstance p = new PackageInstance(Id); //TODO DELETE PACKAGE FOLDER... //p.Folder XmlNode n = data.GetFromId(Id, dataSource, true); if (n != null) { data.Source.SelectSingleNode("/packages").RemoveChild(n); data.Source.Save(dataSource); } } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This method is no longer in use and will be removed in the future")] public static void UpdateValue(XmlNode n, string Value) { if (n.FirstChild != null) n.FirstChild.Value = Value; else { n.AppendChild(Source.CreateTextNode(Value)); } } public static void Save(PackageInstance package, string dataSource) { Reload(dataSource); var xmlDef = GetFromId(package.Id, dataSource, false); XmlHelper.SetAttribute(Source, xmlDef, "name", package.Name); XmlHelper.SetAttribute(Source, xmlDef, "version", package.Version); XmlHelper.SetAttribute(Source, xmlDef, "url", package.Url); XmlHelper.SetAttribute(Source, xmlDef, "packagepath", package.PackagePath); XmlHelper.SetAttribute(Source, xmlDef, "repositoryGuid", package.RepositoryGuid); XmlHelper.SetAttribute(Source, xmlDef, "packageGuid", package.PackageGuid); XmlHelper.SetAttribute(Source, xmlDef, "hasUpdate", package.HasUpdate.ToString()); XmlHelper.SetAttribute(Source, xmlDef, "enableSkins", package.EnableSkins.ToString()); XmlHelper.SetAttribute(Source, xmlDef, "skinRepoGuid", package.SkinRepoGuid.ToString()); XmlHelper.SetAttribute(Source, xmlDef, "iconUrl", package.IconUrl); if (package.UmbracoVersion != null) { XmlHelper.SetAttribute(Source, xmlDef, "umbVersion", package.UmbracoVersion.ToString(3)); } var licenseNode = xmlDef.SelectSingleNode("license"); if (licenseNode == null) { licenseNode = Source.CreateElement("license"); xmlDef.AppendChild(licenseNode); } licenseNode.InnerText = package.License; XmlHelper.SetAttribute(Source, licenseNode, "url", package.LicenseUrl); var authorNode = xmlDef.SelectSingleNode("author"); if (authorNode == null) { authorNode = Source.CreateElement("author"); xmlDef.AppendChild(authorNode); } authorNode.InnerText = package.Author; XmlHelper.SetAttribute(Source, authorNode, "url", package.AuthorUrl); XmlHelper.SetCDataNode(Source, xmlDef, "readme", package.Readme); XmlHelper.SetInnerXmlNode(Source, xmlDef, "actions", package.Actions); var contentNode = xmlDef.SelectSingleNode("content"); if (contentNode == null) { contentNode = Source.CreateElement("content"); xmlDef.AppendChild(contentNode); } XmlHelper.SetAttribute(Source, contentNode, "nodeId", package.ContentNodeId); XmlHelper.SetAttribute(Source, contentNode, "loadChildNodes", package.ContentLoadChildNodes.ToString()); XmlHelper.SetTextNode(Source, xmlDef, "macros", JoinList(package.Macros, ',')); XmlHelper.SetTextNode(Source, xmlDef, "templates", JoinList(package.Templates, ',')); XmlHelper.SetTextNode(Source, xmlDef, "stylesheets", JoinList(package.Stylesheets, ',')); XmlHelper.SetTextNode(Source, xmlDef, "documenttypes", JoinList(package.Documenttypes, ',')); XmlHelper.SetTextNode(Source, xmlDef, "languages", JoinList(package.Languages, ',')); XmlHelper.SetTextNode(Source, xmlDef, "dictionaryitems", JoinList(package.DictionaryItems, ',')); XmlHelper.SetTextNode(Source, xmlDef, "datatypes", JoinList(package.DataTypes, ',')); var filesNode = xmlDef.SelectSingleNode("files"); if (filesNode == null) { filesNode = Source.CreateElement("files"); xmlDef.AppendChild(filesNode); } filesNode.InnerXml = ""; foreach (var fileStr in package.Files) { if (string.IsNullOrWhiteSpace(fileStr) == false) filesNode.AppendChild(XmlHelper.AddTextNode(Source, "file", fileStr)); } XmlHelper.SetTextNode(Source, xmlDef, "loadcontrol", package.LoadControl); Source.Save(dataSource); } private static string SafeAttribute(string name, XmlNode n) { return n.Attributes == null || n.Attributes[name] == null ? string.Empty : n.Attributes[name].Value; } private static string SafeNodeValue(XmlNode n) { try { return XmlHelper.GetNodeValue(n); } catch { return string.Empty; } } private static string SafeNodeInnerXml(XmlNode n) { try { return n.InnerXml; } catch { return string.Empty; } } private static string JoinList(List<string> list, char seperator) { string retVal = ""; foreach (string str in list) { retVal += str + seperator; } return retVal.Trim(seperator); } public data() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Reflection.Emit; using System.Runtime.Remoting; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Tests { public partial class ActivatorTests { [Fact] public void CreateInstance_NonPublicValueTypeWithPrivateDefaultConstructor_Success() { AssemblyName assemblyName = new AssemblyName("Assembly"); AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = moduleBuilder.DefineType("Type", TypeAttributes.Public, typeof(ValueType)); FieldBuilder fieldBuilder = typeBuilder.DefineField("_field", typeof(int), FieldAttributes.Public); ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Private | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.HideBySig, CallingConventions.Standard, new Type[0]); ILGenerator generator = constructorBuilder.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldc_I4, -1); generator.Emit(OpCodes.Stfld, fieldBuilder); generator.Emit(OpCodes.Ret); Type type = typeBuilder.CreateType(); FieldInfo field = type.GetField("_field"); // Activator holds a cache of constructors and the types to which they belong. // Test caching behaviour by activating multiple times. object v1 = Activator.CreateInstance(type, nonPublic: true); Assert.Equal(-1, field.GetValue(v1)); object v2 = Activator.CreateInstance(type, nonPublic: true); Assert.Equal(-1, field.GetValue(v2)); } [Fact] public void CreateInstance_PublicOnlyValueTypeWithPrivateDefaultConstructor_ThrowsMissingMethodException() { AssemblyName assemblyName = new AssemblyName("Assembly"); AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = moduleBuilder.DefineType("Type", TypeAttributes.Public, typeof(ValueType)); FieldBuilder fieldBuilder = typeBuilder.DefineField("_field", typeof(int), FieldAttributes.Public); ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Private | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.HideBySig, CallingConventions.Standard, new Type[0]); ILGenerator generator = constructorBuilder.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldc_I4, -1); generator.Emit(OpCodes.Stfld, fieldBuilder); generator.Emit(OpCodes.Ret); Type type = typeBuilder.CreateType(); Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(type)); Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(type, nonPublic: false)); // Put the private default constructor into the cache and make sure we still throw if public only. Assert.NotNull(Activator.CreateInstance(type, nonPublic: true)); Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(type)); Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(type, nonPublic: false)); } [Theory] [MemberData(nameof(TestingCreateInstanceFromObjectHandleData))] public static void TestingCreateInstanceFromObjectHandle(string physicalFileName, string assemblyFile, string type, string returnedFullNameType, Type exceptionType) { ObjectHandle oh = null; if (exceptionType != null) { Assert.Throws(exceptionType, () => Activator.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type)); } else { oh = Activator.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type); CheckValidity(oh, returnedFullNameType); } if (exceptionType != null) { Assert.Throws(exceptionType, () => Activator.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type, null)); } else { oh = Activator.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type, null); CheckValidity(oh, returnedFullNameType); } Assert.True(File.Exists(physicalFileName)); } public static TheoryData<string, string, string, string, Type> TestingCreateInstanceFromObjectHandleData => new TheoryData<string, string, string, string, Type>() { // string physicalFileName, string assemblyFile, string typeName, returnedFullNameType, expectedException { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PublicClassSample", "PublicClassSample", null }, { "TestLoadAssembly.dll", "testloadassembly.dll", "publicclasssample", "PublicClassSample", typeof(TypeLoadException) }, { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PrivateClassSample", "PrivateClassSample", null }, { "TestLoadAssembly.dll", "testloadassembly.dll", "privateclasssample", "PrivateClassSample", typeof(TypeLoadException) }, { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PublicClassNoDefaultConstructorSample", "PublicClassNoDefaultConstructorSample", typeof(MissingMethodException) }, { "TestLoadAssembly.dll", "testloadassembly.dll", "publicclassnodefaultconstructorsample", "PublicClassNoDefaultConstructorSample", typeof(TypeLoadException) } }; [Theory] [MemberData(nameof(TestingCreateInstanceObjectHandleData))] public static void TestingCreateInstanceObjectHandle(string assemblyName, string type, string returnedFullNameType, Type exceptionType, bool returnNull) { ObjectHandle oh = null; if (exceptionType != null) { Assert.Throws(exceptionType, () => Activator.CreateInstance(assemblyName: assemblyName, typeName: type)); } else { oh = Activator.CreateInstance(assemblyName: assemblyName, typeName: type); if (returnNull) { Assert.Null(oh); } else { CheckValidity(oh, returnedFullNameType); } } if (exceptionType != null) { Assert.Throws(exceptionType, () => Activator.CreateInstance(assemblyName: assemblyName, typeName: type, null)); } else { oh = Activator.CreateInstance(assemblyName: assemblyName, typeName: type, null); if (returnNull) { Assert.Null(oh); } else { CheckValidity(oh, returnedFullNameType); } } } public static TheoryData<string, string, string, Type, bool> TestingCreateInstanceObjectHandleData => new TheoryData<string, string, string, Type, bool>() { // string assemblyName, string typeName, returnedFullNameType, expectedException { "TestLoadAssembly", "PublicClassSample", "PublicClassSample", null, false }, { "testloadassembly", "publicclasssample", "PublicClassSample", typeof(TypeLoadException), false }, { "TestLoadAssembly", "PrivateClassSample", "PrivateClassSample", null, false }, { "testloadassembly", "privateclasssample", "PrivateClassSample", typeof(TypeLoadException), false }, { "TestLoadAssembly", "PublicClassNoDefaultConstructorSample", "PublicClassNoDefaultConstructorSample", typeof(MissingMethodException), false }, { "testloadassembly", "publicclassnodefaultconstructorsample", "PublicClassNoDefaultConstructorSample", typeof(TypeLoadException), false }, { "mscorlib", "System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", "", null, true } }; [Theory] [MemberData(nameof(TestingCreateInstanceFromObjectHandleFullSignatureData))] public static void TestingCreateInstanceFromObjectHandleFullSignature(string physicalFileName, string assemblyFile, string type, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, string returnedFullNameType) { ObjectHandle oh = Activator.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type, ignoreCase: ignoreCase, bindingAttr: bindingAttr, binder: binder, args: args, culture: culture, activationAttributes: activationAttributes); CheckValidity(oh, returnedFullNameType); Assert.True(File.Exists(physicalFileName)); } public static IEnumerable<object[]> TestingCreateInstanceFromObjectHandleFullSignatureData() { // string physicalFileName, string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, returnedFullNameType yield return new object[] { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PublicClassSample", false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PublicClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "testloadassembly.dll", "publicclasssample", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PublicClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PublicClassSample", false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PublicClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "testloadassembly.dll", "publicclasssample", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PublicClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PrivateClassSample", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PrivateClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "testloadassembly.dll", "privateclasssample", true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PrivateClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PrivateClassSample", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PrivateClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "testloadassembly.dll", "privateclasssample", true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PrivateClassSample" }; } [Theory] [MemberData(nameof(TestingCreateInstanceObjectHandleFullSignatureData))] public static void TestingCreateInstanceObjectHandleFullSignature(string assemblyName, string type, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, string returnedFullNameType, bool returnNull) { ObjectHandle oh = Activator.CreateInstance(assemblyName: assemblyName, typeName: type, ignoreCase: ignoreCase, bindingAttr: bindingAttr, binder: binder, args: args, culture: culture, activationAttributes: activationAttributes); if (returnNull) { Assert.Null(oh); } else { CheckValidity(oh, returnedFullNameType); } } public static IEnumerable<object[]> TestingCreateInstanceObjectHandleFullSignatureData() { // string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, returnedFullNameType yield return new object[] { "TestLoadAssembly", "PublicClassSample", false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PublicClassSample" , false }; yield return new object[] { "testloadassembly", "publicclasssample", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PublicClassSample" , false }; yield return new object[] { "TestLoadAssembly", "PublicClassSample", false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PublicClassSample" , false }; yield return new object[] { "testloadassembly", "publicclasssample", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PublicClassSample" , false }; yield return new object[] { "TestLoadAssembly", "PrivateClassSample", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PrivateClassSample", false }; yield return new object[] { "testloadassembly", "privateclasssample", true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PrivateClassSample", false }; yield return new object[] { "TestLoadAssembly", "PrivateClassSample", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PrivateClassSample", false }; yield return new object[] { "testloadassembly", "privateclasssample", true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PrivateClassSample", false }; yield return new object[] { null, typeof(PublicType).FullName, false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, typeof(PublicType).FullName, false }; yield return new object[] { null, typeof(PrivateType).FullName, false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, typeof(PrivateType).FullName, false }; yield return new object[] { "mscorlib", "System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "", true }; } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsWinRTSupported), nameof(PlatformDetection.IsNotWindows8x), nameof(PlatformDetection.IsNotWindowsServerCore), nameof(PlatformDetection.IsNotWindowsNanoServer), nameof(PlatformDetection.IsNotWindowsIoTCore))] [PlatformSpecific(TestPlatforms.Windows)] [MemberData(nameof(TestingCreateInstanceObjectHandleFullSignatureWinRTData))] public static void TestingCreateInstanceObjectHandleFullSignatureWinRT(string assemblyName, string type, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, string returnedFullNameType) { ObjectHandle oh = Activator.CreateInstance(assemblyName: assemblyName, typeName: type, ignoreCase: ignoreCase, bindingAttr: bindingAttr, binder: binder, args: args, culture: culture, activationAttributes: activationAttributes); CheckValidity(oh, returnedFullNameType); } public static IEnumerable<object[]> TestingCreateInstanceObjectHandleFullSignatureWinRTData() { // string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, returnedFullNameType yield return new object[] { "Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime", "Windows.Foundation.Collections.StringMap", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "Windows.Foundation.Collections.StringMap" }; } private static void CheckValidity(ObjectHandle instance, string expected) { Assert.NotNull(instance); Assert.Equal(expected, instance.Unwrap().GetType().FullName); } public class PublicType { public PublicType() { } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.LoadFile is not supported in AppX.")] public static void CreateInstanceAssemblyResolve() { RemoteExecutor.Invoke(() => { AppDomain.CurrentDomain.AssemblyResolve += (object sender, ResolveEventArgs args) => Assembly.LoadFile(Path.Combine(Directory.GetCurrentDirectory(), "TestLoadAssembly.dll")); Assert.Throws<FileLoadException>(() => Activator.CreateInstance(",,,,", "PublicClassSample")); }).Dispose(); } [Fact] public void CreateInstance_TypeBuilder_ThrowsNotSupportedException() { AssemblyName assemblyName = new AssemblyName("Assembly"); AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = moduleBuilder.DefineType("Type", TypeAttributes.Public); Assert.Throws<ArgumentException>("type", () => Activator.CreateInstance(typeBuilder)); Assert.Throws<NotSupportedException>(() => Activator.CreateInstance(typeBuilder, new object[0])); } } }
using System; namespace UnityEngine.Rendering.PostProcessing { // TODO: VR support [Serializable] public sealed class TemporalAntialiasing { [Tooltip("The diameter (in texels) inside which jitter samples are spread. Smaller values result in crisper but more aliased output, while larger values result in more stable but blurrier output.")] [Range(0.1f, 1f)] public float jitterSpread = 0.75f; [Tooltip("Controls the amount of sharpening applied to the color buffer.")] [Range(0f, 3f)] public float sharpen = 0.25f; [Tooltip("The blend coefficient for a stationary fragment. Controls the percentage of history sample blended into the final color.")] [Range(0f, 0.99f)] public float stationaryBlending = 0.95f; [Tooltip("The blend coefficient for a fragment with significant motion. Controls the percentage of history sample blended into the final color.")] [Range(0f, 0.99f)] public float motionBlending = 0.85f; // For custom jittered matrices - use at your own risks public Func<Camera, Vector2, Matrix4x4> jitteredMatrixFunc; public Vector2 jitter { get; private set; } enum Pass { SolverDilate, SolverNoDilate, AlphaClear } readonly RenderTargetIdentifier[] m_Mrt = new RenderTargetIdentifier[2]; bool m_ResetHistory = true; const int k_SampleCount = 8; int m_SampleIndex; // Ping-pong between two history textures as we can't read & write the same target in the // same pass readonly RenderTexture[] m_HistoryTextures = new RenderTexture[2]; int m_HistoryPingPong; public bool IsSupported() { return SystemInfo.supportedRenderTargetCount >= 2 && SystemInfo.supportsMotionVectors && !RuntimeUtilities.isSinglePassStereoEnabled; } internal DepthTextureMode GetCameraFlags() { return DepthTextureMode.Depth | DepthTextureMode.MotionVectors; } internal void ResetHistory() { m_ResetHistory = true; } Vector2 GenerateRandomOffset() { var offset = new Vector2( HaltonSeq.Get(m_SampleIndex & 1023, 2), HaltonSeq.Get(m_SampleIndex & 1023, 3) ); if (++m_SampleIndex >= k_SampleCount) m_SampleIndex = 0; return offset; } // Adapted heavily from PlayDead's TAA code // https://github.com/playdeadgames/temporal/blob/master/Assets/Scripts/Extensions.cs Matrix4x4 GetPerspectiveProjectionMatrix(Camera camera, Vector2 offset) { float vertical = Mathf.Tan(0.5f * Mathf.Deg2Rad * camera.fieldOfView); float horizontal = vertical * camera.aspect; float near = camera.nearClipPlane; float far = camera.farClipPlane; offset.x *= horizontal / (0.5f * camera.pixelWidth); offset.y *= vertical / (0.5f * camera.pixelHeight); float left = (offset.x - horizontal) * near; float right = (offset.x + horizontal) * near; float top = (offset.y + vertical) * near; float bottom = (offset.y - vertical) * near; var matrix = new Matrix4x4(); matrix[0, 0] = (2f * near) / (right - left); matrix[0, 1] = 0f; matrix[0, 2] = (right + left) / (right - left); matrix[0, 3] = 0f; matrix[1, 0] = 0f; matrix[1, 1] = (2f * near) / (top - bottom); matrix[1, 2] = (top + bottom) / (top - bottom); matrix[1, 3] = 0f; matrix[2, 0] = 0f; matrix[2, 1] = 0f; matrix[2, 2] = -(far + near) / (far - near); matrix[2, 3] = -(2f * far * near) / (far - near); matrix[3, 0] = 0f; matrix[3, 1] = 0f; matrix[3, 2] = -1f; matrix[3, 3] = 0f; return matrix; } Matrix4x4 GetOrthographicProjectionMatrix(Camera camera, Vector2 offset) { float vertical = camera.orthographicSize; float horizontal = vertical * camera.aspect; offset.x *= horizontal / (0.5f * camera.pixelWidth); offset.y *= vertical / (0.5f * camera.pixelHeight); float left = offset.x - horizontal; float right = offset.x + horizontal; float top = offset.y + vertical; float bottom = offset.y - vertical; return Matrix4x4.Ortho(left, right, bottom, top, camera.nearClipPlane, camera.farClipPlane); } public void SetProjectionMatrix(Camera camera) { jitter = GenerateRandomOffset(); jitter *= jitterSpread; camera.nonJitteredProjectionMatrix = camera.projectionMatrix; if (jitteredMatrixFunc != null) { camera.projectionMatrix = jitteredMatrixFunc(camera, jitter); } else { camera.projectionMatrix = camera.orthographic ? GetOrthographicProjectionMatrix(camera, jitter) : GetPerspectiveProjectionMatrix(camera, jitter); } camera.useJitteredProjectionMatrixForTransparentRendering = false; jitter = new Vector2(jitter.x / camera.pixelWidth, jitter.y / camera.pixelHeight); } RenderTexture CheckHistory(int id, PostProcessRenderContext context, PropertySheet sheet) { var rt = m_HistoryTextures[id]; if (m_ResetHistory || rt == null || !rt.IsCreated()) { RenderTexture.ReleaseTemporary(rt); rt = RenderTexture.GetTemporary(context.width, context.height, 0, context.sourceFormat); rt.name = "Temporal Anti-aliasing History"; rt.filterMode = FilterMode.Bilinear; m_HistoryTextures[id] = rt; context.command.BlitFullscreenTriangle(context.source, rt, sheet, (int)Pass.AlphaClear); } else if (rt.width != context.width || rt.height != context.height) { // On size change, simply copy the old history to the new one. This looks better // than completely discarding the history and seeing a few aliased frames. var rt2 = RenderTexture.GetTemporary(context.width, context.height, 0, context.sourceFormat); rt2.name = "Temporal Anti-aliasing History"; rt2.filterMode = FilterMode.Bilinear; m_HistoryTextures[id] = rt2; context.command.BlitFullscreenTriangle(rt, rt2); RenderTexture.ReleaseTemporary(rt); } return m_HistoryTextures[id]; } internal void Render(PostProcessRenderContext context) { var sheet = context.propertySheets.Get(context.resources.shaders.temporalAntialiasing); var cmd = context.command; cmd.BeginSample("TemporalAntialiasing"); int pp = m_HistoryPingPong; var historyRead = CheckHistory(++pp % 2, context, sheet); var historyWrite = CheckHistory(++pp % 2, context, sheet); m_HistoryPingPong = ++pp % 2; const float kMotionAmplification = 100f * 60f; sheet.properties.SetVector(ShaderIDs.Jitter, jitter); sheet.properties.SetFloat(ShaderIDs.SharpenParameters, sharpen); sheet.properties.SetVector(ShaderIDs.FinalBlendParameters, new Vector4(stationaryBlending, motionBlending, kMotionAmplification, 0f)); sheet.properties.SetTexture(ShaderIDs.HistoryTex, historyRead); int pass = context.camera.orthographic ? (int)Pass.SolverNoDilate : (int)Pass.SolverDilate; m_Mrt[0] = context.destination; m_Mrt[1] = historyWrite; cmd.BlitFullscreenTriangle(context.source, m_Mrt, context.source, sheet, pass); cmd.EndSample("TemporalAntialiasing"); m_ResetHistory = false; } internal void Release() { for (int i = 0; i < m_HistoryTextures.Length; i++) { RenderTexture.ReleaseTemporary(m_HistoryTextures[i]); m_HistoryTextures[i] = null; } m_SampleIndex = 0; m_HistoryPingPong = 0; ResetHistory(); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading; using System.Text; using System.Xml; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Monitoring; using OpenSim.Framework.Servers; using log4net; using log4net.Config; using log4net.Appender; using log4net.Core; using log4net.Repository; using Nini.Config; namespace OpenSim.Server.Base { public class ServicesServerBase : ServerBase { // Logger // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // Command line args // protected string[] m_Arguments; public string ConfigDirectory { get; private set; } // Run flag // private bool m_Running = true; // Handle all the automagical stuff // public ServicesServerBase(string prompt, string[] args) : base() { // Save raw arguments m_Arguments = args; // Read command line ArgvConfigSource argvConfig = new ArgvConfigSource(args); argvConfig.AddSwitch("Startup", "console", "c"); argvConfig.AddSwitch("Startup", "logfile", "l"); argvConfig.AddSwitch("Startup", "inifile", "i"); argvConfig.AddSwitch("Startup", "prompt", "p"); argvConfig.AddSwitch("Startup", "logconfig", "g"); // Automagically create the ini file name string fileName = Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location); string iniFile = fileName + ".ini"; string logConfig = null; IConfig startupConfig = argvConfig.Configs["Startup"]; if (startupConfig != null) { // Check if a file name was given on the command line iniFile = startupConfig.GetString("inifile", iniFile); // Check if a prompt was given on the command line prompt = startupConfig.GetString("prompt", prompt); // Check for a Log4Net config file on the command line logConfig =startupConfig.GetString("logconfig", logConfig); } // Find out of the file name is a URI and remote load it if possible. // Load it as a local file otherwise. Uri configUri; try { if (Uri.TryCreate(iniFile, UriKind.Absolute, out configUri) && configUri.Scheme == Uri.UriSchemeHttp) { XmlReader r = XmlReader.Create(iniFile); Config = new XmlConfigSource(r); } else { Config = new IniConfigSource(iniFile); } } catch (Exception e) { System.Console.WriteLine("Error reading from config source. {0}", e.Message); Environment.Exit(1); } // Merge OpSys env vars m_log.Info("[CONFIG]: Loading environment variables for Config"); Util.MergeEnvironmentToConfig(Config); // Merge the configuration from the command line into the loaded file Config.Merge(argvConfig); Config.ReplaceKeyValues(); // Refresh the startupConfig post merge if (Config.Configs["Startup"] != null) { startupConfig = Config.Configs["Startup"]; } ConfigDirectory = startupConfig.GetString("ConfigDirectory", "."); prompt = startupConfig.GetString("Prompt", prompt); // Allow derived classes to load config before the console is opened. ReadConfig(); // Create main console string consoleType = "local"; if (startupConfig != null) consoleType = startupConfig.GetString("console", consoleType); if (consoleType == "basic") { MainConsole.Instance = new CommandConsole(prompt); } else if (consoleType == "rest") { MainConsole.Instance = new RemoteConsole(prompt); ((RemoteConsole)MainConsole.Instance).ReadConfig(Config); } else { MainConsole.Instance = new LocalConsole(prompt, startupConfig); } m_console = MainConsole.Instance; if (logConfig != null) { FileInfo cfg = new FileInfo(logConfig); XmlConfigurator.Configure(cfg); } else { XmlConfigurator.Configure(); } LogEnvironmentInformation(); RegisterCommonAppenders(startupConfig); if (startupConfig.GetString("PIDFile", String.Empty) != String.Empty) { CreatePIDFile(startupConfig.GetString("PIDFile")); } RegisterCommonCommands(); RegisterCommonComponents(Config); // Allow derived classes to perform initialization that // needs to be done after the console has opened Initialise(); } public bool Running { get { return m_Running; } } public virtual int Run() { Watchdog.Enabled = true; MemoryWatchdog.Enabled = true; while (m_Running) { try { MainConsole.Instance.Prompt(); } catch (Exception e) { m_log.ErrorFormat("Command error: {0}", e); } } RemovePIDFile(); return 0; } protected override void ShutdownSpecific() { m_Running = false; m_log.Info("[CONSOLE] Quitting"); base.ShutdownSpecific(); } protected virtual void ReadConfig() { } protected virtual void Initialise() { } } }
#if UNITY_WINRT && !UNITY_EDITOR && !UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using Newtonsoft.Json.Utilities; using System.Globalization; namespace Newtonsoft.Json.Linq { /// <summary> /// Represents a JSON constructor. /// </summary> public class JConstructor : JContainer { private string _name; private readonly List<JToken> _values = new List<JToken>(); /// <summary> /// Gets the container's children tokens. /// </summary> /// <value>The container's children tokens.</value> protected override IList<JToken> ChildrenTokens { get { return _values; } } /// <summary> /// Gets or sets the name of this constructor. /// </summary> /// <value>The constructor name.</value> public string Name { get { return _name; } set { _name = value; } } /// <summary> /// Gets the node type for this <see cref="JToken"/>. /// </summary> /// <value>The type.</value> public override JTokenType Type { get { return JTokenType.Constructor; } } /// <summary> /// Initializes a new instance of the <see cref="JConstructor"/> class. /// </summary> public JConstructor() { } /// <summary> /// Initializes a new instance of the <see cref="JConstructor"/> class from another <see cref="JConstructor"/> object. /// </summary> /// <param name="other">A <see cref="JConstructor"/> object to copy from.</param> public JConstructor(JConstructor other) : base(other) { _name = other.Name; } /// <summary> /// Initializes a new instance of the <see cref="JConstructor"/> class with the specified name and content. /// </summary> /// <param name="name">The constructor name.</param> /// <param name="content">The contents of the constructor.</param> public JConstructor(string name, params object[] content) : this(name, (object)content) { } /// <summary> /// Initializes a new instance of the <see cref="JConstructor"/> class with the specified name and content. /// </summary> /// <param name="name">The constructor name.</param> /// <param name="content">The contents of the constructor.</param> public JConstructor(string name, object content) : this(name) { Add(content); } /// <summary> /// Initializes a new instance of the <see cref="JConstructor"/> class with the specified name. /// </summary> /// <param name="name">The constructor name.</param> public JConstructor(string name) { ValidationUtils.ArgumentNotNullOrEmpty(name, "name"); _name = name; } internal override bool DeepEquals(JToken node) { JConstructor c = node as JConstructor; return (c != null && _name == c.Name && ContentsEqual(c)); } internal override JToken CloneToken() { return new JConstructor(this); } /// <summary> /// Writes this token to a <see cref="JsonWriter"/>. /// </summary> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { writer.WriteStartConstructor(_name); foreach (JToken token in Children()) { token.WriteTo(writer, converters); } writer.WriteEndConstructor(); } /// <summary> /// Gets the <see cref="JToken"/> with the specified key. /// </summary> /// <value>The <see cref="JToken"/> with the specified key.</value> public override JToken this[object key] { get { ValidationUtils.ArgumentNotNull(key, "o"); if (!(key is int)) throw new ArgumentException("Accessed JConstructor values with invalid key value: {0}. Argument position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); return GetItem((int)key); } set { ValidationUtils.ArgumentNotNull(key, "o"); if (!(key is int)) throw new ArgumentException("Set JConstructor values with invalid key value: {0}. Argument position index expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); SetItem((int)key, value); } } internal override int GetDeepHashCode() { return _name.GetHashCode() ^ ContentsHashCode(); } /// <summary> /// Loads an <see cref="JConstructor"/> from a <see cref="JsonReader"/>. /// </summary> /// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JConstructor"/>.</param> /// <returns>A <see cref="JConstructor"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns> public static new JConstructor Load(JsonReader reader) { if (reader.TokenType == JsonToken.None) { if (!reader.Read()) throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader."); } while (reader.TokenType == JsonToken.Comment) { reader.Read(); } if (reader.TokenType != JsonToken.StartConstructor) throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader. Current JsonReader item is not a constructor: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); JConstructor c = new JConstructor((string)reader.Value); c.SetLineInfo(reader as IJsonLineInfo); c.ReadTokenFrom(reader); return c; } } } #endif
using Lucene.Net.Attributes; using Lucene.Net.Documents; using Lucene.Net.Store; using Lucene.Net.Support; using Lucene.Net.Support.Threading; using Lucene.Net.Util; using NUnit.Framework; using System; using System.Threading; using Console = Lucene.Net.Support.SystemConsole; namespace Lucene.Net.Index { /* * 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; [TestFixture] public class TestAtomicUpdate : LuceneTestCase { private abstract class TimedThread : ThreadClass { internal volatile bool Failed; internal int Count; internal static float RUN_TIME_MSEC = AtLeast(500); internal TimedThread[] AllThreads; public abstract void DoWork(); internal TimedThread(TimedThread[] threads) { this.AllThreads = threads; } public override void Run() { long stopTime = Environment.TickCount + (long)RUN_TIME_MSEC; Count = 0; try { do { if (AnyErrors()) { break; } DoWork(); Count++; } while (Environment.TickCount < stopTime); } catch (Exception e) { Console.WriteLine(Thread.CurrentThread.Name + ": exc"); Console.WriteLine(e.StackTrace); Failed = true; } } internal virtual bool AnyErrors() { for (int i = 0; i < AllThreads.Length; i++) { if (AllThreads[i] != null && AllThreads[i].Failed) { return true; } } return false; } } private class IndexerThread : TimedThread { internal IndexWriter Writer; public IndexerThread(IndexWriter writer, TimedThread[] threads) : base(threads) { this.Writer = writer; } public override void DoWork() { // Update all 100 docs... for (int i = 0; i < 100; i++) { Documents.Document d = new Documents.Document(); d.Add(new StringField("id", Convert.ToString(i), Field.Store.YES)); d.Add(new TextField("contents", English.IntToEnglish(i + 10 * Count), Field.Store.NO)); Writer.UpdateDocument(new Term("id", Convert.ToString(i)), d); } } } private class SearcherThread : TimedThread { internal Directory Directory; public SearcherThread(Directory directory, TimedThread[] threads) : base(threads) { this.Directory = directory; } public override void DoWork() { IndexReader r = DirectoryReader.Open(Directory); Assert.AreEqual(100, r.NumDocs); r.Dispose(); } } /* Run one indexer and 2 searchers against single index as stress test. */ public virtual void RunTest(Directory directory) { TimedThread[] threads = new TimedThread[4]; IndexWriterConfig conf = (new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))).SetMaxBufferedDocs(7); ((TieredMergePolicy)conf.MergePolicy).MaxMergeAtOnce = 3; IndexWriter writer = RandomIndexWriter.MockIndexWriter(directory, conf, Random()); // Establish a base index of 100 docs: for (int i = 0; i < 100; i++) { Documents.Document d = new Documents.Document(); d.Add(NewStringField("id", Convert.ToString(i), Field.Store.YES)); d.Add(NewTextField("contents", English.IntToEnglish(i), Field.Store.NO)); if ((i - 1) % 7 == 0) { writer.Commit(); } writer.AddDocument(d); } writer.Commit(); IndexReader r = DirectoryReader.Open(directory); Assert.AreEqual(100, r.NumDocs); r.Dispose(); IndexerThread indexerThread = new IndexerThread(writer, threads); threads[0] = indexerThread; indexerThread.Start(); IndexerThread indexerThread2 = new IndexerThread(writer, threads); threads[1] = indexerThread2; indexerThread2.Start(); SearcherThread searcherThread1 = new SearcherThread(directory, threads); threads[2] = searcherThread1; searcherThread1.Start(); SearcherThread searcherThread2 = new SearcherThread(directory, threads); threads[3] = searcherThread2; searcherThread2.Start(); indexerThread.Join(); indexerThread2.Join(); searcherThread1.Join(); searcherThread2.Join(); writer.Dispose(); Assert.IsTrue(!indexerThread.Failed, "hit unexpected exception in indexer"); Assert.IsTrue(!indexerThread2.Failed, "hit unexpected exception in indexer2"); Assert.IsTrue(!searcherThread1.Failed, "hit unexpected exception in search1"); Assert.IsTrue(!searcherThread2.Failed, "hit unexpected exception in search2"); //System.out.println(" Writer: " + indexerThread.count + " iterations"); //System.out.println("Searcher 1: " + searcherThread1.count + " searchers created"); //System.out.println("Searcher 2: " + searcherThread2.count + " searchers created"); } /* Run above stress test against RAMDirectory and then FSDirectory. */ [Test, LongRunningTest] public virtual void TestAtomicUpdates() { Directory directory; // First in a RAM directory: using (directory = new MockDirectoryWrapper(Random(), new RAMDirectory())) { RunTest(directory); } // Second in an FSDirectory: System.IO.DirectoryInfo dirPath = CreateTempDir("lucene.test.atomic"); using (directory = NewFSDirectory(dirPath)) { RunTest(directory); } System.IO.Directory.Delete(dirPath.FullName, true); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: ContainerFormats.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Akka.Remote.Serialization.Proto.Msg { /// <summary>Holder for reflection information generated from ContainerFormats.proto</summary> internal static partial class ContainerFormatsReflection { #region Descriptor /// <summary>File descriptor for ContainerFormats.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ContainerFormatsReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChZDb250YWluZXJGb3JtYXRzLnByb3RvEiNBa2thLlJlbW90ZS5TZXJpYWxp", "emF0aW9uLlByb3RvLk1zZyKTAQoRU2VsZWN0aW9uRW52ZWxvcGUSPQoHcGF5", "bG9hZBgBIAEoCzIsLkFra2EuUmVtb3RlLlNlcmlhbGl6YXRpb24uUHJvdG8u", "TXNnLlBheWxvYWQSPwoHcGF0dGVybhgCIAMoCzIuLkFra2EuUmVtb3RlLlNl", "cmlhbGl6YXRpb24uUHJvdG8uTXNnLlNlbGVjdGlvbiKzAQoJU2VsZWN0aW9u", "EkgKBHR5cGUYASABKA4yOi5Ba2thLlJlbW90ZS5TZXJpYWxpemF0aW9uLlBy", "b3RvLk1zZy5TZWxlY3Rpb24uUGF0dGVyblR5cGUSDwoHbWF0Y2hlchgCIAEo", "CSJLCgtQYXR0ZXJuVHlwZRINCglOT19QQVRFUk4QABIKCgZQQVJFTlQQARIO", "CgpDSElMRF9OQU1FEAISEQoNQ0hJTERfUEFUVEVSThADIhwKDEFjdG9yUmVm", "RGF0YRIMCgRwYXRoGAEgASgJIk8KC0FkZHJlc3NEYXRhEg4KBnN5c3RlbRgB", "IAEoCRIQCghob3N0bmFtZRgCIAEoCRIMCgRwb3J0GAMgASgNEhAKCHByb3Rv", "Y29sGAQgASgJIkkKB1BheWxvYWQSDwoHbWVzc2FnZRgBIAEoDBIUCgxzZXJp", "YWxpemVySWQYAiABKAUSFwoPbWVzc2FnZU1hbmlmZXN0GAMgASgMIksKCElk", "ZW50aWZ5Ej8KCW1lc3NhZ2VJZBgBIAEoCzIsLkFra2EuUmVtb3RlLlNlcmlh", "bGl6YXRpb24uUHJvdG8uTXNnLlBheWxvYWQiYgoNQWN0b3JJZGVudGl0eRJD", "Cg1jb3JyZWxhdGlvbklkGAEgASgLMiwuQWtrYS5SZW1vdGUuU2VyaWFsaXph", "dGlvbi5Qcm90by5Nc2cuUGF5bG9hZBIMCgRwYXRoGAIgASgJIi0KHlJlbW90", "ZVdhdGNoZXJIZWFydGJlYXRSZXNwb25zZRILCgN1aWQYASABKAQi4QIKDUV4", "Y2VwdGlvbkRhdGESEAoIdHlwZU5hbWUYASABKAkSDwoHbWVzc2FnZRgCIAEo", "CRISCgpzdGFja1RyYWNlGAMgASgJEg4KBnNvdXJjZRgEIAEoCRJKCg5pbm5l", "ckV4Y2VwdGlvbhgFIAEoCzIyLkFra2EuUmVtb3RlLlNlcmlhbGl6YXRpb24u", "UHJvdG8uTXNnLkV4Y2VwdGlvbkRhdGESWgoMY3VzdG9tRmllbGRzGAYgAygL", "MkQuQWtrYS5SZW1vdGUuU2VyaWFsaXphdGlvbi5Qcm90by5Nc2cuRXhjZXB0", "aW9uRGF0YS5DdXN0b21GaWVsZHNFbnRyeRphChFDdXN0b21GaWVsZHNFbnRy", "eRILCgNrZXkYASABKAkSOwoFdmFsdWUYAiABKAsyLC5Ba2thLlJlbW90ZS5T", "ZXJpYWxpemF0aW9uLlByb3RvLk1zZy5QYXlsb2FkOgI4AWIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Remote.Serialization.Proto.Msg.SelectionEnvelope), global::Akka.Remote.Serialization.Proto.Msg.SelectionEnvelope.Parser, new[]{ "Payload", "Pattern" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Remote.Serialization.Proto.Msg.Selection), global::Akka.Remote.Serialization.Proto.Msg.Selection.Parser, new[]{ "Type", "Matcher" }, null, new[]{ typeof(global::Akka.Remote.Serialization.Proto.Msg.Selection.Types.PatternType) }, null), new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Remote.Serialization.Proto.Msg.ActorRefData), global::Akka.Remote.Serialization.Proto.Msg.ActorRefData.Parser, new[]{ "Path" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Remote.Serialization.Proto.Msg.AddressData), global::Akka.Remote.Serialization.Proto.Msg.AddressData.Parser, new[]{ "System", "Hostname", "Port", "Protocol" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Remote.Serialization.Proto.Msg.Payload), global::Akka.Remote.Serialization.Proto.Msg.Payload.Parser, new[]{ "Message", "SerializerId", "MessageManifest" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Remote.Serialization.Proto.Msg.Identify), global::Akka.Remote.Serialization.Proto.Msg.Identify.Parser, new[]{ "MessageId" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Remote.Serialization.Proto.Msg.ActorIdentity), global::Akka.Remote.Serialization.Proto.Msg.ActorIdentity.Parser, new[]{ "CorrelationId", "Path" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Remote.Serialization.Proto.Msg.RemoteWatcherHeartbeatResponse), global::Akka.Remote.Serialization.Proto.Msg.RemoteWatcherHeartbeatResponse.Parser, new[]{ "Uid" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Remote.Serialization.Proto.Msg.ExceptionData), global::Akka.Remote.Serialization.Proto.Msg.ExceptionData.Parser, new[]{ "TypeName", "Message", "StackTrace", "Source", "InnerException", "CustomFields" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, }) })); } #endregion } #region Messages internal sealed partial class SelectionEnvelope : pb::IMessage<SelectionEnvelope> { private static readonly pb::MessageParser<SelectionEnvelope> _parser = new pb::MessageParser<SelectionEnvelope>(() => new SelectionEnvelope()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<SelectionEnvelope> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Akka.Remote.Serialization.Proto.Msg.ContainerFormatsReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SelectionEnvelope() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SelectionEnvelope(SelectionEnvelope other) : this() { Payload = other.payload_ != null ? other.Payload.Clone() : null; pattern_ = other.pattern_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SelectionEnvelope Clone() { return new SelectionEnvelope(this); } /// <summary>Field number for the "payload" field.</summary> public const int PayloadFieldNumber = 1; private global::Akka.Remote.Serialization.Proto.Msg.Payload payload_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Akka.Remote.Serialization.Proto.Msg.Payload Payload { get { return payload_; } set { payload_ = value; } } /// <summary>Field number for the "pattern" field.</summary> public const int PatternFieldNumber = 2; private static readonly pb::FieldCodec<global::Akka.Remote.Serialization.Proto.Msg.Selection> _repeated_pattern_codec = pb::FieldCodec.ForMessage(18, global::Akka.Remote.Serialization.Proto.Msg.Selection.Parser); private readonly pbc::RepeatedField<global::Akka.Remote.Serialization.Proto.Msg.Selection> pattern_ = new pbc::RepeatedField<global::Akka.Remote.Serialization.Proto.Msg.Selection>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Akka.Remote.Serialization.Proto.Msg.Selection> Pattern { get { return pattern_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as SelectionEnvelope); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(SelectionEnvelope other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Payload, other.Payload)) return false; if(!pattern_.Equals(other.pattern_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (payload_ != null) hash ^= Payload.GetHashCode(); hash ^= pattern_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (payload_ != null) { output.WriteRawTag(10); output.WriteMessage(Payload); } pattern_.WriteTo(output, _repeated_pattern_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (payload_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Payload); } size += pattern_.CalculateSize(_repeated_pattern_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(SelectionEnvelope other) { if (other == null) { return; } if (other.payload_ != null) { if (payload_ == null) { payload_ = new global::Akka.Remote.Serialization.Proto.Msg.Payload(); } Payload.MergeFrom(other.Payload); } pattern_.Add(other.pattern_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (payload_ == null) { payload_ = new global::Akka.Remote.Serialization.Proto.Msg.Payload(); } input.ReadMessage(payload_); break; } case 18: { pattern_.AddEntriesFrom(input, _repeated_pattern_codec); break; } } } } } internal sealed partial class Selection : pb::IMessage<Selection> { private static readonly pb::MessageParser<Selection> _parser = new pb::MessageParser<Selection>(() => new Selection()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Selection> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Akka.Remote.Serialization.Proto.Msg.ContainerFormatsReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Selection() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Selection(Selection other) : this() { type_ = other.type_; matcher_ = other.matcher_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Selection Clone() { return new Selection(this); } /// <summary>Field number for the "type" field.</summary> public const int TypeFieldNumber = 1; private global::Akka.Remote.Serialization.Proto.Msg.Selection.Types.PatternType type_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Akka.Remote.Serialization.Proto.Msg.Selection.Types.PatternType Type { get { return type_; } set { type_ = value; } } /// <summary>Field number for the "matcher" field.</summary> public const int MatcherFieldNumber = 2; private string matcher_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Matcher { get { return matcher_; } set { matcher_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Selection); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Selection other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Type != other.Type) return false; if (Matcher != other.Matcher) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Type != 0) hash ^= Type.GetHashCode(); if (Matcher.Length != 0) hash ^= Matcher.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Type != 0) { output.WriteRawTag(8); output.WriteEnum((int) Type); } if (Matcher.Length != 0) { output.WriteRawTag(18); output.WriteString(Matcher); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Type != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type); } if (Matcher.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Matcher); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Selection other) { if (other == null) { return; } if (other.Type != 0) { Type = other.Type; } if (other.Matcher.Length != 0) { Matcher = other.Matcher; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { type_ = (global::Akka.Remote.Serialization.Proto.Msg.Selection.Types.PatternType) input.ReadEnum(); break; } case 18: { Matcher = input.ReadString(); break; } } } } #region Nested types /// <summary>Container for nested types declared in the Selection message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { internal enum PatternType { [pbr::OriginalName("NO_PATERN")] NoPatern = 0, [pbr::OriginalName("PARENT")] Parent = 1, [pbr::OriginalName("CHILD_NAME")] ChildName = 2, [pbr::OriginalName("CHILD_PATTERN")] ChildPattern = 3, } } #endregion } /// <summary> /// Defines a remote ActorRef that "remembers" and uses its original Actor instance on the original node. /// </summary> internal sealed partial class ActorRefData : pb::IMessage<ActorRefData> { private static readonly pb::MessageParser<ActorRefData> _parser = new pb::MessageParser<ActorRefData>(() => new ActorRefData()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ActorRefData> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Akka.Remote.Serialization.Proto.Msg.ContainerFormatsReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ActorRefData() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ActorRefData(ActorRefData other) : this() { path_ = other.path_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ActorRefData Clone() { return new ActorRefData(this); } /// <summary>Field number for the "path" field.</summary> public const int PathFieldNumber = 1; private string path_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Path { get { return path_; } set { path_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ActorRefData); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ActorRefData other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Path != other.Path) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Path.Length != 0) hash ^= Path.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Path.Length != 0) { output.WriteRawTag(10); output.WriteString(Path); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Path.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Path); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ActorRefData other) { if (other == null) { return; } if (other.Path.Length != 0) { Path = other.Path; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Path = input.ReadString(); break; } } } } } /// <summary> /// Defines a remote address. /// </summary> internal sealed partial class AddressData : pb::IMessage<AddressData> { private static readonly pb::MessageParser<AddressData> _parser = new pb::MessageParser<AddressData>(() => new AddressData()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<AddressData> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Akka.Remote.Serialization.Proto.Msg.ContainerFormatsReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AddressData() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AddressData(AddressData other) : this() { system_ = other.system_; hostname_ = other.hostname_; port_ = other.port_; protocol_ = other.protocol_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AddressData Clone() { return new AddressData(this); } /// <summary>Field number for the "system" field.</summary> public const int SystemFieldNumber = 1; private string system_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string System { get { return system_; } set { system_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "hostname" field.</summary> public const int HostnameFieldNumber = 2; private string hostname_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Hostname { get { return hostname_; } set { hostname_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "port" field.</summary> public const int PortFieldNumber = 3; private uint port_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public uint Port { get { return port_; } set { port_ = value; } } /// <summary>Field number for the "protocol" field.</summary> public const int ProtocolFieldNumber = 4; private string protocol_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Protocol { get { return protocol_; } set { protocol_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as AddressData); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(AddressData other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (System != other.System) return false; if (Hostname != other.Hostname) return false; if (Port != other.Port) return false; if (Protocol != other.Protocol) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (System.Length != 0) hash ^= System.GetHashCode(); if (Hostname.Length != 0) hash ^= Hostname.GetHashCode(); if (Port != 0) hash ^= Port.GetHashCode(); if (Protocol.Length != 0) hash ^= Protocol.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (System.Length != 0) { output.WriteRawTag(10); output.WriteString(System); } if (Hostname.Length != 0) { output.WriteRawTag(18); output.WriteString(Hostname); } if (Port != 0) { output.WriteRawTag(24); output.WriteUInt32(Port); } if (Protocol.Length != 0) { output.WriteRawTag(34); output.WriteString(Protocol); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (System.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(System); } if (Hostname.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Hostname); } if (Port != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(Port); } if (Protocol.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Protocol); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(AddressData other) { if (other == null) { return; } if (other.System.Length != 0) { System = other.System; } if (other.Hostname.Length != 0) { Hostname = other.Hostname; } if (other.Port != 0) { Port = other.Port; } if (other.Protocol.Length != 0) { Protocol = other.Protocol; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { System = input.ReadString(); break; } case 18: { Hostname = input.ReadString(); break; } case 24: { Port = input.ReadUInt32(); break; } case 34: { Protocol = input.ReadString(); break; } } } } } /// <summary> /// Defines a payload. /// </summary> internal sealed partial class Payload : pb::IMessage<Payload> { private static readonly pb::MessageParser<Payload> _parser = new pb::MessageParser<Payload>(() => new Payload()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Payload> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Akka.Remote.Serialization.Proto.Msg.ContainerFormatsReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Payload() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Payload(Payload other) : this() { message_ = other.message_; serializerId_ = other.serializerId_; messageManifest_ = other.messageManifest_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Payload Clone() { return new Payload(this); } /// <summary>Field number for the "message" field.</summary> public const int MessageFieldNumber = 1; private pb::ByteString message_ = pb::ByteString.Empty; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString Message { get { return message_; } set { message_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "serializerId" field.</summary> public const int SerializerIdFieldNumber = 2; private int serializerId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int SerializerId { get { return serializerId_; } set { serializerId_ = value; } } /// <summary>Field number for the "messageManifest" field.</summary> public const int MessageManifestFieldNumber = 3; private pb::ByteString messageManifest_ = pb::ByteString.Empty; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString MessageManifest { get { return messageManifest_; } set { messageManifest_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Payload); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Payload other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Message != other.Message) return false; if (SerializerId != other.SerializerId) return false; if (MessageManifest != other.MessageManifest) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Message.Length != 0) hash ^= Message.GetHashCode(); if (SerializerId != 0) hash ^= SerializerId.GetHashCode(); if (MessageManifest.Length != 0) hash ^= MessageManifest.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Message.Length != 0) { output.WriteRawTag(10); output.WriteBytes(Message); } if (SerializerId != 0) { output.WriteRawTag(16); output.WriteInt32(SerializerId); } if (MessageManifest.Length != 0) { output.WriteRawTag(26); output.WriteBytes(MessageManifest); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Message.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(Message); } if (SerializerId != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(SerializerId); } if (MessageManifest.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(MessageManifest); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Payload other) { if (other == null) { return; } if (other.Message.Length != 0) { Message = other.Message; } if (other.SerializerId != 0) { SerializerId = other.SerializerId; } if (other.MessageManifest.Length != 0) { MessageManifest = other.MessageManifest; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Message = input.ReadBytes(); break; } case 16: { SerializerId = input.ReadInt32(); break; } case 26: { MessageManifest = input.ReadBytes(); break; } } } } } internal sealed partial class Identify : pb::IMessage<Identify> { private static readonly pb::MessageParser<Identify> _parser = new pb::MessageParser<Identify>(() => new Identify()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Identify> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Akka.Remote.Serialization.Proto.Msg.ContainerFormatsReflection.Descriptor.MessageTypes[5]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Identify() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Identify(Identify other) : this() { MessageId = other.messageId_ != null ? other.MessageId.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Identify Clone() { return new Identify(this); } /// <summary>Field number for the "messageId" field.</summary> public const int MessageIdFieldNumber = 1; private global::Akka.Remote.Serialization.Proto.Msg.Payload messageId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Akka.Remote.Serialization.Proto.Msg.Payload MessageId { get { return messageId_; } set { messageId_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Identify); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Identify other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(MessageId, other.MessageId)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (messageId_ != null) hash ^= MessageId.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (messageId_ != null) { output.WriteRawTag(10); output.WriteMessage(MessageId); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (messageId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(MessageId); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Identify other) { if (other == null) { return; } if (other.messageId_ != null) { if (messageId_ == null) { messageId_ = new global::Akka.Remote.Serialization.Proto.Msg.Payload(); } MessageId.MergeFrom(other.MessageId); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (messageId_ == null) { messageId_ = new global::Akka.Remote.Serialization.Proto.Msg.Payload(); } input.ReadMessage(messageId_); break; } } } } } internal sealed partial class ActorIdentity : pb::IMessage<ActorIdentity> { private static readonly pb::MessageParser<ActorIdentity> _parser = new pb::MessageParser<ActorIdentity>(() => new ActorIdentity()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ActorIdentity> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Akka.Remote.Serialization.Proto.Msg.ContainerFormatsReflection.Descriptor.MessageTypes[6]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ActorIdentity() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ActorIdentity(ActorIdentity other) : this() { CorrelationId = other.correlationId_ != null ? other.CorrelationId.Clone() : null; path_ = other.path_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ActorIdentity Clone() { return new ActorIdentity(this); } /// <summary>Field number for the "correlationId" field.</summary> public const int CorrelationIdFieldNumber = 1; private global::Akka.Remote.Serialization.Proto.Msg.Payload correlationId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Akka.Remote.Serialization.Proto.Msg.Payload CorrelationId { get { return correlationId_; } set { correlationId_ = value; } } /// <summary>Field number for the "path" field.</summary> public const int PathFieldNumber = 2; private string path_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Path { get { return path_; } set { path_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ActorIdentity); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ActorIdentity other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(CorrelationId, other.CorrelationId)) return false; if (Path != other.Path) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (correlationId_ != null) hash ^= CorrelationId.GetHashCode(); if (Path.Length != 0) hash ^= Path.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (correlationId_ != null) { output.WriteRawTag(10); output.WriteMessage(CorrelationId); } if (Path.Length != 0) { output.WriteRawTag(18); output.WriteString(Path); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (correlationId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(CorrelationId); } if (Path.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Path); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ActorIdentity other) { if (other == null) { return; } if (other.correlationId_ != null) { if (correlationId_ == null) { correlationId_ = new global::Akka.Remote.Serialization.Proto.Msg.Payload(); } CorrelationId.MergeFrom(other.CorrelationId); } if (other.Path.Length != 0) { Path = other.Path; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (correlationId_ == null) { correlationId_ = new global::Akka.Remote.Serialization.Proto.Msg.Payload(); } input.ReadMessage(correlationId_); break; } case 18: { Path = input.ReadString(); break; } } } } } internal sealed partial class RemoteWatcherHeartbeatResponse : pb::IMessage<RemoteWatcherHeartbeatResponse> { private static readonly pb::MessageParser<RemoteWatcherHeartbeatResponse> _parser = new pb::MessageParser<RemoteWatcherHeartbeatResponse>(() => new RemoteWatcherHeartbeatResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<RemoteWatcherHeartbeatResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Akka.Remote.Serialization.Proto.Msg.ContainerFormatsReflection.Descriptor.MessageTypes[7]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RemoteWatcherHeartbeatResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RemoteWatcherHeartbeatResponse(RemoteWatcherHeartbeatResponse other) : this() { uid_ = other.uid_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RemoteWatcherHeartbeatResponse Clone() { return new RemoteWatcherHeartbeatResponse(this); } /// <summary>Field number for the "uid" field.</summary> public const int UidFieldNumber = 1; private ulong uid_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ulong Uid { get { return uid_; } set { uid_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as RemoteWatcherHeartbeatResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(RemoteWatcherHeartbeatResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Uid != other.Uid) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Uid != 0UL) hash ^= Uid.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Uid != 0UL) { output.WriteRawTag(8); output.WriteUInt64(Uid); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Uid != 0UL) { size += 1 + pb::CodedOutputStream.ComputeUInt64Size(Uid); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(RemoteWatcherHeartbeatResponse other) { if (other == null) { return; } if (other.Uid != 0UL) { Uid = other.Uid; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Uid = input.ReadUInt64(); break; } } } } } internal sealed partial class ExceptionData : pb::IMessage<ExceptionData> { private static readonly pb::MessageParser<ExceptionData> _parser = new pb::MessageParser<ExceptionData>(() => new ExceptionData()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ExceptionData> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Akka.Remote.Serialization.Proto.Msg.ContainerFormatsReflection.Descriptor.MessageTypes[8]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ExceptionData() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ExceptionData(ExceptionData other) : this() { typeName_ = other.typeName_; message_ = other.message_; stackTrace_ = other.stackTrace_; source_ = other.source_; InnerException = other.innerException_ != null ? other.InnerException.Clone() : null; customFields_ = other.customFields_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ExceptionData Clone() { return new ExceptionData(this); } /// <summary>Field number for the "typeName" field.</summary> public const int TypeNameFieldNumber = 1; private string typeName_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string TypeName { get { return typeName_; } set { typeName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "message" field.</summary> public const int MessageFieldNumber = 2; private string message_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Message { get { return message_; } set { message_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "stackTrace" field.</summary> public const int StackTraceFieldNumber = 3; private string stackTrace_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string StackTrace { get { return stackTrace_; } set { stackTrace_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "source" field.</summary> public const int SourceFieldNumber = 4; private string source_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Source { get { return source_; } set { source_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "innerException" field.</summary> public const int InnerExceptionFieldNumber = 5; private global::Akka.Remote.Serialization.Proto.Msg.ExceptionData innerException_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Akka.Remote.Serialization.Proto.Msg.ExceptionData InnerException { get { return innerException_; } set { innerException_ = value; } } /// <summary>Field number for the "customFields" field.</summary> public const int CustomFieldsFieldNumber = 6; private static readonly pbc::MapField<string, global::Akka.Remote.Serialization.Proto.Msg.Payload>.Codec _map_customFields_codec = new pbc::MapField<string, global::Akka.Remote.Serialization.Proto.Msg.Payload>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForMessage(18, global::Akka.Remote.Serialization.Proto.Msg.Payload.Parser), 50); private readonly pbc::MapField<string, global::Akka.Remote.Serialization.Proto.Msg.Payload> customFields_ = new pbc::MapField<string, global::Akka.Remote.Serialization.Proto.Msg.Payload>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::MapField<string, global::Akka.Remote.Serialization.Proto.Msg.Payload> CustomFields { get { return customFields_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ExceptionData); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ExceptionData other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (TypeName != other.TypeName) return false; if (Message != other.Message) return false; if (StackTrace != other.StackTrace) return false; if (Source != other.Source) return false; if (!object.Equals(InnerException, other.InnerException)) return false; if (!CustomFields.Equals(other.CustomFields)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (TypeName.Length != 0) hash ^= TypeName.GetHashCode(); if (Message.Length != 0) hash ^= Message.GetHashCode(); if (StackTrace.Length != 0) hash ^= StackTrace.GetHashCode(); if (Source.Length != 0) hash ^= Source.GetHashCode(); if (innerException_ != null) hash ^= InnerException.GetHashCode(); hash ^= CustomFields.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (TypeName.Length != 0) { output.WriteRawTag(10); output.WriteString(TypeName); } if (Message.Length != 0) { output.WriteRawTag(18); output.WriteString(Message); } if (StackTrace.Length != 0) { output.WriteRawTag(26); output.WriteString(StackTrace); } if (Source.Length != 0) { output.WriteRawTag(34); output.WriteString(Source); } if (innerException_ != null) { output.WriteRawTag(42); output.WriteMessage(InnerException); } customFields_.WriteTo(output, _map_customFields_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (TypeName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(TypeName); } if (Message.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Message); } if (StackTrace.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(StackTrace); } if (Source.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Source); } if (innerException_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(InnerException); } size += customFields_.CalculateSize(_map_customFields_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ExceptionData other) { if (other == null) { return; } if (other.TypeName.Length != 0) { TypeName = other.TypeName; } if (other.Message.Length != 0) { Message = other.Message; } if (other.StackTrace.Length != 0) { StackTrace = other.StackTrace; } if (other.Source.Length != 0) { Source = other.Source; } if (other.innerException_ != null) { if (innerException_ == null) { innerException_ = new global::Akka.Remote.Serialization.Proto.Msg.ExceptionData(); } InnerException.MergeFrom(other.InnerException); } customFields_.Add(other.customFields_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { TypeName = input.ReadString(); break; } case 18: { Message = input.ReadString(); break; } case 26: { StackTrace = input.ReadString(); break; } case 34: { Source = input.ReadString(); break; } case 42: { if (innerException_ == null) { innerException_ = new global::Akka.Remote.Serialization.Proto.Msg.ExceptionData(); } input.ReadMessage(innerException_); break; } case 50: { customFields_.AddEntriesFrom(input, _map_customFields_codec); break; } } } } } #endregion } #endregion Designer generated code
public static class GlobalMembersGdimagefilledpolygon3 { #if __cplusplus #endif #define GD_H #define GD_MAJOR_VERSION #define GD_MINOR_VERSION #define GD_RELEASE_VERSION #define GD_EXTRA_VERSION //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdXXX_VERSION_STR(mjr, mnr, rev, ext) mjr "." mnr "." rev ext #define GDXXX_VERSION_STR //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdXXX_STR(s) gd.gdXXX_SSTR(s) #define GDXXX_STR //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdXXX_SSTR(s) #s #define GDXXX_SSTR //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define GD_VERSION_STRING "GD_MAJOR_VERSION" "." "GD_MINOR_VERSION" "." "GD_RELEASE_VERSION" GD_EXTRA_VERSION #define GD_VERSION_STRING #if _WIN32 || CYGWIN || _WIN32_WCE #if BGDWIN32 #if NONDLL #define BGD_EXPORT_DATA_PROT #else #if __GNUC__ #define BGD_EXPORT_DATA_PROT #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_EXPORT_DATA_PROT __declspec(dllexport) #define BGD_EXPORT_DATA_PROT #endif #endif #else #if __GNUC__ #define BGD_EXPORT_DATA_PROT #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_EXPORT_DATA_PROT __declspec(dllimport) #define BGD_EXPORT_DATA_PROT #endif #endif //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_STDCALL __stdcall #define BGD_STDCALL #define BGD_EXPORT_DATA_IMPL #else #if HAVE_VISIBILITY #define BGD_EXPORT_DATA_PROT #define BGD_EXPORT_DATA_IMPL #else #define BGD_EXPORT_DATA_PROT #define BGD_EXPORT_DATA_IMPL #endif #define BGD_STDCALL #endif #if BGD_EXPORT_DATA_PROT_ConditionalDefinition1 #if BGD_STDCALL_ConditionalDefinition1 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt __stdcall #define BGD_DECLARE #elif BGD_STDCALL_ConditionalDefinition2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt #define BGD_DECLARE #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt BGD_STDCALLTangibleTempImmunity #define BGD_DECLARE #endif #elif BGD_EXPORT_DATA_PROT_ConditionalDefinition2 #if BGD_STDCALL_ConditionalDefinition1 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt __stdcall #define BGD_DECLARE #elif BGD_STDCALL_ConditionalDefinition2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt #define BGD_DECLARE #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) rt BGD_STDCALLTangibleTempImmunity #define BGD_DECLARE #endif #elif BGD_EXPORT_DATA_PROT_ConditionalDefinition3 #if BGD_STDCALL_ConditionalDefinition1 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt __stdcall #define BGD_DECLARE #elif BGD_STDCALL_ConditionalDefinition2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt #define BGD_DECLARE #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt BGD_STDCALLTangibleTempImmunity #define BGD_DECLARE #endif #elif BGD_EXPORT_DATA_PROT_ConditionalDefinition4 #if BGD_STDCALL_ConditionalDefinition1 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt __stdcall #define BGD_DECLARE #elif BGD_STDCALL_ConditionalDefinition2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt #define BGD_DECLARE #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt BGD_STDCALLTangibleTempImmunity #define BGD_DECLARE #endif #else #if BGD_STDCALL_ConditionalDefinition1 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt __stdcall #define BGD_DECLARE #elif BGD_STDCALL_ConditionalDefinition2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define BGD_DECLARE (rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt #define BGD_DECLARE #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define Bgd.gd_DECLARE(rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt BGD_STDCALLTangibleTempImmunity #define BGD_DECLARE #endif #endif #if __cplusplus #endif #if __cplusplus #endif #define GD_IO_H #if VMS #endif #if __cplusplus #endif #define gdMaxColors #define gdAlphaMax #define gdAlphaOpaque #define gdAlphaTransparent #define gdRedMax #define gdGreenMax #define gdBlueMax //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColorGetAlpha(c) (((c) & 0x7F000000) >> 24) #define gdTrueColorGetAlpha //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColorGetRed(c) (((c) & 0xFF0000) >> 16) #define gdTrueColorGetRed //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColorGetGreen(c) (((c) & 0x00FF00) >> 8) #define gdTrueColorGetGreen //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColorGetBlue(c) ((c) & 0x0000FF) #define gdTrueColorGetBlue #define gdEffectReplace #define gdEffectAlphaBlend #define gdEffectNormal #define gdEffectOverlay #define GD_TRUE #define GD_FALSE #define GD_EPSILON #define M_PI #define gdDashSize #define gdStyled #define gdBrushed #define gdStyledBrushed #define gdTiled #define gdTransparent #define gdAntiAliased //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gdImageCreatePalette gdImageCreate #define gdImageCreatePalette #define gdFTEX_LINESPACE #define gdFTEX_CHARMAP #define gdFTEX_RESOLUTION #define gdFTEX_DISABLE_KERNING #define gdFTEX_XSHOW #define gdFTEX_FONTPATHNAME #define gdFTEX_FONTCONFIG #define gdFTEX_RETURNFONTPATHNAME #define gdFTEX_Unicode #define gdFTEX_Shift_JIS #define gdFTEX_Big5 #define gdFTEX_Adobe_Custom //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColor(r, g, b) (((r) << 16) + ((g) << 8) + (b)) #define gdTrueColor //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTrueColorAlpha(r, g, b, a) (((a) << 24) + ((r) << 16) + ((g) << 8) + (b)) #define gdTrueColorAlpha #define gdArc //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gdPie gdArc #define gdPie #define gdChord #define gdNoFill #define gdEdged //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageTrueColor(im) ((im)->trueColor) #define gdImageTrueColor //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageSX(im) ((im)->sx) #define gdImageSX //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageSY(im) ((im)->sy) #define gdImageSY //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageColorsTotal(im) ((im)->colorsTotal) #define gdImageColorsTotal //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageRed(im, c) ((im)->trueColor ? (((c) & 0xFF0000) >> 16) : (im)->red[(c)]) #define gdImageRed //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageGreen(im, c) ((im)->trueColor ? (((c) & 0x00FF00) >> 8) : (im)->green[(c)]) #define gdImageGreen //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageBlue(im, c) ((im)->trueColor ? ((c) & 0x0000FF) : (im)->blue[(c)]) #define gdImageBlue //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageAlpha(im, c) ((im)->trueColor ? (((c) & 0x7F000000) >> 24) : (im)->alpha[(c)]) #define gdImageAlpha //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageGetTransparent(im) ((im)->transparent) #define gdImageGetTransparent //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageGetInterlaced(im) ((im)->interlace) #define gdImageGetInterlaced //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImagePalettePixel(im, x, y) (im)->pixels[(y)][(x)] #define gdImagePalettePixel //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageTrueColorPixel(im, x, y) (im)->tpixels[(y)][(x)] #define gdImageTrueColorPixel //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageResolutionX(im) (im)->res_x #define gdImageResolutionX //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdImageResolutionY(im) (im)->res_y #define gdImageResolutionY #define GD2_CHUNKSIZE #define GD2_CHUNKSIZE_MIN #define GD2_CHUNKSIZE_MAX #define GD2_VERS #define GD2_ID #define GD2_FMT_RAW #define GD2_FMT_COMPRESSED #define GD_FLIP_HORINZONTAL #define GD_FLIP_VERTICAL #define GD_FLIP_BOTH #define GD_CMP_IMAGE #define GD_CMP_NUM_COLORS #define GD_CMP_COLOR #define GD_CMP_SIZE_X #define GD_CMP_SIZE_Y #define GD_CMP_TRANSPARENT #define GD_CMP_BACKGROUND #define GD_CMP_INTERLACE #define GD_CMP_TRUECOLOR #define GD_RESOLUTION #if __cplusplus #endif #if __cplusplus #endif #define GDFX_H #if __cplusplus #endif #if __cplusplus #endif #if __cplusplus #endif #define GDHELPERS_H #if ! _WIN32_WCE #else #endif #if _WIN32 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexDeclare(x) CRITICAL_SECTION x #define gdMutexDeclare //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexSetup(x) InitializeCriticalSection(&x) #define gdMutexSetup //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexShutdown(x) DeleteCriticalSection(&x) #define gdMutexShutdown //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexLock(x) EnterCriticalSection(&x) #define gdMutexLock //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexUnlock(x) LeaveCriticalSection(&x) #define gdMutexUnlock #elif HAVE_PTHREAD //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexDeclare(x) pthread_mutex_t x #define gdMutexDeclare //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexSetup(x) pthread_mutex_init(&x, 0) #define gdMutexSetup //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexShutdown(x) pthread_mutex_destroy(&x) #define gdMutexShutdown //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexLock(x) pthread_mutex_lock(&x) #define gdMutexLock //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexUnlock(x) pthread_mutex_unlock(&x) #define gdMutexUnlock #else //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexDeclare(x) #define gdMutexDeclare //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexSetup(x) #define gdMutexSetup //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexShutdown(x) #define gdMutexShutdown //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexLock(x) #define gdMutexLock //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdMutexUnlock(x) #define gdMutexUnlock #endif //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define DPCM2DPI(dpcm) (unsigned int)((dpcm)*2.54 + 0.5) #define DPCM2DPI //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define DPM2DPI(dpm) (unsigned int)((dpm)*0.0254 + 0.5) #define DPM2DPI //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define DPI2DPCM(dpi) (unsigned int)((dpi)/2.54 + 0.5) #define DPI2DPCM //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define DPI2DPM(dpi) (unsigned int)((dpi)/0.0254 + 0.5) #define DPI2DPM #if __cplusplus #endif #define GDTEST_TOP_DIR #define GDTEST_STRING_MAX //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdAssertImageEqualsToFile(ex,ac) gd.gdTestImageCompareToFile(__FILE__,__LINE__,NULL,(ex),(ac)) #define gdAssertImageEqualsToFile //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdAssertImageFileEqualsMsg(ex,ac) gd.gdTestImageCompareFiles(__FILE__,__LINE__,(ms),(ex),(ac)) #define gdAssertImageFileEqualsMsg //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdAssertImageEquals(tc,ex,ac) CuAssertImageEquals_LineMsg((tc),__FILE__,__LINE__,NULL,(ex),(ac)) #define gdAssertImageEquals //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdAssertImageEqualsMsg(tc,ex,ac) CuAssertImageEquals_LineMsg((tc),__FILE__,__LINE__,(ms),(ex),(ac)) #define gdAssertImageEqualsMsg //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTestAssert(cond) _gd.gdTestAssert(__FILE__, __LINE__, "assert failed in <%s:%i>\n", (cond)) #define gdTestAssert //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define gd.gdTestErrorMsg(...) _gd.gdTestErrorMsg(__FILE__, __LINE__, __VA_ARGS__) #define gdTestErrorMsg static int Main() { gdImageStruct im; int white; int black; int r; gdPoint points; im = gd.gdImageCreate(100, 100); if (im == null) Environment.Exit(1); white = gd.gdImageColorAllocate(im, 0xff, 0xff, 0xff); black = gd.gdImageColorAllocate(im, 0, 0, 0); gd.gdImageFilledRectangle(im, 0, 0, 99, 99, white); //C++ TO C# CONVERTER TODO TASK: The memory management function 'calloc' has no equivalent in C#: points = (gdPoint)calloc(3, sizeof(gdPoint)); if (points == null) { gd.gdImageDestroy(im); Environment.Exit(1); } points[0].x = 10; points[0].y = 10; points[1].x = 50; points[1].y = 70; points[2].x = 90; points[2].y = 30; gd.gdImageFilledPolygon(im, points, 3, black); //C++ TO C# CONVERTER TODO TASK: There is no direct equivalent in C# to the following C++ macro: r = GlobalMembersGdtest.gd.gdTestImageCompareToFile(__FILE__, __LINE__, null, (DefineConstants.GDTEST_TOP_DIR "/gdimagefilledpolygon/gdimagefilledpolygon3.png"), (im)); //C++ TO C# CONVERTER TODO TASK: The memory management function 'free' has no equivalent in C#: free(points); gd.gdImageDestroy(im); if (r == 0) Environment.Exit(1); return EXIT_SUCCESS; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.SymbolSearch; using Microsoft.VisualStudio.Shell.Interop; using NuGet.VisualStudio; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Packaging { /// <summary> /// Free threaded wrapper around the NuGet.VisualStudio STA package installer interfaces. /// We want to be able to make queries about packages from any thread. For example, the /// add-nuget-reference feature wants to know what packages a project already has /// references to. NuGet.VisualStudio provides this information, but only in a COM STA /// manner. As we don't want our background work to bounce and block on the UI thread /// we have this helper class which queries the information on the UI thread and caches /// the data so it can be read from the background. /// </summary> [ExportWorkspaceService(typeof(IPackageInstallerService)), Shared] internal partial class PackageInstallerService : AbstractDelayStartedService, IPackageInstallerService, IVsSearchProviderCallback { private readonly object _gate = new object(); private readonly VisualStudioWorkspaceImpl _workspace; private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; // We refer to the package services through proxy types so that we can // delay loading their DLLs until we actually need them. private IPackageServicesProxy _packageServices; private CancellationTokenSource _tokenSource = new CancellationTokenSource(); // We keep track of what types of changes we've seen so we can then determine what to // refresh on the UI thread. If we hear about project changes, we only refresh that // project. If we hear about a solution level change, we'll refresh all projects. private bool _solutionChanged; private HashSet<ProjectId> _changedProjects = new HashSet<ProjectId>(); private readonly ConcurrentDictionary<ProjectId, Dictionary<string, string>> _projectToInstalledPackageAndVersion = new ConcurrentDictionary<ProjectId, Dictionary<string, string>>(); [ImportingConstructor] public PackageInstallerService( VisualStudioWorkspaceImpl workspace, IVsEditorAdaptersFactoryService editorAdaptersFactoryService) : base(workspace, ServiceComponentOnOffOptions.SymbolSearch, AddImportOptions.SuggestForTypesInReferenceAssemblies, AddImportOptions.SuggestForTypesInNuGetPackages) { _workspace = workspace; _editorAdaptersFactoryService = editorAdaptersFactoryService; } public ImmutableArray<PackageSource> PackageSources { get; private set; } = ImmutableArray<PackageSource>.Empty; public event EventHandler PackageSourcesChanged; public bool IsEnabled => _packageServices != null; protected override void EnableService() { // Our service has been enabled. Now load the VS package dlls. var componentModel = _workspace.GetVsService<SComponentModel, IComponentModel>(); var packageInstallerServices = componentModel.GetExtensions<IVsPackageInstallerServices>().FirstOrDefault(); var packageInstaller = componentModel.GetExtensions<IVsPackageInstaller>().FirstOrDefault(); var packageUninstaller = componentModel.GetExtensions<IVsPackageUninstaller>().FirstOrDefault(); var packageSourceProvider = componentModel.GetExtensions<IVsPackageSourceProvider>().FirstOrDefault(); if (packageInstallerServices == null || packageInstaller == null || packageUninstaller == null || packageSourceProvider == null) { return; } _packageServices = new PackageServicesProxy( packageInstallerServices, packageInstaller, packageUninstaller, packageSourceProvider); // Start listening to additional events workspace changes. _workspace.WorkspaceChanged += OnWorkspaceChanged; _packageServices.SourcesChanged += OnSourceProviderSourcesChanged; } protected override void StopWorking() { this.AssertIsForeground(); if (!IsEnabled) { return; } // Stop listening to workspace changes. _workspace.WorkspaceChanged -= OnWorkspaceChanged; _packageServices.SourcesChanged -= OnSourceProviderSourcesChanged; } protected override void StartWorking() { this.AssertIsForeground(); if (!this.IsEnabled) { return; } OnSourceProviderSourcesChanged(this, EventArgs.Empty); } private void OnSourceProviderSourcesChanged(object sender, EventArgs e) { if (!this.IsForeground()) { this.InvokeBelowInputPriority(() => OnSourceProviderSourcesChanged(sender, e)); return; } this.AssertIsForeground(); PackageSources = _packageServices.GetSources(includeUnOfficial: true, includeDisabled: false) .Select(r => new PackageSource(r.Key, r.Value)) .ToImmutableArrayOrEmpty(); PackageSourcesChanged?.Invoke(this, EventArgs.Empty); } public bool TryInstallPackage( Workspace workspace, DocumentId documentId, string source, string packageName, string versionOpt, CancellationToken cancellationToken) { this.AssertIsForeground(); // The 'workspace == _workspace' line is probably not necessary. However, we include // it just to make sure that someone isn't trying to install a package into a workspace // other than the VisualStudioWorkspace. if (workspace == _workspace && _workspace != null && _packageServices != null) { var projectId = documentId.ProjectId; var dte = _workspace.GetVsService<SDTE, EnvDTE.DTE>(); var dteProject = _workspace.TryGetDTEProject(projectId); if (dteProject != null) { var description = string.Format(ServicesVSResources.Install_0, packageName); var document = workspace.CurrentSolution.GetDocument(documentId); var text = document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); var textSnapshot = text.FindCorrespondingEditorTextSnapshot(); var textBuffer = textSnapshot?.TextBuffer; var undoManager = GetUndoManager(textBuffer); return TryInstallAndAddUndoAction(source, packageName, versionOpt, dte, dteProject, undoManager); } } return false; } private bool TryInstallPackage( string source, string packageName, string versionOpt, EnvDTE.DTE dte, EnvDTE.Project dteProject) { try { if (!_packageServices.IsPackageInstalled(dteProject, packageName)) { dte.StatusBar.Text = string.Format(ServicesVSResources.Installing_0, packageName); _packageServices.InstallPackage(source, dteProject, packageName, versionOpt, ignoreDependencies: false); var installedVersion = GetInstalledVersion(packageName, dteProject); dte.StatusBar.Text = string.Format(ServicesVSResources.Installing_0_completed, GetStatusBarText(packageName, installedVersion)); return true; } // fall through. } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { dte.StatusBar.Text = string.Format(ServicesVSResources.Package_install_failed_colon_0, e.Message); var notificationService = _workspace.Services.GetService<INotificationService>(); notificationService?.SendNotification( string.Format(ServicesVSResources.Installing_0_failed_Additional_information_colon_1, packageName, e.Message), severity: NotificationSeverity.Error); // fall through. } return false; } private static string GetStatusBarText(string packageName, string installedVersion) { return installedVersion == null ? packageName : $"{packageName} - {installedVersion}"; } private bool TryUninstallPackage( string packageName, EnvDTE.DTE dte, EnvDTE.Project dteProject) { this.AssertIsForeground(); try { if (_packageServices.IsPackageInstalled(dteProject, packageName)) { dte.StatusBar.Text = string.Format(ServicesVSResources.Uninstalling_0, packageName); var installedVersion = GetInstalledVersion(packageName, dteProject); _packageServices.UninstallPackage(dteProject, packageName, removeDependencies: true); dte.StatusBar.Text = string.Format(ServicesVSResources.Uninstalling_0_completed, GetStatusBarText(packageName, installedVersion)); return true; } // fall through. } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { dte.StatusBar.Text = string.Format(ServicesVSResources.Package_uninstall_failed_colon_0, e.Message); var notificationService = _workspace.Services.GetService<INotificationService>(); notificationService?.SendNotification( string.Format(ServicesVSResources.Uninstalling_0_failed_Additional_information_colon_1, packageName, e.Message), severity: NotificationSeverity.Error); // fall through. } return false; } private string GetInstalledVersion(string packageName, EnvDTE.Project dteProject) { this.AssertIsForeground(); try { var installedPackages = _packageServices.GetInstalledPackages(dteProject); var metadata = installedPackages.FirstOrDefault(m => m.Id == packageName); return metadata?.VersionString; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return null; } } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e) { ThisCanBeCalledOnAnyThread(); bool localSolutionChanged = false; ProjectId localChangedProject = null; switch (e.Kind) { default: // Nothing to do for any other events. return; case WorkspaceChangeKind.ProjectAdded: case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.ProjectReloaded: case WorkspaceChangeKind.ProjectRemoved: localChangedProject = e.ProjectId; break; case WorkspaceChangeKind.SolutionAdded: case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionCleared: case WorkspaceChangeKind.SolutionReloaded: case WorkspaceChangeKind.SolutionRemoved: localSolutionChanged = true; break; } lock (_gate) { // Augment the data that the foreground thread will process. _solutionChanged |= localSolutionChanged; if (localChangedProject != null) { _changedProjects.Add(localChangedProject); } // Now cancel any inflight work that is processing the data. _tokenSource.Cancel(); _tokenSource = new CancellationTokenSource(); // And enqueue a new job to process things. Wait one second before starting. // That way if we get a flurry of events we'll end up processing them after // they've all come in. var cancellationToken = _tokenSource.Token; Task.Delay(TimeSpan.FromSeconds(1), cancellationToken) .ContinueWith(_ => ProcessBatchedChangesOnForeground(cancellationToken), cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion, this.ForegroundTaskScheduler); } } private void ProcessBatchedChangesOnForeground(CancellationToken cancellationToken) { this.AssertIsForeground(); // If we've been asked to stop, then there's no point proceeding. if (cancellationToken.IsCancellationRequested) { return; } // If we've been disconnected, then there's no point proceeding. if (_workspace == null || _packageServices == null) { return; } // Get a project to process. var solution = _workspace.CurrentSolution; var projectId = DequeueNextProject(solution); if (projectId == null) { // No project to process, nothing to do. return; } // Process this single project. ProcessProjectChange(solution, projectId); // After processing this single project, yield so the foreground thread // can do more work. Then go and loop again so we can process the // rest of the projects. Task.Factory.SafeStartNew( () => ProcessBatchedChangesOnForeground(cancellationToken), cancellationToken, ForegroundTaskScheduler); } private ProjectId DequeueNextProject(Solution solution) { this.AssertIsForeground(); lock (_gate) { // If we detected a solution change, then we need to process all projects. // This includes all the projects that we already know about, as well as // all the projects in the current workspace solution. if (_solutionChanged) { _changedProjects.AddRange(solution.ProjectIds); _changedProjects.AddRange(_projectToInstalledPackageAndVersion.Keys); } _solutionChanged = false; // Remove and return the first project in the list. var projectId = _changedProjects.FirstOrDefault(); _changedProjects.Remove(projectId); return projectId; } } private void ProcessProjectChange(Solution solution, ProjectId projectId) { this.AssertIsForeground(); // Remove anything we have associated with this project. Dictionary<string, string> installedPackages; _projectToInstalledPackageAndVersion.TryRemove(projectId, out installedPackages); if (!solution.ContainsProject(projectId)) { // Project was removed. Nothing needs to be done. return; } // Project was changed in some way. Let's go find the set of installed packages for it. var dteProject = _workspace.TryGetDTEProject(projectId); if (dteProject == null) { // Don't have a DTE project for this project ID. not something we can query nuget for. return; } installedPackages = new Dictionary<string, string>(); // Calling into nuget. Assume they may fail for any reason. try { var installedPackageMetadata = _packageServices.GetInstalledPackages(dteProject); installedPackages.AddRange(installedPackageMetadata.Select(m => new KeyValuePair<string, string>(m.Id, m.VersionString))); } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { } _projectToInstalledPackageAndVersion.AddOrUpdate(projectId, installedPackages, (_1, _2) => installedPackages); } public bool IsInstalled(Workspace workspace, ProjectId projectId, string packageName) { ThisCanBeCalledOnAnyThread(); Dictionary<string, string> installedPackages; return _projectToInstalledPackageAndVersion.TryGetValue(projectId, out installedPackages) && installedPackages.ContainsKey(packageName); } public IEnumerable<string> GetInstalledVersions(string packageName) { ThisCanBeCalledOnAnyThread(); var installedVersions = new HashSet<string>(); foreach (var installedPackages in _projectToInstalledPackageAndVersion.Values) { string version = null; if (installedPackages?.TryGetValue(packageName, out version) == true && version != null) { installedVersions.Add(version); } } // Order the versions with a weak heuristic so that 'newer' versions come first. // Essentially, we try to break the version on dots, and then we use a LogicalComparer // to try to more naturally order the things we see between the dots. var versionsAndSplits = installedVersions.Select(v => new { Version = v, Split = v.Split('.') }).ToList(); versionsAndSplits.Sort((v1, v2) => { var diff = CompareSplit(v1.Split, v2.Split); return diff != 0 ? diff : -v1.Version.CompareTo(v2.Version); }); return versionsAndSplits.Select(v => v.Version).ToList(); } private int CompareSplit(string[] split1, string[] split2) { ThisCanBeCalledOnAnyThread(); for (int i = 0, n = Math.Min(split1.Length, split2.Length); i < n; i++) { // Prefer things that look larger. i.e. 7 should come before 6. // Use a logical string comparer so that 10 is understood to be // greater than 3. var diff = -LogicalStringComparer.Instance.Compare(split1[i], split2[i]); if (diff != 0) { return diff; } } // Choose the one with more parts. return split2.Length - split1.Length; } public IEnumerable<Project> GetProjectsWithInstalledPackage(Solution solution, string packageName, string version) { ThisCanBeCalledOnAnyThread(); var result = new List<Project>(); foreach (var kvp in this._projectToInstalledPackageAndVersion) { var installedPackageAndVersion = kvp.Value; if (installedPackageAndVersion != null) { string installedVersion; if (installedPackageAndVersion.TryGetValue(packageName, out installedVersion) && installedVersion == version) { var project = solution.GetProject(kvp.Key); if (project != null) { result.Add(project); } } } } return result; } public void ShowManagePackagesDialog(string packageName) { this.AssertIsForeground(); var shell = _workspace.GetVsService<SVsShell, IVsShell>(); if (shell == null) { return; } IVsPackage nugetPackage; var nugetGuid = new Guid("5fcc8577-4feb-4d04-ad72-d6c629b083cc"); shell.LoadPackage(ref nugetGuid, out nugetPackage); if (nugetPackage == null) { return; } // We're able to launch the package manager (with an item in its search box) by // using the IVsSearchProvider API that the nuget package exposes. // // We get that interface for it and then pass it a SearchQuery that effectively // wraps the package name we're looking for. The NuGet package will then read // out that string and populate their search box with it. var extensionProvider = (IVsPackageExtensionProvider)nugetPackage; var extensionGuid = new Guid("042C2B4B-C7F7-49DB-B7A2-402EB8DC7892"); var emptyGuid = Guid.Empty; var searchProvider = (IVsSearchProvider)extensionProvider.CreateExtensionInstance(ref emptyGuid, ref extensionGuid); var task = searchProvider.CreateSearch(dwCookie: 1, pSearchQuery: new SearchQuery(packageName), pSearchCallback: this); task.Start(); } public void ReportProgress(IVsSearchTask pTask, uint dwProgress, uint dwMaxProgress) { } public void ReportComplete(IVsSearchTask pTask, uint dwResultsFound) { } public void ReportResult(IVsSearchTask pTask, IVsSearchItemResult pSearchItemResult) { pSearchItemResult.InvokeAction(); } public void ReportResults(IVsSearchTask pTask, uint dwResults, IVsSearchItemResult[] pSearchItemResults) { } private class SearchQuery : IVsSearchQuery { public SearchQuery(string packageName) { this.SearchString = packageName; } public string SearchString { get; } public uint ParseError => 0; public uint GetTokens(uint dwMaxTokens, IVsSearchToken[] rgpSearchTokens) { return 0; } } private class PackageServicesProxy : IPackageServicesProxy { private readonly IVsPackageInstaller _packageInstaller; private readonly IVsPackageInstallerServices _packageInstallerServices; private readonly IVsPackageSourceProvider _packageSourceProvider; private readonly IVsPackageUninstaller _packageUninstaller; public PackageServicesProxy(IVsPackageInstallerServices packageInstallerServices, IVsPackageInstaller packageInstaller, IVsPackageUninstaller packageUninstaller, IVsPackageSourceProvider packageSourceProvider) { _packageInstallerServices = packageInstallerServices; _packageInstaller = packageInstaller; _packageUninstaller = packageUninstaller; _packageSourceProvider = packageSourceProvider; } public IEnumerable<PackageMetadata> GetInstalledPackages(EnvDTE.Project project) { return _packageInstallerServices.GetInstalledPackages(project) .Select(m => new PackageMetadata(m.Id, m.VersionString)) .ToList(); } public bool IsPackageInstalled(EnvDTE.Project project, string id) { return _packageInstallerServices.IsPackageInstalled(project, id); } public void InstallPackage(string source, EnvDTE.Project project, string packageId, string version, bool ignoreDependencies) { _packageInstaller.InstallPackage(source, project, packageId, version, ignoreDependencies); } public event EventHandler SourcesChanged { add { _packageSourceProvider.SourcesChanged += value; } remove { _packageSourceProvider.SourcesChanged -= value; } } public IEnumerable<KeyValuePair<string, string>> GetSources(bool includeUnOfficial, bool includeDisabled) { return _packageSourceProvider.GetSources(includeUnOfficial, includeDisabled); } public void UninstallPackage(EnvDTE.Project project, string packageId, bool removeDependencies) { _packageUninstaller.UninstallPackage(project, packageId, removeDependencies); } } } }
using System; using System.Collections.Generic; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using AGG; using AGG.Image; using AGG.VertexSource; using AGG.Transform; using AGG.UI; using Gaming.Math; using Gaming.Game; using Gaming.Graphics; namespace CTFA { public class PlayfieldView : GUIWidget { internal class PlayerView { rect_d screenWindow; public PlayerView(rect_d inScreenWindow) { screenWindow = inScreenWindow; } public void SetRendererPreDraw(ImageBuffer background, RendererBase rendererToDrawWith, Player playerToCenterOn) { rendererToDrawWith.PushTransform(); Vector2D windowCenter = new Vector2D(screenWindow.Left + (screenWindow.Right - screenWindow.Left) / 2, screenWindow.Bottom + (screenWindow.Top - screenWindow.Bottom) / 2); Vector2D playerPos = playerToCenterOn.Position; Vector2D playfieldOffset = windowCenter - playerPos; if (playfieldOffset.x > screenWindow.Left) { playfieldOffset.x = screenWindow.Left; } if (playfieldOffset.x < -background.Width() + screenWindow.Right) { playfieldOffset.x = -background.Width() + screenWindow.Right; } if (playfieldOffset.y > screenWindow.Bottom) { playfieldOffset.y = screenWindow.Bottom; } if (playfieldOffset.y < -background.Height() + screenWindow.Top) { playfieldOffset.y = -background.Height() + screenWindow.Top; } Affine translation = Affine.NewTranslation(playfieldOffset); rendererToDrawWith.SetTransform(rendererToDrawWith.GetTransform() * translation); rendererToDrawWith.SetClippingRect(screenWindow); } public void SetRendererPostDraw(RendererBase rendererToDrawWith) { rendererToDrawWith.SetClippingRect(new rect_d(0, 0, 800, 600)); rendererToDrawWith.PopTransform(); } } private ImageSequence backgroundImageSequence; private ImageBuffer backgroundImage; Playfield playfield; const int numPlayers = 4; PlayerView[] playerViews = new PlayerView[numPlayers]; public delegate void MenuEventHandler(GUIWidget button); public event MenuEventHandler Menu; public PlayfieldView(rect_d bounds) { Bounds = bounds; backgroundImageSequence = (ImageSequence)DataAssetCache.Instance.GetAsset(typeof(ImageSequence), "Map1Background"); backgroundImage = backgroundImageSequence.GetImageByIndex(0); ImageSequence menuButtonSequence = (ImageSequence)DataAssetCache.Instance.GetAsset(typeof(ImageSequence), "MenuButtonFromGame"); ButtonWidget menuButton = new ButtonWidget(400, 12, new ThreeImageButtonView(menuButtonSequence.GetImageByIndex(0), menuButtonSequence.GetImageByIndex(1), menuButtonSequence.GetImageByIndex(2))); AddChild(menuButton); menuButton.ButtonClick += new ButtonWidget.ButtonEventHandler(EscapeMenu); playerViews[0] = new PlayerView(new rect_d(400, 300, 800, 600)); playerViews[1] = new PlayerView(new rect_d(400, 0, 800, 300)); playerViews[2] = new PlayerView(new rect_d(0, 300, 400, 600)); playerViews[3] = new PlayerView(new rect_d(0, 0, 400, 300)); } public ImageBuffer BackgroundImage { get { return backgroundImage; } } private void EscapeMenu(object sender, MouseEventArgs mouseEvent) { if (Menu != null) { Menu(this); } } internal void StartNewGame() { Focus(); playfield = new Playfield(); playfield.StartNewGame(); } bool haveDrawnWalls = false; public override void OnDraw(RendererBase rendererToDrawWith) { ImageBuffer levelMap = playfield.LevelMap; int offset; byte[] buffer = levelMap.GetBuffer(out offset); if (!haveDrawnWalls) { RendererBase backgroundRenderer = BackgroundImage.NewRenderer(); rect_i boundsI = BackgroundImage.GetBoundingRect(); rect_d bounds = new rect_d(boundsI.Left, boundsI.Bottom, boundsI.Right, boundsI.Top); backgroundRenderer.SetClippingRect(bounds); ImageSequence wallTileSequence = (ImageSequence)DataAssetCache.Instance.GetAsset(typeof(ImageSequence), "WallTile"); for (int y = 0; y < levelMap.Height(); y++) { for (int x = 0; x < levelMap.Width(); x++) { if (buffer[levelMap.GetBufferOffsetXY(x, y)] == 0) { int index = 0; // what type of wall if (x < levelMap.Width() -1 && buffer[levelMap.GetBufferOffsetXY(x + 1, y + 0)] == 0) { index |= 8; } if (y < levelMap.Height() -1 && buffer[levelMap.GetBufferOffsetXY(x + 0, y + 1)] == 0) { index |= 4; } if (x > 0 && buffer[levelMap.GetBufferOffsetXY(x - 1, y + 0)] == 0) { index |= 2; } if (y > 0 && buffer[levelMap.GetBufferOffsetXY(x + 0, y - 1)] == 0) { index |= 1; } backgroundRenderer.Render(wallTileSequence.GetImageByIndex(index), x * 16, y * 16); } } } haveDrawnWalls = true; } //for (int i = 0; i < 1; i++) for (int i = 0; i < numPlayers; i++) { playerViews[i].SetRendererPreDraw(BackgroundImage, rendererToDrawWith, playfield.PlayerList[i]); rendererToDrawWith.Render(BackgroundImage, 0, 0); foreach (SequenceEntity aSequenceEntity in playfield.SequenceEntityList) { aSequenceEntity.Draw(rendererToDrawWith); } foreach (Player aPlayer in playfield.PlayerList) { aPlayer.Draw(rendererToDrawWith); } playfield.sword.Draw(rendererToDrawWith); playfield.key.Draw(rendererToDrawWith); playfield.shield.Draw(rendererToDrawWith); playerViews[i].SetRendererPostDraw(rendererToDrawWith); } ImageSequence hud = (ImageSequence)DataAssetCache.Instance.GetAsset(typeof(ImageSequence), (playfield.PlayerList.Count).ToString() + "PlayerHUD"); rendererToDrawWith.Render(hud.GetImageByIndex(0), 400, 300); foreach (Player aPlayer in playfield.PlayerList) { aPlayer.DrawScore(rendererToDrawWith); } rendererToDrawWith.Line(0.5, 300.5, 800.5, 300.5, new RGBA_Bytes(255, 20, 20)); rendererToDrawWith.Line(400.5, 0.5, 400.5, 600.5, new RGBA_Bytes(255, 20, 20)); base.OnDraw(rendererToDrawWith); } public override void OnKeyDown(AGG.UI.KeyEventArgs keyEvent) { foreach (Player aPlayer in playfield.PlayerList) { aPlayer.KeyDown(keyEvent); } if (keyEvent.Control && keyEvent.KeyCode == Keys.S) { playfield.SaveXML("TestSave"); } base.OnKeyDown(keyEvent); } public override void OnKeyUp(AGG.UI.KeyEventArgs keyEvent) { foreach (Player aPlayer in playfield.PlayerList) { aPlayer.KeyUp(keyEvent); } base.OnKeyUp(keyEvent); } public void OnUpdate(double NumSecondsPassed) { playfield.Update(NumSecondsPassed); } } }
// 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.Generic; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.MethodInfos; using Internal.Reflection.Core; using Internal.Reflection.Core.Execution; namespace System.Reflection.Runtime.TypeInfos { // // The runtime's implementation of TypeInfo's for array types. // internal sealed partial class RuntimeArrayTypeInfo : RuntimeHasElementTypeInfo { private RuntimeArrayTypeInfo(UnificationKey key, bool multiDim, int rank) : base(key) { Debug.Assert(multiDim || rank == 1); _multiDim = multiDim; _rank = rank; } public sealed override int GetArrayRank() { return _rank; } protected sealed override bool IsArrayImpl() => true; public sealed override bool IsSZArray => !_multiDim; public sealed override bool IsVariableBoundArray => _multiDim; protected sealed override bool IsByRefImpl() => false; protected sealed override bool IsPointerImpl() => false; protected sealed override TypeAttributes GetAttributeFlagsImpl() { return TypeAttributes.AutoLayout | TypeAttributes.AnsiClass | TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Serializable; } internal sealed override IEnumerable<RuntimeConstructorInfo> SyntheticConstructors { get { bool multiDim = this.IsVariableBoundArray; int rank = this.GetArrayRank(); RuntimeTypeInfo arrayType = this; RuntimeTypeInfo countType = CommonRuntimeTypes.Int32.CastToRuntimeTypeInfo(); { RuntimeTypeInfo[] ctorParameters = new RuntimeTypeInfo[rank]; for (int i = 0; i < rank; i++) ctorParameters[i] = countType; yield return RuntimeSyntheticConstructorInfo.GetRuntimeSyntheticConstructorInfo( SyntheticMethodId.ArrayCtor, arrayType, ctorParameters, InvokerOptions.AllowNullThis | InvokerOptions.DontWrapException, delegate (Object _this, Object[] args) { if (rank == 1) { // Legacy: This seems really wrong in the rank1-multidim case (as it's a case of a synthetic constructor that's declared on T[*] returning an instance of T[]) // This is how the desktop behaves, however. int count = (int)(args[0]); RuntimeTypeInfo vectorType; if (multiDim) { vectorType = arrayType.InternalRuntimeElementType.GetArrayType(); } else { vectorType = arrayType; } return ReflectionCoreExecution.ExecutionEnvironment.NewArray(vectorType.TypeHandle, count); } else { int[] lengths = new int[rank]; for (int i = 0; i < rank; i++) { lengths[i] = (int)(args[i]); } return ReflectionCoreExecution.ExecutionEnvironment.NewMultiDimArray(arrayType.TypeHandle, lengths, null); } } ); } if (!multiDim) { // // Jagged arrays also expose constructors that take multiple indices and construct a jagged matrix. For example, // // String[][][][] // // also exposes: // // .ctor(int32, int32) // .ctor(int32, int32, int32) // .ctor(int32, int32, int32, int32) // int parameterCount = 2; RuntimeTypeInfo elementType = this.InternalRuntimeElementType; while (elementType.IsArray && elementType.GetArrayRank() == 1) { RuntimeTypeInfo[] ctorParameters = new RuntimeTypeInfo[parameterCount]; for (int i = 0; i < parameterCount; i++) ctorParameters[i] = countType; yield return RuntimeSyntheticConstructorInfo.GetRuntimeSyntheticConstructorInfo( SyntheticMethodId.ArrayCtorJagged + parameterCount, arrayType, ctorParameters, InvokerOptions.AllowNullThis | InvokerOptions.DontWrapException, delegate (Object _this, Object[] args) { int[] lengths = new int[args.Length]; for (int i = 0; i < args.Length; i++) { lengths[i] = (int)(args[i]); } Array jaggedArray = CreateJaggedArray(arrayType, lengths, 0); return jaggedArray; } ); parameterCount++; elementType = elementType.InternalRuntimeElementType; } } if (multiDim) { RuntimeTypeInfo[] ctorParameters = new RuntimeTypeInfo[rank * 2]; for (int i = 0; i < rank * 2; i++) ctorParameters[i] = countType; yield return RuntimeSyntheticConstructorInfo.GetRuntimeSyntheticConstructorInfo( SyntheticMethodId.ArrayMultiDimCtor, arrayType, ctorParameters, InvokerOptions.AllowNullThis | InvokerOptions.DontWrapException, delegate (Object _this, Object[] args) { int[] lengths = new int[rank]; int[] lowerBounds = new int[rank]; for (int i = 0; i < rank; i++) { lowerBounds[i] = (int)(args[i * 2]); lengths[i] = (int)(args[i * 2 + 1]); } return ReflectionCoreExecution.ExecutionEnvironment.NewMultiDimArray(arrayType.TypeHandle, lengths, lowerBounds); } ); } } } internal sealed override IEnumerable<RuntimeMethodInfo> SyntheticMethods { get { int rank = this.GetArrayRank(); RuntimeTypeInfo indexType = CommonRuntimeTypes.Int32.CastToRuntimeTypeInfo(); RuntimeTypeInfo arrayType = this; RuntimeTypeInfo elementType = arrayType.InternalRuntimeElementType; RuntimeTypeInfo voidType = CommonRuntimeTypes.Void.CastToRuntimeTypeInfo(); { RuntimeTypeInfo[] getParameters = new RuntimeTypeInfo[rank]; for (int i = 0; i < rank; i++) getParameters[i] = indexType; yield return RuntimeSyntheticMethodInfo.GetRuntimeSyntheticMethodInfo( SyntheticMethodId.ArrayGet, "Get", arrayType, getParameters, elementType, InvokerOptions.None, delegate (Object _this, Object[] args) { Array array = (Array)_this; int[] indices = new int[rank]; for (int i = 0; i < rank; i++) indices[i] = (int)(args[i]); return array.GetValue(indices); } ); } { RuntimeTypeInfo[] setParameters = new RuntimeTypeInfo[rank + 1]; for (int i = 0; i < rank; i++) setParameters[i] = indexType; setParameters[rank] = elementType; yield return RuntimeSyntheticMethodInfo.GetRuntimeSyntheticMethodInfo( SyntheticMethodId.ArraySet, "Set", arrayType, setParameters, voidType, InvokerOptions.None, delegate (Object _this, Object[] args) { Array array = (Array)_this; int[] indices = new int[rank]; for (int i = 0; i < rank; i++) indices[i] = (int)(args[i]); Object value = args[rank]; array.SetValue(value, indices); return null; } ); } { RuntimeTypeInfo[] addressParameters = new RuntimeTypeInfo[rank]; for (int i = 0; i < rank; i++) addressParameters[i] = indexType; yield return RuntimeSyntheticMethodInfo.GetRuntimeSyntheticMethodInfo( SyntheticMethodId.ArrayAddress, "Address", arrayType, addressParameters, elementType.GetByRefType(), InvokerOptions.None, delegate (Object _this, Object[] args) { throw new NotSupportedException(); } ); } } } // // Returns the base type as a typeDef, Ref, or Spec. Default behavior is to QTypeDefRefOrSpec.Null, which causes BaseType to return null. // internal sealed override QTypeDefRefOrSpec TypeRefDefOrSpecForBaseType { get { return TypeDefInfoProjectionForArrays.TypeRefDefOrSpecForBaseType; } } // // Returns the *directly implemented* interfaces as typedefs, specs or refs. ImplementedInterfaces will take care of the transitive closure and // insertion of the TypeContext. // internal sealed override QTypeDefRefOrSpec[] TypeRefDefOrSpecsForDirectlyImplementedInterfaces { get { if (this.IsVariableBoundArray) return Array.Empty<QTypeDefRefOrSpec>(); else return TypeDefInfoProjectionForArrays.TypeRefDefOrSpecsForDirectlyImplementedInterfaces; } } // // Returns the generic parameter substitutions to use when enumerating declared members, base class and implemented interfaces. // internal sealed override TypeContext TypeContext { get { return new TypeContext(new RuntimeTypeInfo[] { this.InternalRuntimeElementType }, null); } } protected sealed override string Suffix { get { if (!_multiDim) return "[]"; else if (_rank == 1) return "[*]"; else return "[" + new string(',', _rank - 1) + "]"; } } // // Arrays don't have a true typedef behind them but for the purpose of reporting base classes and interfaces, we can create a pretender. // private RuntimeTypeInfo TypeDefInfoProjectionForArrays { get { RuntimeTypeHandle projectionTypeHandleForArrays = ReflectionCoreExecution.ExecutionEnvironment.ProjectionTypeForArrays; RuntimeTypeInfo projectionRuntimeTypeForArrays = projectionTypeHandleForArrays.GetTypeForRuntimeTypeHandle(); return projectionRuntimeTypeForArrays; } } // // Helper for jagged array constructors. // private Array CreateJaggedArray(RuntimeTypeInfo arrayType, int[] lengths, int index) { int length = lengths[index]; Array jaggedArray = ReflectionCoreExecution.ExecutionEnvironment.NewArray(arrayType.TypeHandle, length); if (index != lengths.Length - 1) { for (int i = 0; i < length; i++) { Array subArray = CreateJaggedArray(arrayType.InternalRuntimeElementType, lengths, index + 1); jaggedArray.SetValue(subArray, i); } } return jaggedArray; } private readonly int _rank; private readonly bool _multiDim; } }
//----------------------------------------------------------------------- // <copyright file="VB6.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright> //----------------------------------------------------------------------- namespace MSBuild.ExtensionPack.VisualStudio { using System; using System.Diagnostics; using System.Globalization; using System.IO; using Microsoft.Build.Framework; using MSBuild.ExtensionPack.VisualStudio.Extended; /// <summary> /// <b>Valid TaskActions are:</b> /// <para><i>Build</i> (<b>Required: </b> Projects <b>Optional: </b>VB6Path, StopOnError)</para> /// <para><b>Remote Execution Support:</b> NA</para> /// <para/> /// </summary> /// <example> /// <code lang="xml"><![CDATA[ /// <Project ToolsVersion="3.5" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> /// <PropertyGroup> /// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath> /// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath> /// </PropertyGroup> /// <Import Project="$(TPath)"/> /// <ItemGroup> /// <ProjectsToBuild Include="C:\MyVB6Project.vbp"> /// <OutDir>c:\output</OutDir> /// <!-- Note the special use of ChgPropVBP metadata to change project properties at Build Time --> /// <ChgPropVBP>RevisionVer=4;CompatibleMode="0"</ChgPropVBP> /// </ProjectsToBuild> /// <ProjectsToBuild Include="C:\MyVB6Project2.vbp"/> /// </ItemGroup> /// <Target Name="Default"> /// <!-- Build a collection of VB6 projects --> /// <MSBuild.ExtensionPack.VisualStudio.VB6 TaskAction="Build" Projects="@(ProjectsToBuild)"/> /// </Target> /// </Project> /// ]]></code> /// </example> [HelpUrl("http://www.msbuildextensionpack.com/help/3.5.12.0/html/c68d1d6c-b0bc-c944-e1a2-1ad4f0c28d3c.htm")] public class VB6 : BaseTask { private const string BuildTaskAction = "Build"; private const char Separator = ';'; [DropdownValue(BuildTaskAction)] public override string TaskAction { get { return base.TaskAction; } set { base.TaskAction = value; } } /// <summary> /// Sets the VB6Path. Default is [Program Files]\Microsoft Visual Studio\VB98\VB6.exe /// </summary> [TaskAction(BuildTaskAction, false)] public string VB6Path { get; set; } /// <summary> /// Set to true to stop processing when a project in the Projects collection fails to compile. Default is false. /// </summary> [TaskAction(BuildTaskAction, false)] public bool StopOnError { get; set; } /// <summary> /// Sets the projects. Use an 'OutDir' metadata item to specify the output directory. The OutDir will be created if it does not exist. /// </summary> [Required] [TaskAction(BuildTaskAction, true)] public ITaskItem[] Projects { get; set; } protected override void InternalExecute() { if (!this.TargetingLocalMachine()) { return; } if (string.IsNullOrEmpty(this.VB6Path)) { string programFilePath = Environment.GetEnvironmentVariable("ProgramFiles"); if (string.IsNullOrEmpty(programFilePath)) { Log.LogError("Failed to read a value from the ProgramFiles Environment Variable"); return; } if (File.Exists(programFilePath + @"\Microsoft Visual Studio\VB98\VB6.exe")) { this.VB6Path = programFilePath + @"\Microsoft Visual Studio\VB98\VB6.exe"; } else { Log.LogError(string.Format(CultureInfo.CurrentCulture, "VB6.exe was not found in the default location. Use VB6Path to specify it. Searched at: {0}", programFilePath + @"\Microsoft Visual Studio\VB98\VB6.exe")); return; } } switch (this.TaskAction) { case "Build": this.Build(); break; default: this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction)); return; } } private void Build() { if (this.Projects == null) { Log.LogError("The collection passed to Projects is empty"); return; } this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Building Projects Collection: {0} projects", this.Projects.Length)); foreach (ITaskItem project in this.Projects) { if (!this.BuildProject(project) && this.StopOnError) { this.LogTaskMessage("BuildVB6 Task Execution Failed [" + DateTime.Now.ToString("HH:MM:ss", CultureInfo.CurrentCulture) + "] Stopped by StopOnError set on true"); return; } } this.LogTaskMessage("BuildVB6 Task Execution Completed [" + DateTime.Now.ToString("HH:MM:ss", CultureInfo.CurrentCulture) + "]"); return; } private bool BuildProject(ITaskItem project) { using (Process proc = new Process()) { // start changing properties if (!string.IsNullOrEmpty(project.GetMetadata("ChgPropVBP"))) { this.LogTaskMessage("START - Changing Properties VBP"); VBPProject projectVBP = new VBPProject(project.ItemSpec); if (projectVBP.Load()) { string[] linesProperty = project.GetMetadata("ChgPropVBP").Split(Separator); string[] keyProperty = new string[linesProperty.Length]; string[] valueProperty = new string[linesProperty.Length]; int index; for (index = 0; index <= linesProperty.Length - 1; index++) { if (linesProperty[index].IndexOf("=", StringComparison.OrdinalIgnoreCase) != -1) { keyProperty[index] = linesProperty[index].Substring(0, linesProperty[index].IndexOf("=", StringComparison.OrdinalIgnoreCase)); valueProperty[index] = linesProperty[index].Substring(linesProperty[index].IndexOf("=", StringComparison.OrdinalIgnoreCase) + 1); } if (!string.IsNullOrEmpty(keyProperty[index]) && !string.IsNullOrEmpty(valueProperty[index])) { this.LogTaskMessage(keyProperty[index] + " -> New value: " + valueProperty[index]); projectVBP.SetProjectProperty(keyProperty[index], valueProperty[index], false); } } projectVBP.Save(); } this.LogTaskMessage("END - Changing Properties VBP"); } // end changing properties proc.StartInfo.FileName = this.VB6Path; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; if (string.IsNullOrEmpty(project.GetMetadata("OutDir"))) { proc.StartInfo.Arguments = @"/MAKE /OUT " + @"""" + project.ItemSpec + ".log" + @""" " + @"""" + project.ItemSpec + @""""; } else { if (!Directory.Exists(project.GetMetadata("OutDir"))) { Directory.CreateDirectory(project.GetMetadata("OutDir")); } proc.StartInfo.Arguments = @"/MAKE /OUT " + @"""" + project.ItemSpec + ".log" + @""" " + @"""" + project.ItemSpec + @"""" + " /outdir " + @"""" + project.GetMetadata("OutDir") + @""""; } // start the process this.LogTaskMessage("Running " + proc.StartInfo.FileName + " " + proc.StartInfo.Arguments); proc.Start(); string outputStream = proc.StandardOutput.ReadToEnd(); if (outputStream.Length > 0) { this.LogTaskMessage(outputStream); } string errorStream = proc.StandardError.ReadToEnd(); if (errorStream.Length > 0) { Log.LogError(errorStream); } proc.WaitForExit(); if (proc.ExitCode != 0) { Log.LogError("Non-zero exit code from VB6.exe: " + proc.ExitCode); try { using (FileStream myStreamFile = new FileStream(project.ItemSpec + ".log", FileMode.Open)) { System.IO.StreamReader myStream = new System.IO.StreamReader(myStreamFile); string myBuffer = myStream.ReadToEnd(); Log.LogError(myBuffer); } } catch (Exception ex) { Log.LogError(string.Format(CultureInfo.CurrentUICulture, "Unable to open log file: '{0}'. Exception: {1}", project.ItemSpec + ".log", ex.Message)); } return false; } return true; } } } }
using System; using System.Diagnostics; using System.Text; using Microsoft.CSharp; using System.CodeDom.Compiler; using System.Reflection; using System.Globalization; namespace DynamicTemplate.Compiler { class CSharpLanguageProvider : LanguageProvider { private PositionBuffer _value; private PositionTransposer _sourcePositionTransposer = new PositionTransposer(); public override string Name { get { return "C#"; } } public override bool IsValidIdentifier(string identifier, out string errorMessage) { if (identifier.Length == 0) { errorMessage = "Variable names must be one or more characters long"; return false; } if (identifier[0] == '@') { string subIdentifier = identifier.Substring(1); if (subIdentifier.Length == 0) { errorMessage = "Variable name is too short"; return false; } if (!IsValidIdentifierInternal(subIdentifier, out errorMessage)) return false; } else { if (!IsValidIdentifierInternal(identifier, out errorMessage)) return false; } switch (identifier) { case "abstract": #region C# keywords case "as": case "base": case "bool": case "break": case "byte": case ": case": case "catch": case "char": case "checked": case "class": case "const": case "continue": case "decimal": case "default": case "delegate": case "do": case "double": case "else": case "enum": case "event": case "explicit": case "extern": case "false": case "finally": case "fixed": case "float": case "for": case "foreach": case "goto": case "if": case "implicit": case "in": case "int": case "interface": case "internal": case "is": case "lock": case "long": case "namespace": case "new": case "null": case "object": case "operator": case "out": case "override": case "params": case "private": case "protected": case "public": case "readonly": case "ref": case "return": case "sbyte": case "sealed": case "short": case "sizeof": case "stackalloc": case "static": case "string": case "struct": case "switch": case "this": case "throw": case "true": case "try": case "typeof": case "uint": case "ulong": case "unchecked": case "unsafe": case "ushort": case "using": case "virtual": case "void": case "volatile": #endregion case "while": errorMessage = "\"" + identifier + "\" is a keyword and cannot be used as a variable name"; return false; } return true; } private static bool IsValidIdentifierInternal(string identifier, out string errorMessage) { if (!char.IsLetter(identifier[0]) && identifier[0] != '_') { errorMessage = "Variable names must start with either a letter or the underscore character"; return false; } for (int i = 1; i < identifier.Length; i++) { switch (char.GetUnicodeCategory(identifier[i])) { // letter-character case UnicodeCategory.LowercaseLetter: case UnicodeCategory.UppercaseLetter: case UnicodeCategory.TitlecaseLetter: case UnicodeCategory.ModifierLetter: case UnicodeCategory.OtherLetter: case UnicodeCategory.LetterNumber: // combining-character case UnicodeCategory.NonSpacingMark: case UnicodeCategory.SpacingCombiningMark: // decimal-digit-character case UnicodeCategory.DecimalDigitNumber: // connecting-character case UnicodeCategory.ConnectorPunctuation: // format-character case UnicodeCategory.Format: break; case UnicodeCategory.SpaceSeparator: errorMessage = "Variable names must not contain spaces"; return false; default: errorMessage = "Variable name contains illegal character(s)"; return false; } } errorMessage = null; return true; } public override string NormalizeIdentifier(string identifier) { return identifier[0] == '@' ? identifier.Substring(1) : identifier; } public override void Start(ArgumentDescription[] args) { _value = new PositionBuffer(); _value.Append( @"using System; using System.Text; using System.Web; using BlogServer; using BlogServer.Model; public class Template { private static string HtmlEncode(string val) { return System.Web.HttpUtility.HtmlEncode(val); } private static string HtmlAttributeEncode(string val) { return System.Web.HttpUtility.HtmlAttributeEncode(val); } private static string HtmlDecode(string val) { return System.Web.HttpUtility.HtmlDecode(val); } private static string UrlEncode(string val) { return System.Web.HttpUtility.UrlEncode(val); } private static string UrlPathEncode(string val) { return System.Web.HttpUtility.UrlPathEncode(val); } private static string UrlDecode(string val) { return System.Web.HttpUtility.UrlDecode(val); } public static string Process(object[] parameters) { StringBuilder ___output = new StringBuilder(); "); for (int ___i = 0; ___i < args.Length; ___i++) { ArgumentDescription arg = args[___i]; string argType = arg.Type.FullName; _value.AppendFormat("{0} {1} = ({0})parameters[{2}];", argType, arg.Identifier, ___i); } } public override void Code(string code, Position startPos) { _sourcePositionTransposer.AddMapping( _value.Position, startPos); _value.Append(code); /* _sourcePositionTransposer.AddMapping( new Position(_value.Line, _value.Column), Position.Unknown); */ } public override void Expression(string expr, Position startPos) { _value.Append("___output.Append("); _sourcePositionTransposer.AddMapping( _value.Position, startPos); _value.Append(expr); /* _sourcePositionTransposer.AddMapping( new Position(_value.Line, _value.Column + 1), Position.Unknown); */ _value.Append(");"); } public override void Literal(string literal, Position startPos) { _value.Append("___output.Append(@\""); foreach (char c in literal) { switch (c) { case '"': _value.Append("\"\""); break; default: _value.Append(c.ToString()); break; } } _value.Append("\");"); } public override TemplateOperation End() { _value.Append(@" return ___output.ToString(); } }"); CompilerParameters p = new CompilerParameters(); p.IncludeDebugInformation = true; p.GenerateInMemory = true; p.ReferencedAssemblies.Add("System.Web.dll"); p.ReferencedAssemblies.Add(Process.GetCurrentProcess().MainModule.FileName); CompilerResults results = new CSharpCodeProvider().CreateCompiler().CompileAssemblyFromSource(p, _value.ToString()); if (results.NativeCompilerReturnValue != 0) { throw TemplateCompilationException.CreateFromCompilerResults(results, _sourcePositionTransposer); } Type t = results.CompiledAssembly.GetType("Template"); MethodInfo m = t.GetMethod("Process", BindingFlags.Static | BindingFlags.Public); return new TemplateOperation(new InvokeAdapter(m).Invoke); } private class InvokeAdapter { private readonly MethodInfo _method; public InvokeAdapter(MethodInfo method) { _method = method; } public string Invoke(object[] values) { return (string)_method.Invoke(null, new object[] { values }); } } } }
using System.IO; using System.Threading.Tasks; using Android.Content; using Android.Graphics; using Android.Support.V4.Content; using Android.Text; using Android.Views; using Android.Widget; using AView = Android.Views.View; using AColor = Android.Graphics.Color; using AColorDraw = Android.Graphics.Drawables.ColorDrawable; namespace Xamarin.Forms.Platform.Android { public class BaseCellView : LinearLayout, INativeElementView { public const double DefaultMinHeight = 44; readonly Color _androidDefaultTextColor; readonly Cell _cell; readonly TextView _detailText; readonly ImageView _imageView; readonly TextView _mainText; Color _defaultDetailColor; Color _defaultMainTextColor; Color _detailTextColor; string _detailTextText; ImageSource _imageSource; Color _mainTextColor; string _mainTextText; public BaseCellView(Context context, Cell cell) : base(context) { _cell = cell; SetMinimumWidth((int)context.ToPixels(25)); SetMinimumHeight((int)context.ToPixels(25)); Orientation = Orientation.Horizontal; var padding = (int)context.FromPixels(8); SetPadding(padding, padding, padding, padding); _imageView = new ImageView(context); var imageParams = new LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.MatchParent) { Width = (int)context.ToPixels(60), Height = (int)context.ToPixels(60), RightMargin = 0, Gravity = GravityFlags.Center }; using (imageParams) AddView(_imageView, imageParams); var textLayout = new LinearLayout(context) { Orientation = Orientation.Vertical }; _mainText = new TextView(context); _mainText.SetSingleLine(true); _mainText.Ellipsize = TextUtils.TruncateAt.End; _mainText.SetPadding((int)context.ToPixels(15), padding, padding, padding); _mainText.SetTextAppearanceCompat(context, global::Android.Resource.Style.TextAppearanceSmall); using (var lp = new LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)) textLayout.AddView(_mainText, lp); _detailText = new TextView(context); _detailText.SetSingleLine(true); _detailText.Ellipsize = TextUtils.TruncateAt.End; _detailText.SetPadding((int)context.ToPixels(15), padding, padding, padding); _detailText.Visibility = ViewStates.Gone; _detailText.SetTextAppearanceCompat(context, global::Android.Resource.Style.TextAppearanceSmall); using (var lp = new LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)) textLayout.AddView(_detailText, lp); var layoutParams = new LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent) { Width = 0, Weight = 1, Gravity = GravityFlags.Center }; using (layoutParams) AddView(textLayout, layoutParams); SetMinimumHeight((int)context.ToPixels(DefaultMinHeight)); _androidDefaultTextColor = Color.FromUint((uint)_mainText.CurrentTextColor); } public AView AccessoryView { get; private set; } public string DetailText { get { return _detailTextText; } set { if (_detailTextText == value) return; _detailTextText = value; _detailText.Text = value; _detailText.Visibility = string.IsNullOrEmpty(value) ? ViewStates.Gone : ViewStates.Visible; } } public string MainText { get { return _mainTextText; } set { if (_mainTextText == value) return; _mainTextText = value; _mainText.Text = value; } } Element INativeElementView.Element { get { return _cell; } } public void SetAccessoryView(AView view) { if (AccessoryView != null) RemoveView(AccessoryView); if (view != null) { using (var layout = new LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.MatchParent)) AddView(view, layout); AccessoryView = view; } } public void SetDefaultMainTextColor(Color defaultColor) { _defaultMainTextColor = defaultColor; if (_mainTextColor == Color.Default) _mainText.SetTextColor(defaultColor.ToAndroid()); } public void SetDetailTextColor(Color color) { if (_detailTextColor == color) return; if (_defaultDetailColor == Color.Default) _defaultDetailColor = Color.FromUint((uint)_detailText.CurrentTextColor); _detailTextColor = color; _detailText.SetTextColor(color.ToAndroid(_defaultDetailColor)); } public void SetImageSource(ImageSource source) { UpdateBitmap(source, _imageSource); _imageSource = source; } public void SetImageVisible(bool visible) { _imageView.Visibility = visible ? ViewStates.Visible : ViewStates.Gone; } public void SetIsEnabled(bool isEnable) { _mainText.Enabled = isEnable; _detailText.Enabled = isEnable; } public void SetMainTextColor(Color color) { Color defaultColorToSet = _defaultMainTextColor == Color.Default ? _androidDefaultTextColor : _defaultMainTextColor; _mainTextColor = color; _mainText.SetTextColor(color.ToAndroid(defaultColorToSet)); } public void SetRenderHeight(double height) { height = Context.ToPixels(height); LayoutParameters = new LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(height == -1 ? ViewGroup.LayoutParams.WrapContent : height)); } async void UpdateBitmap(ImageSource source, ImageSource previousSource = null) { if (Equals(source, previousSource)) return; _imageView.SetImageResource(global::Android.Resource.Color.Transparent); Bitmap bitmap = null; IImageSourceHandler handler; if (source != null && (handler = Registrar.Registered.GetHandler<IImageSourceHandler>(source.GetType())) != null) { try { bitmap = await handler.LoadImageAsync(source, Context); } catch (TaskCanceledException) { } catch (IOException ex) { Log.Warning("Xamarin.Forms.Platform.Android.BaseCellView", "Error updating bitmap: {0}", ex); } } _imageView.SetImageBitmap(bitmap); if (bitmap != null) bitmap.Dispose(); } } }