content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using Alabo.App.Share.HuDong.Domain.Entities; using Alabo.Datas.UnitOfWorks; using Alabo.Domains.Repositories; using MongoDB.Bson; namespace Alabo.App.Share.HuDong.Domain.Repositories { public class HudongRecordRepository : RepositoryMongo<HudongRecord, ObjectId>, IHudongRecordRepository { public HudongRecordRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { } } }
29.142857
106
0.757353
[ "MIT" ]
tongxin3267/alabo
src/05.cloud/08-Alabo.Cloud.Hudong/Domain/Repositories/HudongRecordRepository.cs
408
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Business.Log; using System.Data; using Web.Library; using Types.Enums; namespace Web.Admin { public partial class Log : MasterOfMaster { protected override MemberShipType PageMemberShip { get { return MemberShipType.Guest; } } protected DataSet dsLoglar { get { return (DataSet)Session["__loglar"]; } set { Session["__loglar"] = value; } } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { exdrpIslemTuru.Items.Add(new ListItem("Yeni Kayıt", Log_Yapilan_Islem_Turu.Yeni_Kayit.GetHashCode().ToString())); exdrpIslemTuru.Items.Add(new ListItem("Kayıt Güncelleme", Log_Yapilan_Islem_Turu.Kayit_Guncelleme.GetHashCode().ToString())); exdrpIslemTuru.Items.Add(new ListItem("Silinen Kayıtlar", Log_Yapilan_Islem_Turu.Kayit_Silme.GetHashCode().ToString())); exdrpIslemTuru.Items.Add(new ListItem("Diğer", Log_Yapilan_Islem_Turu.Diger.GetHashCode().ToString())); Araclar.Kombo_Doldur(drpMemberShipType, CacheHelper.KullaniciTipiGetir(), "DESCRIPTION", "RECID", Araclar.KomboTip.Normal); tvFiltrelemeBaslangic.Tarih = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1); tvFiltrelemeBitis.Tarih = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day); Listele(); } } protected void btnFiltrele_Click(object sender, EventArgs e) { Listele(); } protected void Listele() { BSLog oYetki = new BSLog(); DataSet ds = new DataSet(); string whereCondition = string.Empty; whereCondition = " Log.OPERATIONTYPE=" + exdrpIslemTuru.SelectedValue; whereCondition += " AND (MEMBERSHIPTYPE.RECID = " + drpMemberShipType.SelectedValue + ")"; if (Araclar.IsDateTime(tvFiltrelemeBaslangic.Text) & Araclar.IsDateTime(tvFiltrelemeBitis.Text)) { whereCondition += " AND (OPDATE BETWEEN CONVERT(DATETIME, '" + tvFiltrelemeBaslangic.Tarih.ToShortDateString() + " 00:00:00', 103) AND CONVERT(DATETIME, '" + tvFiltrelemeBitis.Tarih.ToShortDateString() + " 23:59:59', 103))"; } ds = oYetki.LogGetir(whereCondition); dsLoglar = ds; gvLoglar.PageIndex = 0; Araclar.GridDoldur(ds, gvLoglar); } protected void gvLoglar_PageIndexChanging(object sender, GridViewPageEventArgs e) { gvLoglar.PageIndex = e.NewPageIndex; Araclar.GridDoldur(dsLoglar, gvLoglar); } } }
34.8
240
0.610886
[ "MIT" ]
onuraltun/BusinessAngelNetwork
Web/Admin/Log.aspx.cs
2,965
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Collections.ObjectModel; using Windows.ApplicationModel.Contacts; using Windows.Storage; using Windows.UI.Xaml; using Windows.UI.Xaml.Automation; using Windows.UI.Xaml.Automation.Peers; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Shapes; namespace MUXControlsTestApp { [TopLevelTestPage(Name="PersonPicture", Icon="PersonPicture.png")] public sealed partial class PersonPicturePage : TestPage { private Uri imageUri = new Uri("ms-appx:///Assets/ingredient2.png"); private bool primaryEllipseLoaded = false; public PersonPicturePage() { this.InitializeComponent(); this.TestPersonPicture.Loaded += PersonPicture_Loaded; this.TestPersonPicture.LayoutUpdated += PersonPicture_LayoutUpdated; } private void PersonPicture_LayoutUpdated(object sender, object e) { // Register items that are delay loaded if (!primaryEllipseLoaded) { string primaryEllipseName = "PersonPictureEllipse"; Ellipse primaryEllipse = FindVisualChildByName(this.TestPersonPicture, primaryEllipseName) as Ellipse; if (primaryEllipse != null) { // Capture initial state of the property PrimaryEllipseFillChanged(primaryEllipse, Ellipse.FillProperty); primaryEllipse.RegisterPropertyChangedCallback(Ellipse.FillProperty, new DependencyPropertyChangedCallback(PrimaryEllipseFillChanged)); primaryEllipseLoaded = true; } } } private void PersonPicture_Loaded(object sender, RoutedEventArgs e) { string InitialTextBlockName = "InitialsTextBlock"; TextBlock initialTextBlock = FindVisualChildByName(this.TestPersonPicture, InitialTextBlockName) as TextBlock; if (initialTextBlock != null) { AutomationProperties.SetName(initialTextBlock, InitialTextBlockName); AutomationProperties.SetAccessibilityView(initialTextBlock, AccessibilityView.Content); } string badgeTextBlockName = "BadgeNumberTextBlock"; TextBlock badgeTextBlock = FindVisualChildByName(this.TestPersonPicture, badgeTextBlockName) as TextBlock; if (badgeTextBlock != null) { AutomationProperties.SetName(badgeTextBlock, badgeTextBlockName); AutomationProperties.SetAccessibilityView(badgeTextBlock, AccessibilityView.Content); } string badgeGlyphIconName = "BadgeGlyphIcon"; FontIcon badgeFontIcon = FindVisualChildByName(this.TestPersonPicture, badgeGlyphIconName) as FontIcon; if (badgeFontIcon != null) { AutomationProperties.SetName(badgeFontIcon, badgeGlyphIconName); AutomationProperties.SetAccessibilityView(badgeFontIcon, AccessibilityView.Content); } string badgeEllipseName = "BadgingEllipse"; Ellipse badgeEllipse = FindVisualChildByName(this.TestPersonPicture, badgeEllipseName) as Ellipse; if (badgeEllipse != null) { AutomationProperties.SetName(badgeEllipse, badgeEllipseName); AutomationProperties.SetAccessibilityView(badgeEllipse, AccessibilityView.Content); } CollectionViewSource cvs = rootGrid.FindName("cvs") as CollectionViewSource; cvs.Source = GetGroupedPeople(); cvs.IsSourceGrouped = true; } private void FindAndGiveAutomationNameToVisualChild(string childName) { DependencyObject obj = FindVisualChildByName(this.TestPersonPicture, childName); if (obj != null) { AutomationProperties.SetName(obj, childName); } } private void PrimaryEllipseFillChanged(DependencyObject o, DependencyProperty p) { if (((Ellipse)o).Fill != null) { BgEllipseFilled.IsChecked = true; } else { BgEllipseFilled.IsChecked = false; } } private void BadgeNumberTextBox_TextChanged(object sender, RoutedEventArgs e) { int result = 0; int.TryParse(BadgeNumberTextBox.Text, out result); TestPersonPicture.BadgeNumber = result; } private void BadgeGlyphTextBox_TextChanged(object sender, TextChangedEventArgs e) { TestPersonPicture.BadgeGlyph = BadgeGlyphTextBox.Text; } private void InitialTextBox_TextChanged(object sender, TextChangedEventArgs e) { TestPersonPicture.Initials = InitialTextBox.Text; } private void GroupCheckBox_Checked(object sender, RoutedEventArgs e) { TestPersonPicture.IsGroup = true; } private void GroupCheckBox_Unchecked(object sender, RoutedEventArgs e) { TestPersonPicture.IsGroup = false; } private void DisplayNameTextBox_TextChanged(object sender, TextChangedEventArgs e) { TestPersonPicture.DisplayName = DisplayNameTextBox.Text; } private void ContactBtn_Click(object sender, RoutedEventArgs e) { Contact contact = new Contact(); contact.FirstName = "Test"; contact.LastName = "Contact"; TestPersonPicture.Contact = contact; } private async void ContactImageBtn_Click(object sender, RoutedEventArgs e) { Contact contact = new Contact(); contact.SourceDisplayPicture = await StorageFile.GetFileFromApplicationUriAsync(imageUri); TestPersonPicture.Contact = contact; } private void ClearContactBtn_Click(object sender, RoutedEventArgs e) { TestPersonPicture.Contact = null; } private void ImageBtn_Click(object sender, RoutedEventArgs e) { TestPersonPicture.ProfilePicture = new BitmapImage(imageUri); } private void ClearImageBtn_Click(object sender, RoutedEventArgs e) { TestPersonPicture.ProfilePicture = null; } private void TestPersonPicture_SizeChanged(object sender, SizeChangedEventArgs e) { if (Math.Round(TestPersonPicture.Width) == Math.Round(TestPersonPicture.Height)) { DimensionsMatch.IsChecked = true; } else { DimensionsMatch.IsChecked = false; } } private static ObservableCollection<SportsGroup> GetGroupedPeople() { ObservableCollection<SportsGroup> groupedPeople = new ObservableCollection<SportsGroup>(); for (int i = 0; i< 4; ++i) { SportsGroup group = null; switch (i) { case 0: group = new SportsGroup("Tennis"); group.Add(new SportsPerson(1, "RF", "Roger Federer")); group.Add(new SportsPerson(2, "RN", "Rafael Nadal")); group.Add(new SportsPerson(3, "ND", "Novak Djokovic")); group.Add(new SportsPerson(4, "AM", "Andy Murray")); group.Add(new SportsPerson(5, "GD", "Grigor Dimitrov")); break; case 1: group = new SportsGroup("Soccer"); group.Add(new SportsPerson(6, "CR", "Cristiano Ronaldo")); group.Add(new SportsPerson(7, "LM", "Lionel Messi")); group.Add(new SportsPerson(8, "N", "Neymar")); group.Add(new SportsPerson(9, "AI", "Andres Iniesta")); group.Add(new SportsPerson(10, "GB", "Gareth Bale")); group.Add(new SportsPerson(11, "X", "Xavi")); group.Add(new SportsPerson(12, "JR", "James Rodriguez")); group.Add(new SportsPerson(13, "R", "Ronaldinho")); group.Add(new SportsPerson(14, "AR", "Arjen Robben")); break; case 2: group = new SportsGroup("Basketball"); group.Add(new SportsPerson(15, "AI", "Allen Iverson")); group.Add(new SportsPerson(16, "DW", "Dwayne Wade")); group.Add(new SportsPerson(17, "LJ", "LeBron James")); group.Add(new SportsPerson(18, "KD", "Kevin Durant")); group.Add(new SportsPerson(19, "KB", "Kobe Bryant")); break; case 3: group = new SportsGroup("Formula 1"); group.Add(new SportsPerson(20, "AP", "Alain Prost")); group.Add(new SportsPerson(21, "AS", "Ayrton Senna")); group.Add(new SportsPerson(22, "MS", "Michael Schumacher")); group.Add(new SportsPerson(23, "NL", "Niki Lauda")); group.Add(new SportsPerson(24, "SV", "Sebastian Vettel")); break; } groupedPeople.Add(group); } return groupedPeople; } public class SportsPerson { public SportsPerson(int badgeNumber, string initials, string displayName) { BadgeNumber = badgeNumber; Initials = initials; DisplayName = displayName; } public int BadgeNumber { get; set; } public string Initials { get; set; } public string DisplayName { get; set; } } public class SportsGroup : ObservableCollection<SportsPerson> { public SportsGroup(string name) { Name = name; } public string Name { get; set; } } } }
38.010989
155
0.586971
[ "MIT" ]
55995409/microsoft-ui-xaml
dev/PersonPicture/TestUI/PersonPicturePage.xaml.cs
10,379
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImport; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.CSharp.Simplification; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; // to avoid excessive #ifdefs #pragma warning disable CA1822 // Mark members as static #pragma warning disable IDE0052 // Remove unread private members namespace Microsoft.CodeAnalysis.CodeActions; internal readonly struct CSharpCodeFixOptionsProvider { /// <summary> /// Document editorconfig options. /// </summary> private readonly AnalyzerConfigOptions _options; /// <summary> /// C# language services. /// </summary> private readonly HostLanguageServices _languageServices; /// <summary> /// Fallback options provider - default options provider in Code Style layer. /// </summary> private readonly CodeActionOptionsProvider _fallbackOptions; public CSharpCodeFixOptionsProvider(AnalyzerConfigOptions options, CodeActionOptionsProvider fallbackOptions, HostLanguageServices languageServices) { _options = options; _fallbackOptions = fallbackOptions; _languageServices = languageServices; } // LineFormattingOptions public string NewLine => GetOption(FormattingOptions2.NewLine, FallbackLineFormattingOptions.NewLine); // SimplifierOptions public CodeStyleOption2<bool> VarForBuiltInTypes => GetOption(CSharpCodeStyleOptions.VarForBuiltInTypes, FallbackSimplifierOptions.VarForBuiltInTypes); public CodeStyleOption2<bool> VarElsewhere => GetOption(CSharpCodeStyleOptions.VarElsewhere, FallbackSimplifierOptions.VarElsewhere); public SimplifierOptions GetSimplifierOptions() => _options.GetCSharpSimplifierOptions(FallbackSimplifierOptions); // FormattingOptions public CodeStyleOption2<NamespaceDeclarationPreference> NamespaceDeclarations => GetOption(CSharpCodeStyleOptions.NamespaceDeclarations, FallbackSyntaxFormattingOptions.NamespaceDeclarations); public CodeStyleOption2<bool> PreferTopLevelStatements => GetOption(CSharpCodeStyleOptions.PreferTopLevelStatements, FallbackSyntaxFormattingOptions.PreferTopLevelStatements); internal SyntaxFormattingOptions GetFormattingOptions() => _options.GetCSharpSyntaxFormattingOptions(FallbackSyntaxFormattingOptions); // AddImportPlacementOptions public CodeStyleOption2<AddImportPlacement> UsingDirectivePlacement => GetOption(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, FallbackAddImportPlacementOptions.UsingDirectivePlacement); // CodeStyleOptions public CodeStyleOption2<string> PreferredModifierOrder => GetOption(CSharpCodeStyleOptions.PreferredModifierOrder, FallbackCodeStyleOptions.PreferredModifierOrder); public CodeStyleOption2<AccessibilityModifiersRequired> AccessibilityModifiersRequired => GetOption(CodeStyleOptions2.AccessibilityModifiersRequired, FallbackCodeStyleOptions.Common.AccessibilityModifiersRequired); private TValue GetOption<TValue>(Option2<TValue> option, TValue defaultValue) => _options.GetEditorConfigOption(option, defaultValue); private TValue GetOption<TValue>(PerLanguageOption2<TValue> option, TValue defaultValue) => _options.GetEditorConfigOption(option, defaultValue); private CSharpIdeCodeStyleOptions FallbackCodeStyleOptions #if CODE_STYLE => CSharpIdeCodeStyleOptions.Default; #else => (CSharpIdeCodeStyleOptions)_fallbackOptions.GetOptions(_languageServices).CodeStyleOptions; #endif private CSharpSimplifierOptions FallbackSimplifierOptions #if CODE_STYLE => CSharpSimplifierOptions.Default; #else => (CSharpSimplifierOptions)_fallbackOptions.GetOptions(_languageServices).CleanupOptions.SimplifierOptions; #endif private CSharpSyntaxFormattingOptions FallbackSyntaxFormattingOptions #if CODE_STYLE => CSharpSyntaxFormattingOptions.Default; #else => (CSharpSyntaxFormattingOptions)_fallbackOptions.GetOptions(_languageServices).CleanupOptions.FormattingOptions; #endif private LineFormattingOptions FallbackLineFormattingOptions #if CODE_STYLE => LineFormattingOptions.Default; #else => _fallbackOptions.GetOptions(_languageServices).CleanupOptions.FormattingOptions.LineFormatting; #endif private AddImportPlacementOptions FallbackAddImportPlacementOptions #if CODE_STYLE => AddImportPlacementOptions.Default; #else => _fallbackOptions.GetOptions(_languageServices).CleanupOptions.AddImportOptions; #endif } internal static class CSharpCodeFixOptionsProviders { public static async ValueTask<CSharpCodeFixOptionsProvider> GetCSharpCodeFixOptionsProviderAsync(this Document document, CodeActionOptionsProvider fallbackOptions, CancellationToken cancellationToken) { var configOptions = await document.GetAnalyzerConfigOptionsAsync(cancellationToken).ConfigureAwait(false); return new CSharpCodeFixOptionsProvider(configOptions, fallbackOptions, document.Project.GetExtendedLanguageServices()); } }
43.330769
218
0.814841
[ "MIT" ]
BillWagner/roslyn
src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/CodeActions/CSharpCodeFixOptionsProvider.cs
5,635
C#
using System.Collections.Generic; using System.Text.Json.Serialization; namespace JL.PoS { public class JmdictWc { [JsonPropertyName("S")] public string Spelling { get; set; } [JsonPropertyName("R")] public List<string> Readings { get; set; } [JsonPropertyName("C")] public List<string> WordClasses { get; set; } public JmdictWc(string spelling, List<string> readings, List<string> wordClasses) { Spelling = spelling; Readings = readings; WordClasses = wordClasses; } } }
26.045455
89
0.619546
[ "Apache-2.0" ]
thovip119/JL
JL/PoS/JmdictWc.cs
575
C#
using CadEditor; using System; //css_include ninja_gaiden_3/NinjaGaiden3Utils.cs; public class Data { public OffsetRec getScreensOffset() { return new OffsetRec(0x1ab6, 1 , 6*8, 6, 8); } public OffsetRec getBlocksOffset() { return new OffsetRec(0x5010 , 1 , 0x1000); } public int getBlocksCount() { return 256; } public OffsetRec getBigBlocksOffset() { return new OffsetRec(0x6810 , 1 , 0x1000); } public int getBigBlocksCount() { return 256; } public int getPalBytesAddr() { return 0x7d10; } public bool getScreenVertical() { return true; } public bool isBigBlockEditorEnabled() { return true; } public bool isBlockEditorEnabled() { return true; } public bool isEnemyEditorEnabled() { return false; } public GetVideoPageAddrFunc getVideoPageAddrFunc() { return getVideoAddress; } public GetVideoChunkFunc getVideoChunkFunc() { return getVideoChunk; } public SetVideoChunkFunc setVideoChunkFunc() { return null; } public GetPalFunc getPalFunc() { return getPallete;} public SetPalFunc setPalFunc() { return null;} public GetBlocksFunc getBlocksFunc() { return NinjaGaiden3Utils.getBlocks;} public SetBlocksFunc setBlocksFunc() { return NinjaGaiden3Utils.setBlocks;} public GetBigBlocksFunc getBigBlocksFunc() { return NinjaGaiden3Utils.getBigBlocksTT;} public SetBigBlocksFunc setBigBlocksFunc() { return NinjaGaiden3Utils.setBigBlocksTT;} //---------------------------------------------------------------------------- public int getVideoAddress(int id) { return -1; } public byte[] getVideoChunk(int videoPageId) { return Utils.readVideoBankFromFile("chr6-2a.bin", videoPageId); } public byte[] getPallete(int palId) { return Utils.readBinFile("pal6-3a.bin"); } }
37.784314
96
0.648158
[ "MIT" ]
spiiin/CadEditor
CadEditor/settings_nes/ninja_gaiden_3/Settings_NinjaGaiden3_6-3a.cs
1,927
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace MixERP.Net.Core.Modules.Finance.Widgets { public partial class WorkflowWidget { /// <summary> /// Placeholder1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.PlaceHolder Placeholder1; } }
32.08
84
0.486284
[ "MPL-2.0" ]
asine/mixerp
src/FrontEnd/Modules/Finance/Widgets/WorkflowWidget.ascx.designer.cs
804
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.PowerPlatform.Formulas.Tools; using Microsoft.PowerPlatform.Formulas.Tools.Utility; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Data; using System.IO; using System.IO.Compression; using System.Linq; namespace PAModelTests { // DataSources Tests [TestClass] public class DataSourceTests { // Validates that the TableDefinitions are being added at the end of the DataSources.json when the entropy file is deleted. [DataTestMethod] [DataRow("GalleryTestApp.msapp")] [DataRow("AccountPlanReviewerMaster.msapp")] public void TestTableDefinitionsAreLastEntriesWhenEntropyDeleted(string appName) { var root = Path.Combine(Environment.CurrentDirectory, "Apps", appName); Assert.IsTrue(File.Exists(root)); (var msapp, var errors) = CanvasDocument.LoadFromMsapp(root); errors.ThrowOnErrors(); using (var tempDir = new TempDir()) { string outSrcDir = tempDir.Dir; // Save to sources msapp.SaveToSources(outSrcDir); // Delete Entropy directory var entropyPath = Path.Combine(outSrcDir, "Entropy"); if (Directory.Exists(entropyPath)) { Directory.Delete(entropyPath, true); } // Load app from the sources after deleting the entropy var app = SourceSerializer.LoadFromSource(outSrcDir, new ErrorContainer()); using (var tempFile = new TempFile()) { // Repack the app MsAppSerializer.SaveAsMsApp(app, tempFile.FullPath, new ErrorContainer()); using (var stream = new FileStream(tempFile.FullPath, FileMode.Open)) { // Read the msapp file ZipArchive zipOpen = new ZipArchive(stream, ZipArchiveMode.Read); foreach (var entry in zipOpen.Entries) { var kind = FileEntry.TriageKind(FilePath.FromMsAppPath(entry.FullName)); switch (kind) { // Validate that the last entry in the DataSources.json is TableDefinition entry. case FileKind.DataSources: { var dataSourcesFromMsapp = ToObject<DataSourcesJson>(entry); var last = dataSourcesFromMsapp.DataSources.LastOrDefault(); Assert.AreEqual(last.TableDefinition != null, true); return; } default: break; } } } } } } [DataTestMethod] [DataRow("EmptyLocalDBRefsHashMismatchProperties.msapp")] public void TestNoLocalDatabaseRefsWhenLocalDatabaseReferencesPropertyWasEmptyJson(string appName) { var pathToMsApp = Path.Combine(Environment.CurrentDirectory, "Apps", appName); Assert.IsTrue(File.Exists(pathToMsApp)); var (msApp, errors) = CanvasDocument.LoadFromMsapp(pathToMsApp); errors.ThrowOnErrors(); using var sourcesTempDir = new TempDir(); var sourcesTempDirPath = sourcesTempDir.Dir; msApp.SaveToSources(sourcesTempDirPath); var loadedMsApp = SourceSerializer.LoadFromSource(sourcesTempDirPath, new ErrorContainer()); Assert.IsTrue(loadedMsApp._entropy.WasLocalDatabaseReferencesEmpty.Value); Assert.IsFalse(loadedMsApp._entropy.LocalDatabaseReferencesAsEmpty); Assert.IsTrue(loadedMsApp._dataSourceReferences.Count == 0); } [DataTestMethod] [DataRow("EmptyLocalDBRefsHashMismatchProperties.msapp")] public void TestConnectionInstanceIDHandling(string appName) { var pathToMsApp = Path.Combine(Environment.CurrentDirectory, "Apps", appName); Assert.IsTrue(File.Exists(pathToMsApp)); var (msApp, errors) = CanvasDocument.LoadFromMsapp(pathToMsApp); errors.ThrowOnErrors(); // Testing if conn instance id is added to entropy Assert.IsNotNull(msApp._entropy.LocalConnectionIDReferences); using var sourcesTempDir = new TempDir(); var sourcesTempDirPath = sourcesTempDir.Dir; ErrorContainer errorsCaptured = msApp.SaveToSources(sourcesTempDirPath, pathToMsApp); errorsCaptured.ThrowOnErrors(); } [DataTestMethod] [DataRow(new string[] {"FileNameOne.txt" }, ".txt")] [DataRow(new string[] {"FileNameTwo.tx<t" }, ".tx%3ct")] [DataRow(new string[] { "FileNameThr<ee.txt" }, ".txt")] public void TestGetExtensionEncoded(string[] fileExtension, string encodedExtension) { FilePath filePath = new FilePath(fileExtension); Assert.AreEqual(filePath.GetExtension(), encodedExtension); } private static T ToObject<T>(ZipArchiveEntry entry) { var je = entry.ToJson(); return je.ToObject<T>(); } } }
40.912409
131
0.57645
[ "MIT" ]
jack-work/PowerApps-Language-Tooling
src/PAModelTests/DataSourceTests.cs
5,605
C#
using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Xml.Linq; using OpenAC.Net.Core; using OpenAC.Net.Core.Extensions; using OpenAC.Net.DFe.Core.Attributes; namespace OpenAC.Net.DFe.Core.Serializer; internal static class InterfaceSerializer { public static XObject[] Serialize(PropertyInfo prop, object parentObject, SerializerOptions options) { var value = prop.GetValue(parentObject, null); var objectType = ObjectType.From(value); var attributes = prop.GetAttributes<DFeItemAttribute>(); var itemAttribute = attributes.SingleOrDefault(x => x.Tipo == value.GetType()); Guard.Against<OpenDFeException>(itemAttribute == null, $"Nenhum atributo [{nameof(DFeItemAttribute)}] encontrado " + $"para o objeto: {nameof(value.GetType)}"); if (objectType.IsIn(ObjectType.ListType, ObjectType.ArrayType, ObjectType.EnumerableType)) { var list = (ICollection)prop.GetValue(parentObject, null); return CollectionSerializer.SerializeObjects(list, itemAttribute, options); } return objectType == ObjectType.ValueElementType ? ValueElementSerializer.Serialize(prop, parentObject, options) : new XObject[] { ObjectSerializer.Serialize(value, value.GetType(), itemAttribute.Name, itemAttribute.Namespace, options) }; } public static object Deserialize(PropertyInfo prop, XElement parentElement, object item, SerializerOptions options) { var tags = prop.GetAttributes<DFeItemAttribute>(); foreach (var att in tags) { var node = parentElement.ElementsAnyNs(att.Name).FirstOrDefault(); if (node == null) continue; var objectType = ObjectType.From(att.Tipo); if (objectType.IsIn(ObjectType.ArrayType, ObjectType.EnumerableType)) { var listElement = parentElement.ElementsAnyNs(att.Name); var list = (List<object>)CollectionSerializer.Deserialize(typeof(List<object>), listElement, options); var type = CollectionSerializer.GetItemType(att.Tipo); return objectType == ObjectType.ArrayType ? list.Cast(type).ToArray(type) : list.Cast(type); } if (objectType == ObjectType.ListType) { var listElement = parentElement.ElementsAnyNs(att.Name); return CollectionSerializer.Deserialize(att.Tipo, listElement, options); } return objectType == ObjectType.ValueElementType ? ValueElementSerializer.Deserialize(att.Tipo, parentElement, options) : ObjectSerializer.Deserialize(att.Tipo, node, options); } return null; } }
44.936508
135
0.66443
[ "MIT" ]
OpenAC-Net/OpenAC.Net.DFe.Core
src/OpenAC.Net.DFe.Core/Serializer/InterfaceSerializer.cs
2,831
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Inventor; namespace InventorShims.TranslatorShim { /// <summary>Exports a document to a STL file</summary> public class StlExporter { ///<summary>The document to be exported</summary> public Inventor.Document Document { get; set; } = null; ///<value>Defaults to mm.</value> public ImportUnitsTypeEnum Units { get; set; } = ImportUnitsTypeEnum.kMillimeterUnitsType; /// <summary> /// Setting this to anything other than Custom will cause the exporter to ignore the following variables:<code/> /// <see cref="SurfaceDeviation"/>,<code/> /// <see cref="NormalDeviation"/>,<code/> /// <see cref="MaxEdgeLength"/>,<code/> /// <see cref="MaxAspectRatio"/> /// </summary> public StlResolutionEnum Resolution { get; set; } = StlResolutionEnum.Custom; public bool AllowMoveMeshNodes { get; set; } = false; ///<summary>backing variable for <see cref="SurfaceDeviation"/></summary> private double _surfaceDeviation = 0.005; /// <summary>Max distance between facet edges and surface edges (as a percentage of each body's RangeBox size).<code/> /// Modifying this value automatically changes <see cref="Resolution"/> to <see cref="StlResolutionEnum.Custom"/><code/> /// Valid values: 0 to 100 /// </summary> public double SurfaceDeviation { get { return _surfaceDeviation; } set { _surfaceDeviation = value; Resolution = StlResolutionEnum.Custom; } } ///<summary>backing variable for <see cref="NormalDeviation"/></summary> private double _normalDeviation = 10.0; /// <summary>The max angle between adjacent face normals of approximated curves.<code/> /// Modifying this value automatically changes <see cref="Resolution"/> to <see cref="StlResolutionEnum.Custom"/><code/> /// Valid values: 0 to 41 /// </summary> public double NormalDeviation { get { return _normalDeviation; } set { _normalDeviation = value; Resolution = StlResolutionEnum.Custom; } } ///<summary>backing variable for <see cref="MaxEdgeLength"/></summary> private double _maxEdgeLength = 0.0; /// <summary>Max distance between the grid lines that are placed on a face during the tessellation process (as a percentage of each body's RangeBox size).<code/> /// Modifying this value automatically changes <see cref="Resolution"/> to <see cref="StlResolutionEnum.Custom"/><code/> /// Valid Values: 0 to 100 (0 to disable) /// </summary> public double MaxEdgeLength { get { return _maxEdgeLength; } set { _maxEdgeLength = value; Resolution = StlResolutionEnum.Custom; } } ///<summary>backing variable for <see cref="MaxAspectRatio"/></summary> private double _maxAspectRatio = 0.0; /// <summary>Ratio between height and width of facets.<code/> /// Modifying this value automatically changes <see cref="Resolution"/> to <see cref="StlResolutionEnum.Custom"/><code/> /// Valid Values: 0 to 21.5 (0 to disable) /// </summary> public double MaxAspectRatio { get { return _maxAspectRatio; } set { _maxAspectRatio = value; Resolution = StlResolutionEnum.Custom; } } /// <summary>Determines whether an assembly is exported as one or multiple files.</summary> public bool OneFilePerPartInstance { get; set; } = false; /// <summary>Requires <see cref="Binary"/> = true</summary> public bool ExportColors { get; set; } = true; /// <summary> /// Exported STL file will be binary instead of plaintext ASCII.<code/> /// Binary files have a smaller filesize, and support colors. /// </summary> public bool Binary { get; set; } = true; ///<summary>Initializes a new instance of <see cref="StlExporter"/></summary> public StlExporter(Inventor.Document Document) { this.Document = Document; } ///<summary>Export to STL file with the same folder and filename as the document.</summary> public void Export() { Export(System.IO.Path.ChangeExtension(this.Document.FullFileName, "stl")); } ///<summary>Export to STL file with the specified full file path.</summary> public void Export(string OutputFile) { TranslatorData oTranslatorData = new TranslatorData(addinGUID: "{533E9A98-FC3B-11D4-8E7E-0010B541CD80}", fullFileName: OutputFile, doc: this.Document); NameValueMap op = oTranslatorData.oOptions; op.Value["ExportUnits"] = (int)Units - 110080; //Convert ImportUnitsTypeEnum to the integer values expected by the STL exporter op.Value["Resolution"] = Resolution; op.Value["AllowMoveMeshNode"] = AllowMoveMeshNodes; op.Value["SurfaceDeviation"] = SurfaceDeviation; op.Value["NormalDeviation"] = NormalDeviation; op.Value["MaxEdgeLength"] = MaxEdgeLength; op.Value["AspectRatio"] = MaxAspectRatio; op.Value["ExportFileStructure"] = Convert.ToInt32(OneFilePerPartInstance); op.Value["OutputFileType"] = Convert.ToInt32(!Binary); op.Value["ExportColor"] = ExportColors; TranslatorAddIn oTranslatorAddIn = (TranslatorAddIn)oTranslatorData.oAppAddIn; oTranslatorAddIn.SaveCopyAs(this.Document, oTranslatorData.oContext, oTranslatorData.oOptions, oTranslatorData.oDataMedium); } } }
39.03871
169
0.61494
[ "MIT" ]
InventorCode/InventorShims
src/InventorShims/TranslatorShim/StlExporter.cs
6,053
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Button : MonoBehaviour { public ParticleSystemRenderer psr; public float PsEmission; // Start is called before the first frame update void Start() { psr = GetComponent<ParticleSystemRenderer>(); } // Update is called once per frame void Update() { } void onclick() { // psr.material = c; } }
17.538462
53
0.640351
[ "MIT" ]
SangwookYoo/SimpleFlameReaction-unity
Assets/Scripts/Button.cs
458
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using Microsoft.ML.Data; namespace Microsoft.ML { /// <summary> /// The input and output of Query Operators (Transforms). This is the fundamental data pipeline /// type, comparable to <see cref="IEnumerable{T}"/> for LINQ. /// </summary> /// <example> /// <format type="text/markdown"> /// <![CDATA[ /// [!code-csharp[SimpleDataViewImplementation](~/../docs/samples/docs/samples/Microsoft.ML.Samples/Dynamic/SimpleDataViewImplementation.cs)] /// ]]> /// </format> /// </example> public interface IDataView { /// <summary> /// Whether this IDataView supports shuffling of rows, to any degree. /// </summary> bool CanShuffle { get; } /// <summary> /// Returns the number of rows if known. Returning null means that the row count is unknown but /// it might return a non-null value on a subsequent call. This indicates, that the transform does /// not YET know the number of rows, but may in the future. Its implementation's computation /// complexity should be O(1). /// /// Most implementation will return the same answer every time. Some, like a cache, might /// return null until the cache is fully populated. /// </summary> long? GetRowCount(); /// <summary> /// Get a row cursor. The <paramref name="columnsNeeded"/> indicate the active columns that are needed /// to iterate over. If set to an empty <see cref="IEnumerable"/> no column is requested. The schema of the returned /// cursor will be the same as the schema of the IDataView, but getting a getter for inactive columns will throw. /// </summary> /// <param name="columnsNeeded">The active columns needed. If passed an empty <see cref="IEnumerable"/> no column is requested.</param> /// <param name="rand">An instance of <see cref="Random"/> to seed randomizing the access for a shuffled cursor.</param> DataViewRowCursor GetRowCursor(IEnumerable<DataViewSchema.Column> columnsNeeded, Random rand = null); /// <summary> /// This constructs a set of parallel batch cursors. The value <paramref name="n"/> is a recommended limit on /// cardinality. If <paramref name="n"/> is non-positive, this indicates that the caller has no recommendation, /// and the implementation should have some default behavior to cover this case. Note that this is strictly a /// recommendation: it is entirely possible that an implementation can return a different number of cursors. /// /// The cursors should return the same data as returned through /// <see cref="GetRowCursor(IEnumerable{DataViewSchema.Column}, Random)"/>, except partitioned: no two cursors should return the /// "same" row as would have been returned through the regular serial cursor, but all rows should be returned by /// exactly one of the cursors returned from this cursor. The cursors can have their values reconciled /// downstream through the use of the <see cref="DataViewRow.Batch"/> property. /// /// The typical usage pattern is that a set of cursors is requested, each of them is then given to a set of /// working threads that consume from them independently while, ultimately, the results are finally collated in /// the end by exploiting the ordering of the <see cref="DataViewRow.Batch"/> property described above. More typical /// scenarios will be content with pulling from the single serial cursor of /// <see cref="GetRowCursor(IEnumerable{DataViewSchema.Column}, Random)"/>. /// </summary> /// <param name="columnsNeeded">The active columns needed. If passed an empty <see cref="IEnumerable"/> no column is requested.</param> /// <param name="n">The suggested degree of parallelism.</param> /// <param name="rand">An instance of <see cref="Random"/> to seed randomizing the access.</param> /// <returns></returns> DataViewRowCursor[] GetRowCursorSet(IEnumerable<DataViewSchema.Column> columnsNeeded, int n, Random rand = null); /// <summary> /// Gets an instance of Schema. /// </summary> DataViewSchema Schema { get; } } /// <summary> /// Delegate type to get a value. This can be used for efficient access to data in a <see cref="DataViewRow"/> /// or <see cref="DataViewRowCursor"/>. /// </summary> public delegate void ValueGetter<TValue>(ref TValue value); /// <summary> /// A logical row of data. May be a row of an <see cref="IDataView"/> or a stand-alone row. /// </summary> public abstract class DataViewRow : IDisposable { /// <summary> /// This is incremented when the underlying contents changes, giving clients a way to detect change. It should be /// -1 when the object is in a state where values cannot be fetched. In particular, for an <see cref="DataViewRowCursor"/>, /// this will be before <see cref="DataViewRowCursor.MoveNext"/> if ever called for the first time, or after the first time /// <see cref="DataViewRowCursor.MoveNext"/> is called and returns <see langword="false"/>. /// /// Note that this position is not position within the underlying data, but position of this cursor only. If /// one, for example, opened a set of parallel streaming cursors, or a shuffled cursor, each such cursor's first /// valid entry would always have position 0. /// </summary> public abstract long Position { get; } /// <summary> /// This provides a means for reconciling multiple rows that have been produced generally from /// <see cref="IDataView.GetRowCursorSet(IEnumerable{DataViewSchema.Column}, int, Random)"/>. When getting a set, there is a need /// to, while allowing parallel processing to proceed, always have an aim that the original order should be /// recoverable. Note, whether or not a user cares about that original order in one's specific application is /// another story altogether (most callers of this as a practical matter do not, otherwise they would not call /// it), but at least in principle it should be possible to reconstruct the original order one would get from an /// identically configured <see cref="IDataView.GetRowCursor(IEnumerable{DataViewSchema.Column}, Random)"/>. So: for any cursor /// implementation, batch numbers should be non-decreasing. Furthermore, any given batch number should only /// appear in one of the cursors as returned by /// <see cref="IDataView.GetRowCursorSet(IEnumerable{DataViewSchema.Column}, int, Random)"/>. In this way, order is determined by /// batch number. An operation that reconciles these cursors to produce a consistent single cursoring, could do /// so by drawing from the single cursor, among all cursors in the set, that has the smallest batch number /// available. /// /// Note that there is no suggestion that the batches for a particular entry will be consistent from cursoring /// to cursoring, except for the consistency in resulting in the same overall ordering. The same entry could /// have different batch numbers from one cursoring to another. There is also no requirement that any given /// batch number must appear, at all. It is merely a mechanism for recovering ordering from a possibly arbitrary /// partitioning of the data. It also follows from this, of course, that considering the batch to be a property /// of the data is completely invalid. /// </summary> public abstract long Batch { get; } /// <summary> /// A getter for a 128-bit ID value. It is common for objects to serve multiple <see cref="DataViewRow"/> /// instances to iterate over what is supposed to be the same data, for example, in a <see cref="IDataView"/> /// a cursor set will produce the same data as a serial cursor, just partitioned, and a shuffled cursor will /// produce the same data as a serial cursor or any other shuffled cursor, only shuffled. The ID exists for /// applications that need to reconcile which entry is actually which. Ideally this ID should be unique, but for /// practical reasons, it suffices if collisions are simply extremely improbable. /// /// Note that this ID, while it must be consistent for multiple streams according to the semantics above, is not /// considered part of the data per se. So, to take the example of a data view specifically, a single data view /// must render consistent IDs across all cursorings, but there is no suggestion at all that if the "same" data /// were presented in a different data view (as by, say, being transformed, cached, saved, or whatever), that /// the IDs between the two different data views would have any discernible relationship.</summary> public abstract ValueGetter<DataViewRowId> GetIdGetter(); /// <summary> /// Returns whether the given column is active in this row. /// </summary> public abstract bool IsColumnActive(DataViewSchema.Column column); /// <summary> /// Returns a value getter delegate to fetch the value of the given <paramref name="column"/>, from the row. /// This throws if the column is not active in this row, or if the type /// <typeparamref name="TValue"/> differs from this column's type. /// </summary> /// <typeparam name="TValue"> is the column's content type.</typeparam> /// <param name="column"> is the output column whose getter should be returned.</param> public abstract ValueGetter<TValue> GetGetter<TValue>(DataViewSchema.Column column); /// <summary> /// Gets a <see cref="Schema"/>, which provides name and type information for variables /// (i.e., columns in ML.NET's type system) stored in this row. /// </summary> public abstract DataViewSchema Schema { get; } /// <summary> /// Implementation of dispose. Calls <see cref="Dispose(bool)"/> with <see langword="true"/>. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// The disposable method for the disposable pattern. This default implementation does nothing. /// </summary> /// <param name="disposing">Whether this was called from <see cref="IDisposable.Dispose"/>. /// Subclasses that implement <see cref="object.Finalize"/> should call this method with /// <see langword="false"/>, but I hasten to add that implementing finalizers should be /// avoided if at all possible.</param>. protected virtual void Dispose(bool disposing) { } } /// <summary> /// Class used to cursor through rows of an <see cref="IDataView"/>. /// </summary> /// <remarks> /// Note that this is also an <see cref="DataViewRow"/>. The <see cref="DataViewRow.Position"/> is /// incremented by <see cref="MoveNext"/>. Prior to the first call to <see cref="MoveNext"/>, or after /// <see cref="MoveNext"/> returns <see langword="false"/>, <see cref="DataViewRow.Position"/> is <c>-1</c>. /// Otherwise, when <see cref="MoveNext"/> returns <see langword="true"/>, <see cref="DataViewRow.Position"/> >= 0. /// </remarks> public abstract class DataViewRowCursor : DataViewRow { /// <summary> /// Advance to the next row. When the cursor is first created, this method should be called to /// move to the first row. Returns <see langword="false"/> if there are no more rows. /// </summary> public abstract bool MoveNext(); } }
61.375
145
0.664196
[ "MIT" ]
1Crazymoney/machinelearning
src/Microsoft.ML.DataView/IDataView.cs
12,275
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.ServiceFabricMesh.V20180901Preview.Inputs { /// <summary> /// Describes parameters for creating application-scoped volumes provided by Service Fabric Volume Disks /// </summary> public sealed class ApplicationScopedVolumeCreationParametersServiceFabricVolumeDiskArgs : Pulumi.ResourceArgs { /// <summary> /// User readable description of the volume. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// Specifies the application-scoped volume kind. /// </summary> [Input("kind", required: true)] public Input<string> Kind { get; set; } = null!; /// <summary> /// Volume size /// </summary> [Input("sizeDisk", required: true)] public Input<string> SizeDisk { get; set; } = null!; public ApplicationScopedVolumeCreationParametersServiceFabricVolumeDiskArgs() { } } }
32.121951
114
0.650721
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/ServiceFabricMesh/V20180901Preview/Inputs/ApplicationScopedVolumeCreationParametersServiceFabricVolumeDiskArgs.cs
1,317
C#
namespace VirtualRadar.WinForms { partial class AircraftOnlineLookupLogView { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if(disposing) { if(components != null) components.Dispose(); if(_Presenter != null) _Presenter.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.listView = new VirtualRadar.WinForms.Controls.ListViewPlus(); this.columnHeaderTime = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderIcao = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderRegistration = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderCountry = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderManufacturer = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderModel = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderModelIcao = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderOperator = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderOperatorIcao = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderSerial = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderYearBuilt = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.SuspendLayout(); // // listView // this.listView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.listView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeaderTime, this.columnHeaderIcao, this.columnHeaderRegistration, this.columnHeaderCountry, this.columnHeaderManufacturer, this.columnHeaderModel, this.columnHeaderModelIcao, this.columnHeaderOperator, this.columnHeaderOperatorIcao, this.columnHeaderSerial, this.columnHeaderYearBuilt}); this.listView.FullRowSelect = true; this.listView.GridLines = true; this.listView.Location = new System.Drawing.Point(13, 12); this.listView.Name = "listView"; this.listView.Size = new System.Drawing.Size(859, 457); this.listView.TabIndex = 0; this.listView.UseCompatibleStateImageBehavior = false; this.listView.View = System.Windows.Forms.View.Details; // // columnHeaderTime // this.columnHeaderTime.Text = "::Time::"; // // columnHeaderIcao // this.columnHeaderIcao.Text = "::ICAO::"; // // columnHeaderRegistration // this.columnHeaderRegistration.Text = "::Reg::"; this.columnHeaderRegistration.Width = 80; // // columnHeaderCountry // this.columnHeaderCountry.Text = "::Country::"; this.columnHeaderCountry.Width = 90; // // columnHeaderManufacturer // this.columnHeaderManufacturer.Text = "::Manufacturer::"; this.columnHeaderManufacturer.Width = 92; // // columnHeaderModel // this.columnHeaderModel.Text = "::Model::"; this.columnHeaderModel.Width = 123; // // columnHeaderModelIcao // this.columnHeaderModelIcao.Text = "::ICAO::"; this.columnHeaderModelIcao.Width = 51; // // columnHeaderOperator // this.columnHeaderOperator.Text = "::Operator::"; this.columnHeaderOperator.Width = 120; // // columnHeaderOperatorIcao // this.columnHeaderOperatorIcao.Text = "::ICAO::"; this.columnHeaderOperatorIcao.Width = 50; // // columnHeaderSerial // this.columnHeaderSerial.Text = "::Serial::"; // // columnHeaderYearBuilt // this.columnHeaderYearBuilt.Text = "::Year::"; this.columnHeaderYearBuilt.Width = 47; // // AircraftOnlineLookupLogView // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(884, 482); this.Controls.Add(this.listView); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "AircraftOnlineLookupLogView"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "::AircraftDetailOnlineLookupLog::"; this.ResumeLayout(false); } #endregion private Controls.ListViewPlus listView; private System.Windows.Forms.ColumnHeader columnHeaderTime; private System.Windows.Forms.ColumnHeader columnHeaderIcao; private System.Windows.Forms.ColumnHeader columnHeaderRegistration; private System.Windows.Forms.ColumnHeader columnHeaderCountry; private System.Windows.Forms.ColumnHeader columnHeaderManufacturer; private System.Windows.Forms.ColumnHeader columnHeaderModel; private System.Windows.Forms.ColumnHeader columnHeaderModelIcao; private System.Windows.Forms.ColumnHeader columnHeaderOperator; private System.Windows.Forms.ColumnHeader columnHeaderOperatorIcao; private System.Windows.Forms.ColumnHeader columnHeaderSerial; private System.Windows.Forms.ColumnHeader columnHeaderYearBuilt; } }
47.012903
158
0.597502
[ "BSD-3-Clause" ]
AlexAX135/vrs
VirtualRadar.WinForms/AircraftOnlineLookupLogView.Designer.cs
7,289
C#
using UnityEngine; using PureCheat.API; namespace PureCheat.Addons { public class RemoveItems : PureModSystem { public override string ModName => "Remove items"; public override void OnUpdate() { if (Input.GetKey(KeyCode.LeftAlt) && Input.GetMouseButton(1) && Input.GetMouseButtonDown(0)) { GameObject playerCamera = PureUtils.GetLocalPlayerCamera(); Ray ray = new Ray(playerCamera.transform.position, playerCamera.transform.forward); RaycastHit[] hits = Physics.RaycastAll(ray); if (hits.Length > 0) { RaycastHit raycastHit = hits[0]; GameObject.Destroy(raycastHit.transform.gameObject); } } } } }
30.333333
104
0.567766
[ "MIT" ]
DanteOtter/PureCheat
PureCheat/PureCheat/Addons/RemoveItems.cs
821
C#
using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; namespace WebApi { public static class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args).ConfigureAppConfiguration((context, builder) => builder.SetBasePath(context.HostingEnvironment.ContentRootPath)). UseStartup<Startup>(); } }
29.3
95
0.674061
[ "MIT" ]
Avertere7/floiir
backend/WebApi/Program.cs
588
C#
// // Options.cs // // Authors: // Jonathan Pryor <jpryor@novell.com>, <Jonathan.Pryor@microsoft.com> // Federico Di Gregorio <fog@initd.org> // Rolf Bjarne Kvinge <rolf@xamarin.com> // // Copyright (C) 2008 Novell (http://www.novell.com) // Copyright (C) 2009 Federico Di Gregorio. // Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com) // Copyright (C) 2017 Microsoft Corporation (http://www.microsoft.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. // // Compile With: // mcs -debug+ -r:System.Core Options.cs -o:Mono.Options.dll -t:library // mcs -debug+ -d:LINQ -r:System.Core Options.cs -o:Mono.Options.dll -t:library // // The LINQ version just changes the implementation of // OptionSet.Parse(IEnumerable<string>), and confers no semantic changes. // // A Getopt::Long-inspired option parsing library for C#. // // Mono.Options.OptionSet is built upon a key/value table, where the // key is a option format string and the value is a delegate that is // invoked when the format string is matched. // // Option format strings: // Regex-like BNF Grammar: // name: .+ // type: [=:] // sep: ( [^{}]+ | '{' .+ '}' )? // aliases: ( name type sep ) ( '|' name type sep )* // // Each '|'-delimited name is an alias for the associated action. If the // format string ends in a '=', it has a required value. If the format // string ends in a ':', it has an optional value. If neither '=' or ':' // is present, no value is supported. `=' or `:' need only be defined on one // alias, but if they are provided on more than one they must be consistent. // // Each alias portion may also end with a "key/value separator", which is used // to split option values if the option accepts > 1 value. If not specified, // it defaults to '=' and ':'. If specified, it can be any character except // '{' and '}' OR the *string* between '{' and '}'. If no separator should be // used (i.e. the separate values should be distinct arguments), then "{}" // should be used as the separator. // // Options are extracted either from the current option by looking for // the option name followed by an '=' or ':', or is taken from the // following option IFF: // - The current option does not contain a '=' or a ':' // - The current option requires a value (i.e. not a Option type of ':') // // The `name' used in the option format string does NOT include any leading // option indicator, such as '-', '--', or '/'. All three of these are // permitted/required on any named option. // // Option bundling is permitted so long as: // - '-' is used to start the option group // - all of the bundled options are a single character // - at most one of the bundled options accepts a value, and the value // provided starts from the next character to the end of the string. // // This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value' // as '-Dname=value'. // // Option processing is disabled by specifying "--". All options after "--" // are returned by OptionSet.Parse() unchanged and unprocessed. // // Unprocessed options are returned from OptionSet.Parse(). // // Examples: // int verbose = 0; // OptionSet p = new OptionSet () // .Add ("v", v => ++verbose) // .Add ("name=|value=", v => Console.WriteLine (v)); // p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"}); // // The above would parse the argument string array, and would invoke the // lambda expression three times, setting `verbose' to 3 when complete. // It would also print out "A" and "B" to standard output. // The returned array would contain the string "extra". // // C# 3.0 collection initializers are supported and encouraged: // var p = new OptionSet () { // { "h|?|help", v => ShowHelp () }, // }; // // System.ComponentModel.TypeConverter is also supported, allowing the use of // custom data types in the callback type; TypeConverter.ConvertFromString() // is used to convert the value option to an instance of the specified // type: // // var p = new OptionSet () { // { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) }, // }; // // Random other tidbits: // - Boolean options (those w/o '=' or ':' in the option format string) // are explicitly enabled if they are followed with '+', and explicitly // disabled if they are followed with '-': // string a = null; // var p = new OptionSet () { // { "a", s => a = s }, // }; // p.Parse (new string[]{"-a"}); // sets v != null // p.Parse (new string[]{"-a+"}); // sets v != null // p.Parse (new string[]{"-a-"}); // sets v is null // // // Mono.Options.CommandSet allows easily having separate commands and // associated command options, allowing creation of a *suite* along the // lines of **git**(1), **svn**(1), etc. // // CommandSet allows intermixing plain text strings for `--help` output, // Option values -- as supported by OptionSet -- and Command instances, // which have a name, optional help text, and an optional OptionSet. // // var suite = new CommandSet ("suite-name") { // // Use strings and option values, as with OptionSet // "usage: suite-name COMMAND [OPTIONS]+", // { "v:", "verbosity", (int? v) => Verbosity = v.HasValue ? v.Value : Verbosity+1 }, // // Commands may also be specified // new Command ("command-name", "command help") { // Options = new OptionSet {/*...*/}, // Run = args => { /*...*/}, // }, // new MyCommandSubclass (), // }; // return suite.Run (new string[]{...}); // // CommandSet provides a `help` command, and forwards `help COMMAND` // to the registered Command instance by invoking Command.Invoke() // with `--help` as an option. // using System; using System.Collections.Generic; using System.Text; namespace Mono.Options { public static class StringCoda { public static IEnumerable<string> WrappedLines(string self, params int[] widths) { IEnumerable<int> w = widths; return WrappedLines(self, w); } public static IEnumerable<string> WrappedLines(string self, IEnumerable<int> widths) { if (widths is null) { throw new ArgumentNullException(nameof(widths)); } return CreateWrappedLinesIterator(self, widths); } private static IEnumerable<string> CreateWrappedLinesIterator(string self, IEnumerable<int> widths) { if (string.IsNullOrEmpty(self)) { yield return string.Empty; yield break; } using IEnumerator<int> eWidths = widths.GetEnumerator(); bool? hw = null; int width = GetNextWidth(eWidths, int.MaxValue, ref hw); int start = 0, end; do { end = GetLineEnd(start, width, self); char c = self[end - 1]; if (char.IsWhiteSpace(c)) { --end; } bool needContinuation = end != self.Length && !IsEolChar(c); string continuation = ""; if (needContinuation) { --end; continuation = "-"; } string line = self[start..end] + continuation; yield return line; start = end; if (char.IsWhiteSpace(c)) { ++start; } width = GetNextWidth(eWidths, width, ref hw); } while (start < self.Length); } private static int GetNextWidth(IEnumerator<int> eWidths, int curWidth, ref bool? eValid) { if (!eValid.HasValue || (eValid.HasValue && eValid.Value)) { curWidth = (eValid = eWidths.MoveNext()).Value ? eWidths.Current : curWidth; // '.' is any character, - is for a continuation const string minWidth = ".-"; if (curWidth < minWidth.Length) { throw new ArgumentOutOfRangeException("widths", $"Element must be greater than or equal to {minWidth.Length}, was {curWidth}."); } return curWidth; } // no more elements, use the last element. return curWidth; } private static bool IsEolChar(char c) { return !char.IsLetterOrDigit(c); } private static int GetLineEnd(int start, int length, string description) { int end = Math.Min(start + length, description.Length); int sep = -1; for (int i = start; i < end; ++i) { if (description[i] == '\n') { return i + 1; } if (IsEolChar(description[i])) { sep = i + 1; } } if (sep == -1 || end == description.Length) { return end; } return sep; } } }
34.340741
101
0.654228
[ "MIT" ]
adamlaska/WalletWasabi
WalletWasabi/Mono/StringCoda.cs
9,272
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CodeCleanup; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> : IAddImportFeatureService, IEqualityComparer<PortableExecutableReference> where TSimpleNameSyntax : SyntaxNode { protected abstract bool CanAddImport(SyntaxNode node, bool allowInHiddenRegions, CancellationToken cancellationToken); protected abstract bool CanAddImportForMethod(string diagnosticId, ISyntaxFacts syntaxFacts, SyntaxNode node, out TSimpleNameSyntax nameNode); protected abstract bool CanAddImportForNamespace(string diagnosticId, SyntaxNode node, out TSimpleNameSyntax nameNode); protected abstract bool CanAddImportForDeconstruct(string diagnosticId, SyntaxNode node); protected abstract bool CanAddImportForGetAwaiter(string diagnosticId, ISyntaxFacts syntaxFactsService, SyntaxNode node); protected abstract bool CanAddImportForGetEnumerator(string diagnosticId, ISyntaxFacts syntaxFactsService, SyntaxNode node); protected abstract bool CanAddImportForGetAsyncEnumerator(string diagnosticId, ISyntaxFacts syntaxFactsService, SyntaxNode node); protected abstract bool CanAddImportForQuery(string diagnosticId, SyntaxNode node); protected abstract bool CanAddImportForType(string diagnosticId, SyntaxNode node, out TSimpleNameSyntax nameNode); protected abstract ISet<INamespaceSymbol> GetImportNamespacesInScope(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken); protected abstract ITypeSymbol GetDeconstructInfo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken); protected abstract ITypeSymbol GetQueryClauseInfo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken); protected abstract bool IsViableExtensionMethod(IMethodSymbol method, SyntaxNode expression, SemanticModel semanticModel, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken); protected abstract Task<Document> AddImportAsync(SyntaxNode contextNode, INamespaceOrTypeSymbol symbol, Document document, AddImportPlacementOptions options, CancellationToken cancellationToken); protected abstract Task<Document> AddImportAsync(SyntaxNode contextNode, IReadOnlyList<string> nameSpaceParts, Document document, AddImportPlacementOptions options, CancellationToken cancellationToken); protected abstract bool IsAddMethodContext(SyntaxNode node, SemanticModel semanticModel); protected abstract string GetDescription(IReadOnlyList<string> nameParts); protected abstract (string description, bool hasExistingImport) GetDescription(Document document, AddImportPlacementOptions options, INamespaceOrTypeSymbol symbol, SemanticModel semanticModel, SyntaxNode root, CancellationToken cancellationToken); public async Task<ImmutableArray<AddImportFixData>> GetFixesAsync( Document document, TextSpan span, string diagnosticId, int maxResults, ISymbolSearchService symbolSearchService, AddImportOptions options, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(document.Project, cancellationToken).ConfigureAwait(false); if (client != null) { var result = await client.TryInvokeAsync<IRemoteMissingImportDiscoveryService, ImmutableArray<AddImportFixData>>( document.Project.Solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetFixesAsync(solutionInfo, callbackId, document.Id, span, diagnosticId, maxResults, options, packageSources, cancellationToken), callbackTarget: symbolSearchService, cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<AddImportFixData>.Empty; } return await GetFixesInCurrentProcessAsync( document, span, diagnosticId, maxResults, symbolSearchService, options, packageSources, cancellationToken).ConfigureAwait(false); } private async Task<ImmutableArray<AddImportFixData>> GetFixesInCurrentProcessAsync( Document document, TextSpan span, string diagnosticId, int maxResults, ISymbolSearchService symbolSearchService, AddImportOptions options, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var node = root.FindToken(span.Start, findInsideTrivia: true) .GetAncestor(n => n.Span.Contains(span) && n != root); using var _ = ArrayBuilder<AddImportFixData>.GetInstance(out var result); if (node != null) { using (Logger.LogBlock(FunctionId.Refactoring_AddImport, cancellationToken)) { if (!cancellationToken.IsCancellationRequested) { if (CanAddImport(node, options.CleanupOptions.AddImportOptions.AllowInHiddenRegions, cancellationToken)) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var allSymbolReferences = await FindResultsAsync( document, semanticModel, diagnosticId, node, maxResults, symbolSearchService, options, packageSources, cancellationToken).ConfigureAwait(false); // Nothing found at all. No need to proceed. foreach (var reference in allSymbolReferences) { cancellationToken.ThrowIfCancellationRequested(); var fixData = await reference.TryGetFixDataAsync(document, node, options.CleanupOptions, cancellationToken).ConfigureAwait(false); result.AddIfNotNull(fixData); } } } } } return result.ToImmutable(); } private async Task<ImmutableArray<Reference>> FindResultsAsync( Document document, SemanticModel semanticModel, string diagnosticId, SyntaxNode node, int maxResults, ISymbolSearchService symbolSearchService, AddImportOptions options, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { // Caches so we don't produce the same data multiple times while searching // all over the solution. var project = document.Project; var projectToAssembly = new ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>>(concurrencyLevel: 2, capacity: project.Solution.ProjectIds.Count); var referenceToCompilation = new ConcurrentDictionary<PortableExecutableReference, Compilation>(concurrencyLevel: 2, capacity: project.Solution.Projects.Sum(p => p.MetadataReferences.Count)); var finder = new SymbolReferenceFinder( this, document, semanticModel, diagnosticId, node, symbolSearchService, options, packageSources, cancellationToken); // Look for exact matches first: var exactReferences = await FindResultsAsync(projectToAssembly, referenceToCompilation, project, maxResults, finder, exact: true, cancellationToken: cancellationToken).ConfigureAwait(false); if (exactReferences.Length > 0) { return exactReferences; } // No exact matches found. Fall back to fuzzy searching. // Only bother doing this for host workspaces. We don't want this for // things like the Interactive workspace as this will cause us to // create expensive bk-trees which we won't even be able to save for // future use. if (!IsHostOrRemoteWorkspace(project)) { return ImmutableArray<Reference>.Empty; } var fuzzyReferences = await FindResultsAsync(projectToAssembly, referenceToCompilation, project, maxResults, finder, exact: false, cancellationToken: cancellationToken).ConfigureAwait(false); return fuzzyReferences; } private static bool IsHostOrRemoteWorkspace(Project project) => project.Solution.Workspace.Kind is WorkspaceKind.Host or WorkspaceKind.RemoteWorkspace; private async Task<ImmutableArray<Reference>> FindResultsAsync( ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>> projectToAssembly, ConcurrentDictionary<PortableExecutableReference, Compilation> referenceToCompilation, Project project, int maxResults, SymbolReferenceFinder finder, bool exact, CancellationToken cancellationToken) { using var _ = ArrayBuilder<Reference>.GetInstance(out var allReferences); // First search the current project to see if any symbols (source or metadata) match the // search string. await FindResultsInAllSymbolsInStartingProjectAsync( allReferences, maxResults, finder, exact, cancellationToken).ConfigureAwait(false); // Only bother doing this for host workspaces. We don't want this for // things like the Interactive workspace as we can't even add project // references to the interactive window. We could consider adding metadata // references with #r in the future. if (IsHostOrRemoteWorkspace(project)) { // Now search unreferenced projects, and see if they have any source symbols that match // the search string. await FindResultsInUnreferencedProjectSourceSymbolsAsync(projectToAssembly, project, allReferences, maxResults, finder, exact, cancellationToken).ConfigureAwait(false); // Finally, check and see if we have any metadata symbols that match the search string. await FindResultsInUnreferencedMetadataSymbolsAsync(referenceToCompilation, project, allReferences, maxResults, finder, exact, cancellationToken).ConfigureAwait(false); // We only support searching NuGet in an exact manner currently. if (exact) { await finder.FindNugetOrReferenceAssemblyReferencesAsync(allReferences, cancellationToken).ConfigureAwait(false); } } return allReferences.ToImmutable(); } private static async Task FindResultsInAllSymbolsInStartingProjectAsync( ArrayBuilder<Reference> allSymbolReferences, int maxResults, SymbolReferenceFinder finder, bool exact, CancellationToken cancellationToken) { var references = await finder.FindInAllSymbolsInStartingProjectAsync(exact, cancellationToken).ConfigureAwait(false); AddRange(allSymbolReferences, references, maxResults); } private static async Task FindResultsInUnreferencedProjectSourceSymbolsAsync( ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>> projectToAssembly, Project project, ArrayBuilder<Reference> allSymbolReferences, int maxResults, SymbolReferenceFinder finder, bool exact, CancellationToken cancellationToken) { // If we didn't find enough hits searching just in the project, then check // in any unreferenced projects. if (allSymbolReferences.Count >= maxResults) { return; } var viableUnreferencedProjects = GetViableUnreferencedProjects(project); // Search all unreferenced projects in parallel. var findTasks = new HashSet<Task<ImmutableArray<SymbolReference>>>(); // Create another cancellation token so we can both search all projects in parallel, // but also stop any searches once we get enough results. using var nestedTokenSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(nestedTokenSource.Token, cancellationToken); foreach (var unreferencedProject in viableUnreferencedProjects) { // Search in this unreferenced project. But don't search in any of its' // direct references. i.e. we don't want to search in its metadata references // or in the projects it references itself. We'll be searching those entities // individually. findTasks.Add(finder.FindInSourceSymbolsInProjectAsync( projectToAssembly, unreferencedProject, exact, linkedTokenSource.Token)); } await WaitForTasksAsync(allSymbolReferences, maxResults, findTasks, nestedTokenSource, cancellationToken).ConfigureAwait(false); } private async Task FindResultsInUnreferencedMetadataSymbolsAsync( ConcurrentDictionary<PortableExecutableReference, Compilation> referenceToCompilation, Project project, ArrayBuilder<Reference> allSymbolReferences, int maxResults, SymbolReferenceFinder finder, bool exact, CancellationToken cancellationToken) { if (allSymbolReferences.Count > 0) { // Only do this if none of the project searches produced any results. We may have a // lot of metadata to search through, and it would be good to avoid that if we can. return; } // Keep track of the references we've seen (so that we don't process them multiple times // across many sibling projects). Prepopulate it with our own metadata references since // we know we don't need to search in that. var seenReferences = new HashSet<PortableExecutableReference>(comparer: this); seenReferences.AddAll(project.MetadataReferences.OfType<PortableExecutableReference>()); var newReferences = GetUnreferencedMetadataReferences(project, seenReferences); // Search all metadata references in parallel. var findTasks = new HashSet<Task<ImmutableArray<SymbolReference>>>(); // Create another cancellation token so we can both search all projects in parallel, // but also stop any searches once we get enough results. using var nestedTokenSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(nestedTokenSource.Token, cancellationToken); foreach (var (referenceProjectId, reference) in newReferences) { var compilation = referenceToCompilation.GetOrAdd( reference, r => CreateCompilation(project, r)); // Ignore netmodules. First, they're incredibly esoteric and barely used. // Second, the SymbolFinder API doesn't even support searching them. if (compilation.GetAssemblyOrModuleSymbol(reference) is IAssemblySymbol assembly) { findTasks.Add(finder.FindInMetadataSymbolsAsync( assembly, referenceProjectId, reference, exact, linkedTokenSource.Token)); } } await WaitForTasksAsync(allSymbolReferences, maxResults, findTasks, nestedTokenSource, cancellationToken).ConfigureAwait(false); } /// <summary> /// Returns the set of PEReferences in the solution that are not currently being referenced /// by this project. The set returned will be tuples containing the PEReference, and the project-id /// for the project we found the pe-reference in. /// </summary> private static ImmutableArray<(ProjectId, PortableExecutableReference)> GetUnreferencedMetadataReferences( Project project, HashSet<PortableExecutableReference> seenReferences) { var result = ArrayBuilder<(ProjectId, PortableExecutableReference)>.GetInstance(); var solution = project.Solution; foreach (var p in solution.Projects) { if (p == project) { continue; } foreach (var reference in p.MetadataReferences) { if (reference is PortableExecutableReference peReference && !IsInPackagesDirectory(peReference) && seenReferences.Add(peReference)) { result.Add((p.Id, peReference)); } } } return result.ToImmutableAndFree(); } private static async Task WaitForTasksAsync( ArrayBuilder<Reference> allSymbolReferences, int maxResults, HashSet<Task<ImmutableArray<SymbolReference>>> findTasks, CancellationTokenSource nestedTokenSource, CancellationToken cancellationToken) { try { while (findTasks.Count > 0) { // Keep on looping through the 'find' tasks, processing each when they finish. cancellationToken.ThrowIfCancellationRequested(); var doneTask = await Task.WhenAny(findTasks).ConfigureAwait(false); // One of the tasks finished. Remove it from the list we're waiting on. findTasks.Remove(doneTask); // Add its results to the final result set we're keeping. AddRange(allSymbolReferences, await doneTask.ConfigureAwait(false), maxResults); // Once we get enough, just stop. if (allSymbolReferences.Count >= maxResults) { return; } } } finally { // Cancel any nested work that's still happening. nestedTokenSource.Cancel(); } } /// <summary> /// We ignore references that are in a directory that contains the names /// "Packages", "packs", "NuGetFallbackFolder", or "NuGetPackages" /// These directories are most likely the ones produced by NuGet, and we don't want /// to offer to add .dll reference manually for dlls that are part of NuGet packages. /// /// Note that this is only a heuristic (though a good one), and we should remove this /// when we can get an API from NuGet that tells us if a reference is actually provided /// by a nuget packages. /// Tracking issue: https://github.com/dotnet/project-system/issues/5275 /// /// This heuristic will do the right thing in practically all cases for all. It /// prevents the very unpleasant experience of us offering to add a direct metadata /// reference to something that should only be referenced as a nuget package. /// /// It does mean that if the following is true: /// You have a project that has a non-nuget metadata reference to something in a "packages" /// directory, and you are in another project that uses a type name that would have matched /// an accessible type from that dll. then we will not offer to add that .dll reference to /// that other project. /// /// However, that would be an exceedingly uncommon case that is degraded. Whereas we're /// vastly improved in the common case. This is a totally acceptable and desirable outcome /// for such a heuristic. /// </summary> private static bool IsInPackagesDirectory(PortableExecutableReference reference) { return ContainsPathComponent(reference, "packages") || ContainsPathComponent(reference, "packs") || ContainsPathComponent(reference, "NuGetFallbackFolder") || ContainsPathComponent(reference, "NuGetPackages"); static bool ContainsPathComponent(PortableExecutableReference reference, string pathComponent) { return PathUtilities.ContainsPathComponent(reference.FilePath, pathComponent, ignoreCase: true); } } /// <summary> /// Called when we want to search a metadata reference. We create a dummy compilation /// containing just that reference and we search that. That way we can get actual symbols /// returned. /// /// We don't want to use the project that the reference is actually associated with as /// getting the compilation for that project may be extremely expensive. For example, /// in a large solution it may cause us to build an enormous amount of skeleton assemblies. /// </summary> private static Compilation CreateCompilation(Project project, PortableExecutableReference reference) { var compilationService = project.LanguageServices.GetRequiredService<ICompilationFactoryService>(); var compilation = compilationService.CreateCompilation("TempAssembly", compilationService.GetDefaultCompilationOptions()); return compilation.WithReferences(reference); } bool IEqualityComparer<PortableExecutableReference>.Equals(PortableExecutableReference? x, PortableExecutableReference? y) { if (x == y) return true; var path1 = x?.FilePath ?? x?.Display; var path2 = y?.FilePath ?? y?.Display; if (path1 == null || path2 == null) return false; return StringComparer.OrdinalIgnoreCase.Equals(path1, path2); } int IEqualityComparer<PortableExecutableReference>.GetHashCode(PortableExecutableReference obj) { var path = obj.FilePath ?? obj.Display; return path == null ? 0 : StringComparer.OrdinalIgnoreCase.GetHashCode(path); } private static HashSet<Project> GetViableUnreferencedProjects(Project project) { var solution = project.Solution; var viableProjects = new HashSet<Project>(solution.Projects); // Clearly we can't reference ourselves. viableProjects.Remove(project); // We can't reference any project that transitively depends on us. Doing so would // cause a circular reference between projects. var dependencyGraph = solution.GetProjectDependencyGraph(); var projectsThatTransitivelyDependOnThisProject = dependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(project.Id); viableProjects.RemoveAll(projectsThatTransitivelyDependOnThisProject.Select(id => solution.GetRequiredProject(id))); // We also aren't interested in any projects we're already directly referencing. viableProjects.RemoveAll(project.ProjectReferences.Select(r => solution.GetRequiredProject(r.ProjectId))); return viableProjects; } private static void AddRange<TReference>(ArrayBuilder<Reference> allSymbolReferences, ImmutableArray<TReference> proposedReferences, int maxResults) where TReference : Reference { allSymbolReferences.AddRange(proposedReferences.Take(maxResults - allSymbolReferences.Count)); } protected static bool IsViableExtensionMethod(IMethodSymbol method, ITypeSymbol receiver) { if (receiver == null || method == null) { return false; } // It's possible that the 'method' we're looking at is from a different language than // the language we're currently in. For example, we might find the extension method // in an unreferenced VB project while we're in C#. However, in order to 'reduce' // the extension method, the compiler requires both the method and receiver to be // from the same language. // // So, if they're not from the same language, we simply can't proceed. Now in this // case we decide that the method is not viable. But we could, in the future, decide // to just always consider such methods viable. if (receiver.Language != method.Language) { return false; } return method.ReduceExtensionMethod(receiver) != null; } private static bool NotGlobalNamespace(SymbolReference reference) { var symbol = reference.SymbolResult.Symbol; return symbol.IsNamespace ? !((INamespaceSymbol)symbol).IsGlobalNamespace : true; } private static bool NotNull(SymbolReference reference) => reference.SymbolResult.Symbol != null; public async Task<ImmutableArray<(Diagnostic Diagnostic, ImmutableArray<AddImportFixData> Fixes)>> GetFixesForDiagnosticsAsync( Document document, TextSpan span, ImmutableArray<Diagnostic> diagnostics, int maxResultsPerDiagnostic, ISymbolSearchService symbolSearchService, AddImportOptions options, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { // We might have multiple different diagnostics covering the same span. Have to // process them all as we might produce different fixes for each diagnostic. var fixesForDiagnosticBuilder = ArrayBuilder<(Diagnostic, ImmutableArray<AddImportFixData>)>.GetInstance(); foreach (var diagnostic in diagnostics) { var fixes = await GetFixesAsync( document, span, diagnostic.Id, maxResultsPerDiagnostic, symbolSearchService, options, packageSources, cancellationToken).ConfigureAwait(false); fixesForDiagnosticBuilder.Add((diagnostic, fixes)); } return fixesForDiagnosticBuilder.ToImmutableAndFree(); } public async Task<ImmutableArray<AddImportFixData>> GetUniqueFixesAsync( Document document, TextSpan span, ImmutableArray<string> diagnosticIds, ISymbolSearchService symbolSearchService, AddImportOptions options, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(document.Project, cancellationToken).ConfigureAwait(false); if (client != null) { var result = await client.TryInvokeAsync<IRemoteMissingImportDiscoveryService, ImmutableArray<AddImportFixData>>( document.Project.Solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetUniqueFixesAsync(solutionInfo, callbackId, document.Id, span, diagnosticIds, options, packageSources, cancellationToken), callbackTarget: symbolSearchService, cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<AddImportFixData>.Empty; } return await GetUniqueFixesAsyncInCurrentProcessAsync( document, span, diagnosticIds, symbolSearchService, options, packageSources, cancellationToken).ConfigureAwait(false); } private async Task<ImmutableArray<AddImportFixData>> GetUniqueFixesAsyncInCurrentProcessAsync( Document document, TextSpan span, ImmutableArray<string> diagnosticIds, ISymbolSearchService symbolSearchService, AddImportOptions options, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); // Get the diagnostics that indicate a missing import. var diagnostics = semanticModel.GetDiagnostics(span, cancellationToken) .Where(diagnostic => diagnosticIds.Contains(diagnostic.Id)) .ToImmutableArray(); var getFixesForDiagnosticsTasks = diagnostics .GroupBy(diagnostic => diagnostic.Location.SourceSpan) .Select(diagnosticsForSourceSpan => GetFixesForDiagnosticsAsync( document, diagnosticsForSourceSpan.Key, diagnosticsForSourceSpan.AsImmutable(), maxResultsPerDiagnostic: 2, symbolSearchService, options, packageSources, cancellationToken)); using var _ = ArrayBuilder<AddImportFixData>.GetInstance(out var fixes); foreach (var getFixesForDiagnosticsTask in getFixesForDiagnosticsTasks) { var fixesForDiagnostics = await getFixesForDiagnosticsTask.ConfigureAwait(false); foreach (var fixesForDiagnostic in fixesForDiagnostics) { // When there is more than one potential fix for a missing import diagnostic, // which is possible when the same class name is present in multiple namespaces, // we do not want to choose for the user and be wrong. We will not attempt to // fix this diagnostic and instead leave it for the user to resolve since they // will have more context for determining the proper fix. if (fixesForDiagnostic.Fixes.Length == 1) fixes.Add(fixesForDiagnostic.Fixes[0]); } } return fixes.ToImmutable(); } public ImmutableArray<CodeAction> GetCodeActionsForFixes( Document document, ImmutableArray<AddImportFixData> fixes, IPackageInstallerService? installerService, int maxResults) { var codeActionsBuilder = ArrayBuilder<CodeAction>.GetInstance(); foreach (var fix in fixes) { var codeAction = TryCreateCodeAction(document, fix, installerService); codeActionsBuilder.AddIfNotNull(codeAction); if (codeActionsBuilder.Count >= maxResults) { break; } } return codeActionsBuilder.ToImmutableAndFree(); } private static CodeAction? TryCreateCodeAction(Document document, AddImportFixData fixData, IPackageInstallerService? installerService) => fixData.Kind switch { AddImportFixKind.ProjectSymbol => new ProjectSymbolReferenceCodeAction(document, fixData), AddImportFixKind.MetadataSymbol => new MetadataSymbolReferenceCodeAction(document, fixData), AddImportFixKind.ReferenceAssemblySymbol => new AssemblyReferenceCodeAction(document, fixData), AddImportFixKind.PackageSymbol => installerService?.IsInstalled(document.Project.Solution.Workspace, document.Project.Id, fixData.PackageName) == false ? new ParentInstallPackageCodeAction(document, fixData, installerService) : null, _ => throw ExceptionUtilities.Unreachable, }; private static ITypeSymbol? GetAwaitInfo(SemanticModel semanticModel, ISyntaxFacts syntaxFactsService, SyntaxNode node) { var awaitExpression = FirstAwaitExpressionAncestor(syntaxFactsService, node); if (awaitExpression is null) return null; Debug.Assert(syntaxFactsService.IsAwaitExpression(awaitExpression)); var innerExpression = syntaxFactsService.GetExpressionOfAwaitExpression(awaitExpression); return semanticModel.GetTypeInfo(innerExpression).Type; } private static ITypeSymbol? GetCollectionExpressionType(SemanticModel semanticModel, ISyntaxFacts syntaxFactsService, SyntaxNode node) { var collectionExpression = FirstForeachCollectionExpressionAncestor(syntaxFactsService, node); if (collectionExpression is null) { return null; } return semanticModel.GetTypeInfo(collectionExpression).Type; } protected static bool AncestorOrSelfIsAwaitExpression(ISyntaxFacts syntaxFactsService, SyntaxNode node) => FirstAwaitExpressionAncestor(syntaxFactsService, node) != null; private static SyntaxNode? FirstAwaitExpressionAncestor(ISyntaxFacts syntaxFactsService, SyntaxNode node) => node.FirstAncestorOrSelf<SyntaxNode, ISyntaxFacts>((n, syntaxFactsService) => syntaxFactsService.IsAwaitExpression(n), syntaxFactsService); private static SyntaxNode? FirstForeachCollectionExpressionAncestor(ISyntaxFacts syntaxFactsService, SyntaxNode node) => node.FirstAncestorOrSelf<SyntaxNode, ISyntaxFacts>((n, syntaxFactsService) => syntaxFactsService.IsExpressionOfForeach(n), syntaxFactsService); } }
54.446009
255
0.668104
[ "MIT" ]
AlexanderSemenyak/roslyn
src/Features/Core/Portable/AddImport/AbstractAddImportFeatureService.cs
34,793
C#
using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json.Linq; using PnP.Core.Model; using PnP.Core.Model.SharePoint; using PnP.Core.QueryModel; using PnP.Core.Transformation.Model; using PnP.Core.Transformation.Services.MappingProviders; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; namespace PnP.Core.Transformation.Services.Core { /// <summary> /// Implements the concrete PageGenerator (this is the core of PnP Transformation Framework) /// </summary> public class DefaultPageGenerator : IPageGenerator { private readonly ILogger<DefaultPageGenerator> logger; private readonly PageTransformationOptions defaultPageTransformationOptions; private readonly IMemoryCache memoryCache; private readonly IServiceProvider serviceProvider; private readonly TokenParser tokenParser; /// <summary> /// Constructor with DI support /// </summary> /// <param name="logger">The logger interface</param> /// <param name="pageTransformationOptions">The options</param> /// <param name="serviceProvider">Service provider</param> public DefaultPageGenerator( ILogger<DefaultPageGenerator> logger, IOptions<PageTransformationOptions> pageTransformationOptions, IServiceProvider serviceProvider) { this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); this.defaultPageTransformationOptions = pageTransformationOptions?.Value ?? throw new ArgumentNullException(nameof(pageTransformationOptions)); this.serviceProvider = serviceProvider; this.memoryCache = this.serviceProvider.GetService<IMemoryCache>(); this.tokenParser = this.serviceProvider.GetService<TokenParser>(); } /// <summary> /// Translates the provided input into a page /// </summary> /// <param name="context">Page transformation options</param> /// <param name="mappingOutput">The mapping provider output</param> /// <param name="targetPageUri">The url for the target page</param> /// <param name="token">Cancellation token</param> /// <returns>The result of the page generation</returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentException"></exception> /// <exception cref="ApplicationException"></exception> public async Task<PageGeneratorOutput> GenerateAsync(PageTransformationContext context, MappingProviderOutput mappingOutput, Uri targetPageUri, CancellationToken token = default) { #region Validate input arguments if (context == null) { throw new ArgumentNullException(nameof(context)); } if (mappingOutput == null) { throw new ArgumentNullException(nameof(mappingOutput)); } if (targetPageUri == null) { throw new ArgumentNullException(nameof(targetPageUri)); } #endregion var result = new PageGeneratorOutput(); #region Validate target site // Ensure to have the needed target web properties var targetWeb = context.Task.TargetContext.Web; await targetWeb.EnsurePropertiesAsync(w => w.WebTemplate).ConfigureAwait(false); // Check target site if (targetWeb.WebTemplate != "SITEPAGEPUBLISHING" && targetWeb.WebTemplate != "STS" && targetWeb.WebTemplate != "GROUP" && targetWeb.WebTemplate != "BDR" && targetWeb.WebTemplate != "DEV") { logger.LogError( TransformationResources.Error_CrossSiteTransferTargetsNonModernSite .CorrelateString(context.Task.Id)); throw new ArgumentException(TransformationResources.Error_CrossSiteTransferTargetsNonModernSite); } #endregion #region Validate and create the target page // Ensure PostAsNews is used together with PagePublishing if (this.defaultPageTransformationOptions.PostAsNews && !this.defaultPageTransformationOptions.PublishPage) { this.defaultPageTransformationOptions.PublishPage = true; logger.LogWarning( TransformationResources.Warning_PostingAPageAsNewsRequiresPagePublishing .CorrelateString(context.Task.Id)); } // Check if the target page already exists string targetPageUriString = targetPageUri.IsAbsoluteUri ? targetPageUri.AbsolutePath : targetPageUri.ToString(); IFile targetFile = null; var targetFileExists = false; try { targetFile = await targetWeb.GetFileByServerRelativeUrlAsync(targetPageUriString).ConfigureAwait(false); targetFileExists = true; } catch (SharePointRestServiceException) { // Simply ignore this exception and assume that the page does not exist targetFileExists = false; } if (targetFileExists) { logger.LogInformation( TransformationResources.Info_PageAlreadyExistsInTargetLocation .CorrelateString(context.Task.Id), targetPageUri); if (!this.defaultPageTransformationOptions.Overwrite) { // Raise an exception and stop the process if Overwrite is not allowed var errorMessage = string.Format(System.Globalization.CultureInfo.InvariantCulture, TransformationResources.Error_PageNotOverwriteIfExists, targetPageUri.ToString()); logger.LogError(errorMessage .CorrelateString(context.Task.Id)); throw new ApplicationException(errorMessage); } } // Create the client side page using PnP Core SDK and save it var targetPage = await targetWeb.NewPageAsync().ConfigureAwait(false); var targetPageFilePath = $"{mappingOutput.TargetPage.Folder}{mappingOutput.TargetPage.PageName}"; await targetPage.SaveAsync(targetPageFilePath).ConfigureAwait(false); // Reload the generated file targetFile = await targetWeb.GetFileByServerRelativeUrlAsync(targetPageUriString).ConfigureAwait(false); #endregion #region Check if the page is the home page logger.LogDebug( TransformationResources.Debug_TransformCheckIfPageIsHomePage .CorrelateString(context.Task.Id)); // Check if the page is the home page bool replacedByOOBHomePage = false; // Check if the transformed page is the web's home page if (mappingOutput.TargetPage.IsHomePage) { targetPage.LayoutType = PnP.Core.Model.SharePoint.PageLayoutType.Home; if (this.defaultPageTransformationOptions.ReplaceHomePageWithDefaultHomePage) { targetPage.KeepDefaultWebParts = true; replacedByOOBHomePage = true; logger.LogInformation( TransformationResources.Info_TransformSourcePageHomePageUsingStock .CorrelateString(context.Task.Id)); } } // If it is not the home, let's define the actual page structure if (!replacedByOOBHomePage) { logger.LogInformation( TransformationResources.Info_TransformSourcePageAsArticlePage .CorrelateString(context.Task.Id)); #region Configure header from target page if (mappingOutput.TargetPage.PageHeader == null || (mappingOutput.TargetPage.PageHeader as PageHeader).Type == PageHeaderType.None) { logger.LogInformation( TransformationResources.Info_TransformArticleSetHeaderToNone .CorrelateString(context.Task.Id)); if (mappingOutput.TargetPage.SetAuthorInPageHeader) { targetPage.SetDefaultPageHeader(); targetPage.PageHeader.LayoutType = PageHeaderLayoutType.NoImage; logger.LogInformation( TransformationResources.Info_TransformArticleSetHeaderToNoneWithAuthor .CorrelateString(context.Task.Id)); await SetAuthorInPageHeaderAsync(context, mappingOutput, targetPage, context.Task.Id, token).ConfigureAwait(false); } else { targetPage.RemovePageHeader(); } } else if ((mappingOutput.TargetPage.PageHeader as PageHeader).Type == PageHeaderType.Default) { logger.LogInformation( TransformationResources.Info_TransformArticleSetHeaderToDefault .CorrelateString(context.Task.Id)); targetPage.SetDefaultPageHeader(); } else if ((mappingOutput.TargetPage.PageHeader as PageHeader).Type == PageHeaderType.Custom) { var infoMessage = $"{TransformationResources.Info_TransformArticleSetHeaderToCustom} {TransformationResources.Info_TransformArticleHeaderImageUrl} {mappingOutput.TargetPage.PageHeader.ImageServerRelativeUrl}"; logger.LogInformation(infoMessage .CorrelateString(context.Task.Id)); targetPage.SetCustomPageHeader(mappingOutput.TargetPage.PageHeader.ImageServerRelativeUrl, mappingOutput.TargetPage.PageHeader.TranslateX, mappingOutput.TargetPage.PageHeader.TranslateY); } #endregion } #endregion // Set page title targetPage.PageTitle = mappingOutput.TargetPage.PageTitle; // Create the web parts and the transformed content // Process all the sections, columns, and controls await GenerateTargetCanvasControlsAsync(targetWeb, targetPage, mappingOutput, context.Task.Id).ConfigureAwait(false); // Process metadata await CopyPageMetadataAsync(targetFile, mappingOutput, context.Task.Id).ConfigureAwait(false); // TODO: Process permissions #region Leftover code, most likely to be removed //if (transformationInformation.SkipHiddenWebParts) //{ // webParts = webParts.Where(c => !c.Hidden).ToList(); //} // Persist the new client side page // Set metadata fields for list item of the page // Configure page item permissions // if (KeepPageSpecificPermissions) { } // Other page settings //#region Page Publishing //// Tag the file with a page modernization version stamp //string serverRelativePathForModernPage = savedTargetPage.ListItemAllFields[Constants.FileRefField].ToString(); //bool pageListItemWasReloaded = false; //try //{ // var targetPageFile = context.Web.GetFileByServerRelativeUrl(serverRelativePathForModernPage); // context.Load(targetPageFile, p => p.Properties); // targetPageFile.Properties["sharepointpnp_pagemodernization"] = this.version; // targetPageFile.Update(); // if (!pageTransformationInformation.KeepPageCreationModificationInformation && // !pageTransformationInformation.PostAsNews && // pageTransformationInformation.PublishCreatedPage) // { // // Try to publish, if publish is not needed/possible (e.g. when no minor/major versioning set) then this will return an error that we'll be ignoring // targetPageFile.Publish(LogStrings.PublishMessage); // } // // Ensure we've the most recent page list item loaded, must be last statement before calling ExecuteQuery // context.Load(savedTargetPage.ListItemAllFields); // // Send both the property update and publish as a single operation to SharePoint // context.ExecuteQueryRetry(); // pageListItemWasReloaded = true; //} //catch (Exception) //{ // // Eat exceptions as this is not critical for the generated page // LogWarning(LogStrings.Warning_NonCriticalErrorDuringVersionStampAndPublish, LogStrings.Heading_ArticlePageHandling); //} //// Update flags field to indicate this is a "migrated" page //try //{ // // If for some reason the reload batched with the previous request did not finish then do it again // if (!pageListItemWasReloaded) // { // context.Load(savedTargetPage.ListItemAllFields); // context.ExecuteQueryRetry(); // } // // Only perform the update when the field was not yet set // bool skipSettingMigratedFromServerRendered = false; // if (savedTargetPage.ListItemAllFields[Constants.SPSitePageFlagsField] != null) // { // skipSettingMigratedFromServerRendered = (savedTargetPage.ListItemAllFields[Constants.SPSitePageFlagsField] as string[]).Contains("MigratedFromServerRendered"); // } // if (!skipSettingMigratedFromServerRendered) // { // savedTargetPage.ListItemAllFields[Constants.SPSitePageFlagsField] = ";#MigratedFromServerRendered;#"; // // Don't use UpdateOverWriteVersion as the listitem already exists // // resulting in an "Additions to this Web site have been blocked" error // savedTargetPage.ListItemAllFields.SystemUpdate(); // context.Load(savedTargetPage.ListItemAllFields); // context.ExecuteQueryRetry(); // } //} //catch (Exception) //{ // // Eat any exception //} //// Disable page comments on the create page, if needed //if (pageTransformationInformation.DisablePageComments) //{ // targetPage.DisableComments(); // LogInfo(LogStrings.TransformDisablePageComments, LogStrings.Heading_ArticlePageHandling); //} //#endregion // Swap pages? //#region Restore page author/editor/created/modified //if ((pageTransformationInformation.SourcePage != null && pageTransformationInformation.KeepPageCreationModificationInformation && this.SourcePageAuthor != null && this.SourcePageEditor != null) || // pageTransformationInformation.PostAsNews) //{ // UpdateTargetPageWithSourcePageInformation(finalListItemToUpdate, pageTransformationInformation, finalListItemToUpdate[Constants.FileRefField].ToString(), hasTargetContext); //} //#endregion // Log generation completed #endregion // Save the generated page await targetPage.SaveAsync(targetPageFilePath).ConfigureAwait(false); // Restore page author/editor/created/modified if ((this.defaultPageTransformationOptions.KeepPageCreationModificationInformation && mappingOutput.TargetPage.Author != null && mappingOutput.TargetPage.Editor != null) || this.defaultPageTransformationOptions.PostAsNews) { await UpdateTargetPageWithSourcePageInformationAsync(targetFile, mappingOutput, context.Task.Id).ConfigureAwait(false); } // Return the generated page URL var generatedPageFile = await targetPage.GetPageFileAsync(f => f.ServerRelativeUrl).ConfigureAwait(false); var generatedPageUri = new Uri($"{targetWeb.Url.Scheme}://{targetWeb.Url.Host}{generatedPageFile.ServerRelativeUrl}"); // Validate the URI of the output page if (!generatedPageUri.AbsoluteUri.Equals(targetPageUri.AbsoluteUri, StringComparison.InvariantCultureIgnoreCase)) { throw new ApplicationException(TransformationResources.Error_InvalidTargetPageUri); } result.GeneratedPageUrl = targetPageUri; return result; } private async Task UpdateTargetPageWithSourcePageInformationAsync(IFile targetFile, MappingProviderOutput mappingOutput, Guid taskId) { try { // Ensure the properties to define the cache key var targetWeb = targetFile.PnPContext.Web; await targetWeb.EnsurePropertiesAsync(w => w.Id).ConfigureAwait(false); // Load the list item corresponding to the file await targetFile.LoadAsync(f => f.ListItemAllFields).ConfigureAwait(false); var targetItem = targetFile.ListItemAllFields; // Update the target page information properties var pageAuthorUser = await targetWeb.EnsureUserAsync(mappingOutput.TargetPage.Author).ConfigureAwait(false); var pageEditorUser = await targetWeb.EnsureUserAsync(mappingOutput.TargetPage.Editor).ConfigureAwait(false); // Prep a new FieldUserValue object instance and update the list item var pageAuthor = new FieldUserValue() { LookupValue = pageAuthorUser.Title, LookupId = pageAuthorUser.Id }; var pageEditor = new FieldUserValue() { LookupValue = pageEditorUser.Title, LookupId = pageEditorUser.Id }; if (this.defaultPageTransformationOptions.KeepPageCreationModificationInformation || this.defaultPageTransformationOptions.PostAsNews) { if (this.defaultPageTransformationOptions.KeepPageCreationModificationInformation) { // All 4 fields have to be set! targetItem[SharePointConstants.CreatedByField] = pageAuthor; targetItem[SharePointConstants.ModifiedByField] = pageEditor; targetItem[SharePointConstants.CreatedField] = mappingOutput.TargetPage.Created; targetItem[SharePointConstants.ModifiedField] = mappingOutput.TargetPage.Modified; } if (this.defaultPageTransformationOptions.PostAsNews) { targetItem[SharePointConstants.PromotedStateField] = "2"; // Determine what will be the publishing date that will show up in the news rollup if (this.defaultPageTransformationOptions.KeepPageCreationModificationInformation) { targetItem[SharePointConstants.FirstPublishedDateField] = mappingOutput.TargetPage.Modified; } else { targetItem[SharePointConstants.FirstPublishedDateField] = targetItem[SharePointConstants.ModifiedField]; } } await targetItem.UpdateOverwriteVersionAsync().ConfigureAwait(false); if (this.defaultPageTransformationOptions.PublishPage) { await targetFile.PublishAsync(TransformationResources.Info_PublishMessage).ConfigureAwait(false); } } } catch (Exception ex) { // Eat exceptions as this is not critical for the generated page logger.LogWarning( TransformationResources.Warning_NonCriticalErrorDuringPublish .CorrelateString(taskId), ex.Message); } } private async Task CopyPageMetadataAsync(IFile targetFile, MappingProviderOutput mappingOutput, Guid taskId) { // Ensure the properties to define the cache key var targetWeb = targetFile.PnPContext.Web; await targetWeb.EnsurePropertiesAsync(w => w.Id).ConfigureAwait(false); var targetSite = targetFile.PnPContext.Site; await targetSite.EnsurePropertiesAsync(s => s.Id).ConfigureAwait(false); await targetFile.EnsurePropertiesAsync(f => f.ListId).ConfigureAwait(false); // Retrieve the list of fields from cache var fieldsToCopy = await GetFieldsFromCache(targetFile, targetWeb, targetSite).ConfigureAwait(false); //bool listItemWasReloaded = false; if (fieldsToCopy.Count > 0) { // Load the list item corresponding to the file await targetFile.LoadAsync(f => f.ListItemAllFields).ConfigureAwait(false); var targetItem = targetFile.ListItemAllFields; // Initially set the content type Id - Are we sure about this excerpt? //targetItem[PageConstants.ContentTypeId] = mappingOutput.Metadata[PageConstants.ContentTypeId]?.Value; //await targetItem.UpdateOverwriteVersionAsync().ConfigureAwait(false); // TODO: Complete metadata fields handling (taxonomy with mapping provider and other fields) foreach (var fieldToCopy in fieldsToCopy.Where(f => f.Type == "TaxonomyFieldTypeMulti" || f.Type == "TaxonomyFieldType")) { logger.LogInformation( TransformationResources.Info_MappingTaxonomyField .CorrelateString(taskId), fieldToCopy.Name); // https://pnp.github.io/pnpcore/using-the-sdk/listitems-fields.html#taxonomy-fields } foreach (var fieldToCopy in fieldsToCopy.Where(f => f.Type != "TaxonomyFieldTypeMulti" && f.Type != "TaxonomyFieldType")) { logger.LogInformation( TransformationResources.Info_MappingRegularField .CorrelateString(taskId), fieldToCopy.Name); // https://pnp.github.io/pnpcore/using-the-sdk/listitems-fields.html } } } private async Task<List<FieldData>> GetFieldsFromCache(IFile targetFile, IWeb targetWeb, ISite targetSite) { // Define the cache key var fieldsCacheKey = $"Fields|{targetSite.Id}|{targetWeb.Id}|{targetFile.ListId}"; List<FieldData> result = null; if (!this.memoryCache.TryGetValue(fieldsCacheKey, out result)) { // Get the fields of the current list var targetList = await targetFile.PnPContext.Web.Lists.GetByIdAsync(targetFile.ListId, l => l.Id, l => l.Fields.QueryProperties(f => f.Id, f => f.StaticName, f => f.TypeAsString, f => f.Hidden) ).ConfigureAwait(false); // Exclude hidden and built-in fields result = targetList.Fields.AsRequested() .Where(f => !f.Hidden && !BuiltInFields.Contains(f.StaticName)).Select(f => new FieldData { Id = f.Id, Name = f.StaticName, Type = f.TypeAsString }).ToList(); // Store the list of fields in cache for future use this.memoryCache.Set(fieldsCacheKey, result); } return result; } private async Task GenerateTargetCanvasControlsAsync(IWeb targetWeb, IPage targetPage, MappingProviderOutput mappingOutput, Guid taskId) { // Prepare global tokens var globalTokens = await PrepareGlobalTokensAsync(targetWeb).ConfigureAwait(false); // Get the list of components available in the current site var componentsToAdd = await GetClientSideComponentsAsync(targetPage).ConfigureAwait(false); int sectionOrder = 0; foreach (var section in mappingOutput.TargetPage.Sections) { section.Order = sectionOrder; targetPage.AddSection(section.CanvasTemplate, sectionOrder); var targetSection = targetPage.Sections[sectionOrder]; sectionOrder++; int columnOrder = 0; int controlOrder = 0; foreach (var column in section.Columns) { var targetColumn = targetSection.Columns[columnOrder]; columnOrder++; controlOrder++; foreach (var control in column.Controls) { GenerateTargetCanvasControl(targetPage, componentsToAdd, controlOrder, targetColumn, control, globalTokens, taskId); } } } } private void GenerateTargetCanvasControl(IPage targetPage, List<PageComponent> componentsToAdd, int controlOrder, ICanvasColumn targetColumn, Model.CanvasControl control, Dictionary<string, string> globalTokens, Guid taskId) { // Prepare a web part control container IPageComponent baseControl = null; switch (control.ControlType) { case Model.CanvasControlType.ClientSideText: // Here we add a text control var text = targetPage.NewTextPart(); text.Text = control["Text"] as string; // Add the actual text control to the page targetPage.AddControl(text, targetColumn, controlOrder); // Log the just executed action logger.LogInformation( TransformationResources.Info_CreatedTextControl .CorrelateString(taskId)); break; case Model.CanvasControlType.CustomClientSideWebPart: // Parse the control ID to support generic web part placement scenarios var ControlId = control["ControlId"] as string; // Check if this web part belongs to the list of "usable" web parts for this site baseControl = componentsToAdd.FirstOrDefault(p => p.Id.Equals($"{{{ControlId}}}", StringComparison.InvariantCultureIgnoreCase)); logger.LogInformation( TransformationResources.Info_UsingCustomModernWebPart .CorrelateString(taskId)); break; case Model.CanvasControlType.DefaultWebPart: // Determine the actual default web part var webPartType = (DefaultWebPart)Enum.Parse(typeof(DefaultWebPart), control["WebPartType"] as string); var webPartName = targetPage.DefaultWebPartToWebPartId(webPartType); var webPartTitle = control["Title"] as string; var webPartProperties = control["Properties"] as Dictionary<string, string>; var jsonControlData = control["JsonControlData"] as string; if (webPartType == DefaultWebPart.ClientWebPart) { var addinComponents = componentsToAdd.Where(p => p.Name.Equals(webPartName, StringComparison.InvariantCultureIgnoreCase)); foreach (var addin in addinComponents) { // Find the right add-in web part via title matching...maybe not bullet proof but did find anything better for now JObject wpJObject = JObject.Parse(addin.Manifest); // As there can be multiple classic web parts (via provider hosted add ins or SharePoint hosted add ins) we're looping to find the first one with a matching title foreach (var addinEntry in wpJObject["preconfiguredEntries"]) { if (addinEntry["title"]["default"].Value<string>() == webPartTitle) { baseControl = addin; var jsonProperties = addinEntry; // Fill custom web part properties in this json. Custom properties are listed as child elements under clientWebPartProperties, // replace their "default" value with the value we got from the web part's properties jsonProperties = PopulateAddInProperties(jsonProperties, webPartProperties); // Override the JSON data we read from the model as this is fully dynamic due to the nature of the add-in client part jsonControlData = jsonProperties.ToString(Newtonsoft.Json.Formatting.None); logger.LogInformation( TransformationResources.Info_ContentUsingAddinWebPart .CorrelateString(taskId), baseControl.Name); break; } } } } else { baseControl = componentsToAdd.FirstOrDefault(p => p.Name.Equals(webPartName, StringComparison.InvariantCultureIgnoreCase)); logger.LogInformation( TransformationResources.Info_ContentUsingModernWebPart .CorrelateString(taskId), webPartType); } // If we found the web part as a possible candidate to use then add it if (baseControl != null) { var jsonDecoded = WebUtility.HtmlDecode(this.tokenParser.ReplaceTargetTokens(targetPage.PnPContext, jsonControlData, webPartProperties, globalTokens)); var myWebPart = targetPage.NewWebPart(baseControl); myWebPart.Order = controlOrder; myWebPart.PropertiesJson = jsonDecoded; // Add the actual text control to the page targetPage.AddControl(myWebPart, targetColumn, controlOrder); logger.LogInformation( TransformationResources.Info_AddedClientSideWebPartToPage .CorrelateString(taskId), webPartTitle); } else { logger.LogWarning( TransformationResources.Warning_ContentWarnModernNotFound .CorrelateString(taskId)); } break; default: break; } } private async Task<List<PageComponent>> GetClientSideComponentsAsync(IPage targetPage) { var siteToComponentMapping = new Dictionary<Guid, string>(); var componentsToAdd = (await targetPage.AvailablePageComponentsAsync().ConfigureAwait(false)) .Cast<PageComponent>().ToList(); // TODO: Consider adding back caching return componentsToAdd; } private JToken PopulateAddInProperties(JToken jsonProperties, Dictionary<string, string> webPartProperties) { foreach (JToken property in jsonProperties["properties"]["clientWebPartProperties"]) { var wpProp = property["name"].Value<string>(); if (!string.IsNullOrEmpty(wpProp)) { if (webPartProperties.ContainsKey(wpProp)) { if (jsonProperties["properties"]["userDefinedProperties"][wpProp] != null) { jsonProperties["properties"]["userDefinedProperties"][wpProp] = webPartProperties[wpProp].ToString(); } else { JToken newProp = JObject.Parse($"{{\"{wpProp}\": \"{webPartProperties[wpProp].ToString()}\"}}"); (jsonProperties["properties"]["userDefinedProperties"] as JObject).Merge(newProp); } } } } return jsonProperties; } internal async Task SetAuthorInPageHeaderAsync(PageTransformationContext context, MappingProviderOutput mappingOutput, IPage targetClientSidePage, Guid taskId, CancellationToken token = default) { // Try to get th var userMappingProvider = serviceProvider.GetService<IUserMappingProvider>(); if (userMappingProvider == null) { throw new ApplicationException(TransformationResources.Error_MissingUserMappingProvider); } try { var mappedAuthorOutput = await userMappingProvider.MapUserAsync(new UserMappingProviderInput(context, mappingOutput.TargetPage.Author), token).ConfigureAwait(false); var ensuredPageAuthorUser = await targetClientSidePage.PnPContext.Web.EnsureUserAsync(mappedAuthorOutput.UserPrincipalName).ConfigureAwait(false); if (ensuredPageAuthorUser != null) { var author = ensuredPageAuthorUser.ToUserEntity(); if (author != null) { if (!author.IsGroup) { // Don't serialize null values var jsonSerializerOptions = new JsonSerializerOptions() { #if NET5_0_OR_GREATER DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, #else IgnoreNullValues = true, #endif }; var json = JsonSerializer.Serialize(author, jsonSerializerOptions); if (!string.IsNullOrEmpty(json)) { targetClientSidePage.PageHeader.Authors = json; } } } else { logger.LogWarning( TransformationResources.Warning_PageHeaderAuthorNotSet .CorrelateString(taskId), mappingOutput.TargetPage.Author); } } else { logger.LogWarning( TransformationResources.Warning_PageHeaderAuthorNotSet .CorrelateString(taskId), mappingOutput.TargetPage.Author); } } catch (Exception ex) { logger.LogWarning( TransformationResources.Warning_PageHeaderAuthorNotSetGenericError .CorrelateString(taskId), ex.Message); } } /// <summary> /// Prepares global tokens for target environment /// </summary> /// <returns></returns> private async Task<Dictionary<string, string>> PrepareGlobalTokensAsync(IWeb web) { Dictionary<string, string> globalTokens = new Dictionary<string, string>(5); await web.EnsurePropertiesAsync(w => w.Id, w => w.Url, w => w.ServerRelativeUrl).ConfigureAwait(false); var site = web.PnPContext.Site; await site.EnsurePropertiesAsync(s => s.Id, s => s.RootWeb.QueryProperties(rw => rw.ServerRelativeUrl)).ConfigureAwait(false); // Add the fixed properties globalTokens.Add("Host", $"{web.Url.Scheme}://{web.Url.DnsSafeHost}"); globalTokens.Add("Web", web.ServerRelativeUrl.TrimEnd('/')); globalTokens.Add("SiteCollection", site.RootWeb.ServerRelativeUrl.TrimEnd('/')); globalTokens.Add("WebId", web.Id.ToString()); globalTokens.Add("SiteId", site.Id.ToString()); return globalTokens; } } }
47.691436
232
0.580717
[ "MIT" ]
JackStrap/pnpcore
src/sdk/PnP.Core.Transformation/Services/Core/DefaultPageGenerator.cs
37,869
C#
/* JustMock Lite Copyright © 2010-2014 Telerik EAD 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 Telerik.JustMock.DemoLib { public partial class VerifyModel : OpenAccessContextBase { public VerifyModel() { } } }
28.307692
75
0.751359
[ "Apache-2.0" ]
tailsu/JustMockLite
Telerik.JustMock.DemoLib/OpenAccess/VerifyModel.cs
737
C#
using System; using System.Threading.Tasks; namespace AppCore { public class Messenger { public async Task<string> GetMessage(string name) { return await Task.FromResult("hola " + name); } } }
16.266667
57
0.598361
[ "MIT" ]
LuisTejedaS/CSDCourseTemplate-dotnet
src/AppCore/Messenger.cs
246
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Abp.Domain.Entities; using Abp.Domain.Entities.Auditing; using Abp.Timing; namespace RoyalEstate.Entities{ public class EstateType : Entity, IHasCreationTime { public const int MaxNameLength = 100; [Required] [StringLength(MaxNameLength)] public string Name { get; set; } public DateTime CreationTime { get; set; } public bool IsActive { get; set; } [ForeignKey(nameof(ServiceTypeId))] [Required] public virtual ServiceType ServiceType { get; set; } public int ServiceTypeId { get; set; } public bool LegalDoc { get; set; } public bool Price { get; set; } public bool Rent { get; set; } public bool Deposit { get; set; } public bool Area { get; set; } public bool Floor { get; set; } public bool TotalFloors { get; set; } public bool UnitsPerFloor { get; set; } public bool Rooms { get; set; } public bool MasterRoom { get; set; } public bool Parking { get; set; } public bool Storeroom { get; set; } public bool Elevator { get; set; } public bool BuiltDate { get; set; } [MaxLength(50)] public string Color { get; set; } public EstateType() { CreationTime = DateTime.Now; } /*public static implicit operator List<object>(EstateType v) { throw new NotImplementedException(); }*/ } }
28.118644
68
0.597951
[ "MIT" ]
kamal24h/Royal
src/RoyalEstate.Core/Entities/EstateType.cs
1,661
C#
//===============================================================// // Taken and modified from: https://github.com/TGEnigma/Amicitia // //===============================================================// using System.Runtime.CompilerServices; namespace MikuMikuLibrary.IO.Common { public static class AlignmentUtilities { [MethodImpl( MethodImplOptions.AggressiveInlining )] public static long Align( long value, int alignment ) { return ( value + ( alignment - 1 ) ) & ~( alignment - 1 ); } [MethodImpl( MethodImplOptions.AggressiveInlining )] public static int Align( int value, int alignment ) { return ( value + ( alignment - 1 ) ) & ~( alignment - 1 ); } [MethodImpl( MethodImplOptions.AggressiveInlining )] public static int GetAlignedDifference( long value, int alignment ) { return ( int ) ( ( ( value + ( alignment - 1 ) ) & ~( alignment - 1 ) ) - value ); } [MethodImpl( MethodImplOptions.AggressiveInlining )] public static int GetAlignedDifference( int value, int alignment ) { return ( ( value + ( alignment - 1 ) ) & ~( alignment - 1 ) ) - value; } [MethodImpl( MethodImplOptions.AggressiveInlining )] public static int AlignToNextPowerOfTwo( int value ) { value--; value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; value++; return value; } } }
33.428571
94
0.504884
[ "MIT" ]
nastys/MikuMikuLibrary
MikuMikuLibrary/IO/Common/AlignmentUtilities.cs
1,640
C#
// Copyright (c) Microsoft Corporation. All rights reserved. using System.Collections.Generic; using ColorSyntax.Common; namespace ColorSyntax.Compilation.Languages { public class Php : ILanguage { public string Id { get { return LanguageId.Php; } } public string Name { get { return "PHP"; } } public string CssClassName { get { return "php"; } } public string FirstLinePattern { get { return null; } } public IList<LanguageRule> Rules { get { return new List<LanguageRule> { new LanguageRule( @"/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/", new Dictionary<int, string> { { 0, ScopeName.Comment }, }), new LanguageRule( @"(//.*?)\r?$", new Dictionary<int, string> { { 1, ScopeName.Comment }, }), new LanguageRule( @"(#.*?)\r?$", new Dictionary<int, string> { { 1, ScopeName.Comment }, }), new LanguageRule( @"'[^\n]*?(?<!\\)'", new Dictionary<int, string> { { 0, ScopeName.String }, }), new LanguageRule( @"""[^\n]*?(?<!\\)""", new Dictionary<int, string> { { 0, ScopeName.String }, }), new LanguageRule( // from http://us.php.net/manual/en/reserved.keywords.php @"\b(abstract|and|array|as|break|case|catch|cfunction|class|clone|const|continue|declare|default|do|else|elseif|enddeclare|endfor|endforeach|endif|endswitch|endwhile|exception|extends|fclose|file|final|for|foreach|function|global|goto|if|implements|interface|instanceof|mysqli_fetch_object|namespace|new|old_function|or|php_user_filter|private|protected|public|static|switch|throw|try|use|var|while|xor|__CLASS__|__DIR__|__FILE__|__FUNCTION__|__LINE__|__METHOD__|__NAMESPACE__|die|echo|empty|exit|eval|include|include_once|isset|list|require|require_once|return|print|unset)\b", new Dictionary<int, string> { { 1, ScopeName.Keyword }, }), }; } } public bool HasAlias(string lang) { switch (lang.ToLower()) { case "php3": case "php4": case "php5": return true; default: return false; } } string[] ILanguage.Aliases => new string[] { "php" }; public override string ToString() { return Name; } } }
38.69
613
0.360817
[ "Apache-2.0" ]
UWPCommunity/Quarrel
old/Discord UWP/Markdown/ColorCode/ColorCode.Core/Compilation/Languages/Php.cs
3,871
C#
using Aspose.OCR.Live.Demos.UI.Config; using Aspose.OCR.Live.Demos.UI.Models; using Aspose.OCR.Live.Demos.UI.Services; using Aspose.OCR.Live.Demos.UI.Helpers; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Net.Http; namespace Aspose.OCR.Live.Demos.UI.Controllers { public abstract class BaseController : Controller { /// <summary> /// Response when uploaded files exceed the limits /// </summary> protected Response BadDocumentResponse = new Response() { Status = "Some of your documents are corrupted", StatusCode = 500 }; public abstract string Product { get; } protected override void OnActionExecuted(ActionExecutedContext ctx) { base.OnActionExecuted(ctx); ViewBag.Title = ViewBag.Title ?? Resources["ApplicationTitle"]; ViewBag.MetaDescription = ViewBag.MetaDescription ?? "Save time and software maintenance costs by running single instance of software, but serving multiple tenants/websites. Customization available for Joomla, Wordpress, Discourse, Confluence and other popular applications."; } private AsposeOCRContext _atcContext; /// <summary> /// Main context object to access all the dcContent specific context info /// </summary> public AsposeOCRContext AsposeOCRContext { get { if (_atcContext == null) _atcContext = new AsposeOCRContext(HttpContext.ApplicationInstance.Context); return _atcContext; } } private Dictionary<string, string> _resources; /// <summary> /// key/value pair containing all the error messages defined in resources.xml file /// </summary> public Dictionary<string, string> Resources { get { if (_resources == null) _resources = AsposeOCRContext.Resources; return _resources; } } } }
25.871429
279
0.73661
[ "MIT" ]
aspose-ocr/Aspose.OCR-for-.NET
Demos/src/Aspose.OCR.Live.Demos.UI/Controllers/BaseController.cs
1,811
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Terraria Midi Player")] [assembly: AssemblyDescription("Terraria Midi Player - A music player for Terrarian instruments")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Trigger's Tools & Games")] [assembly: AssemblyProduct("TerrariaMidiPlayer")] [assembly: AssemblyCopyright("Copyright © Robert Jordan {YEAR}")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.2")] [assembly: AssemblyFileVersion("1.1.0.2")] [assembly: Guid("868163E6-E0A0-4035-AA63-3042476FD242")] [assembly: NeutralResourcesLanguage("en-US")]
41.915254
98
0.751314
[ "MIT" ]
trigger-death/TerrariaMidiPlayer
TerrariaMidiPlayer/Properties/AssemblyInfo.cs
2,476
C#
using Dotnet5.GraphQL3.Domain.Abstractions.Entities; namespace Dotnet5.GraphQL3.Domain.Abstractions.Builders { public interface IBuilder<out TEntity, TId> where TEntity : Entity<TId> where TId : struct { TEntity Build(); } }
23.818182
55
0.683206
[ "MIT" ]
DBollella/Dotnet5.GraphQL3.WebApplication
src/Dotnet5.GraphQL3.Domain.Abstractions/Builders/IBuilder.cs
264
C#
class Program { static void Main(string[] args) { string destination = "default"; switch (destination) { case "Inventory": AddToInventory(); break; case "Hotbar": AddToHotbar(); default: Debug.Log("Destination Unknown"); break; } } static void AddToInventory() { /* inserted */ int _25 = 10; } static void AddToHotbar() {} } class Debug { public static void Log(string v) {} }
18.833333
39
0.586283
[ "Apache-2.0" ]
thufv/DeepFix-C-
data/Mutation/CS0163_2_mutation_15/[E]CS0163.cs
454
C#
// Copyright (c) 2020 Yann Crumeyrolle. All rights reserved. // Licensed under the MIT license. See LICENSE in the project root for license information. using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace JsonWebToken.Cryptography { /// <summary> /// Provides AES key wrapping services. /// </summary> internal sealed class AesKeyWrapper : KeyWrapper { private const int BlockSizeInBytes = 8; // The default initialization vector from RFC3394 private const ulong _defaultIV = 0XA6A6A6A6A6A6A6A6; private readonly AesBlockEncryptor _encryptor; private bool _disposed; public AesKeyWrapper(ReadOnlySpan<byte> key, EncryptionAlgorithm encryptionAlgorithm, KeyManagementAlgorithm algorithm) : base(encryptionAlgorithm, algorithm) { Debug.Assert(SymmetricJwk.SupportedKeyManagement(key.Length << 3, algorithm)); Debug.Assert(algorithm.Category == AlgorithmCategory.Aes); #if SUPPORT_SIMD if (System.Runtime.Intrinsics.X86.Aes.IsSupported && EncryptionAlgorithm.EnabledAesInstructionSet) { if (algorithm == KeyManagementAlgorithm.A128KW) { _encryptor = new Aes128BlockEncryptor(key); } else if (algorithm == KeyManagementAlgorithm.A256KW) { _encryptor = new Aes256BlockEncryptor(key); } else if (algorithm == KeyManagementAlgorithm.A192KW) { _encryptor = new Aes192BlockEncryptor(key); } else { ThrowHelper.ThrowNotSupportedException_AlgorithmForKeyWrap(algorithm); _encryptor = new Aes128BlockEncryptor(default); } } else { _encryptor = new DefaultAesBlockEncryptor(key); } #else _encryptor = new DefaultAesBlockEncryptor(key); #endif } protected override void Dispose(bool disposing) { if (!_disposed) { if (disposing) { _encryptor.Dispose(); } _disposed = true; } } /// <summary> /// Wrap a key using AES encryption. /// </summary> /// <param name="staticKey">the key to be wrapped. If <c>null</c>, a new <see cref="SymmetricJwk"/> will be generated.</param> /// <param name="header"></param> /// <param name="destination"></param> public override SymmetricJwk WrapKey(Jwk? staticKey, JwtHeader header, Span<byte> destination) { if (destination.Length < GetKeyWrapSize()) { ThrowHelper.ThrowArgumentException_DestinationTooSmall(destination.Length, GetKeyWrapSize()); } var contentEncryptionKey = CreateSymmetricKey(EncryptionAlgorithm, (SymmetricJwk?)staticKey); ReadOnlySpan<byte> inputBuffer = contentEncryptionKey.AsSpan(); int n = inputBuffer.Length; if (destination.Length != (n + 8)) { ThrowHelper.ThrowArgumentException_DestinationTooSmall(destination.Length, n + 8); } ulong a = _defaultIV; ref byte input = ref MemoryMarshal.GetReference(inputBuffer); Span<byte> r = stackalloc byte[n]; ref byte rRef = ref MemoryMarshal.GetReference(r); Unsafe.CopyBlockUnaligned(ref rRef, ref input, (uint)n); TryWrapKey(ref a, n, ref rRef); ref byte keyBytes = ref MemoryMarshal.GetReference(destination); Unsafe.WriteUnaligned(ref keyBytes, a); Unsafe.CopyBlockUnaligned(ref Unsafe.AddByteOffset(ref keyBytes, (IntPtr)8), ref rRef, (uint)n); return contentEncryptionKey; } private ulong TryWrapKey(ref ulong a, int n, ref byte rRef) { Span<byte> block = stackalloc byte[16]; ref byte blockRef = ref MemoryMarshal.GetReference(block); ref byte block2Ref = ref Unsafe.AddByteOffset(ref blockRef, (IntPtr)8); Span<byte> t = stackalloc byte[8]; ref byte tRef = ref MemoryMarshal.GetReference(t); ref byte tRef7 = ref Unsafe.AddByteOffset(ref tRef, (IntPtr)7); Unsafe.WriteUnaligned<ulong>(ref tRef, 0L); int n3 = n >> 3; Span<byte> b = stackalloc byte[16]; ref byte bRef = ref MemoryMarshal.GetReference(b); for (var j = 0; j < 6; j++) { for (var i = 0; i < n3; i++) { Unsafe.WriteUnaligned(ref blockRef, a); Unsafe.WriteUnaligned(ref block2Ref, Unsafe.ReadUnaligned<ulong>(ref Unsafe.AddByteOffset(ref rRef, (IntPtr)(i << 3)))); _encryptor!.EncryptBlock(block, b); a = Unsafe.ReadUnaligned<ulong>(ref bRef); Unsafe.WriteUnaligned(ref tRef7, (byte)((n3 * j) + i + 1)); a ^= Unsafe.ReadUnaligned<ulong>(ref tRef); Unsafe.WriteUnaligned(ref Unsafe.AddByteOffset(ref rRef, (IntPtr)(i << 3)), Unsafe.ReadUnaligned<ulong>(ref Unsafe.AddByteOffset(ref bRef, (IntPtr)8))); } } return a; } public override int GetKeyWrapSize() => GetKeyWrappedSize(EncryptionAlgorithm); public static int GetKeyWrappedSize(EncryptionAlgorithm encryptionAlgorithm) => encryptionAlgorithm.KeyWrappedSizeInBytes; } }
40.774648
172
0.582383
[ "MIT" ]
signature-opensource/Jwt
src/JsonWebToken/Cryptography/AesKeyWrapper.cs
5,792
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using CodecToolSet.Core; using CodecToolSet.Core.RFXDecode; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using RDPToolSet.Web.Models; using RDPToolSet.Web.Utils; namespace RDPToolSet.Web.Controllers { public class RFXDecodeController : CodecBaseController { public RFXDecodeController(IWebHostEnvironment hostingEnvironment) : base(hostingEnvironment) { } public override ActionResult Index() { var envValues = new Dictionary<string, object>(); if (this.HttpContext.Session.Get<bool>(isActionValid) == false) { var rfxDecode = new RFXDecode(); envValues[ActionKey] = rfxDecode; } else { this.HttpContext.Session.SetObject(isActionValid, false); } if (this.HttpContext.Session.Get<bool>(isModelValid) == false) { var rfxDeocdeModel = new RFXDecodeViewModel(); envValues[ModelKey] = rfxDeocdeModel; } else { this.HttpContext.Session.SetObject(isModelValid, false); } SaveToSession(envValues); LoadFromSession(); return View(_viewModel); } [HttpPost] public async Task<IActionResult> Decode() { try { using (var bodyStream = new StreamReader(Request.Body)) { var bodyText = await bodyStream.ReadToEndAsync(); dynamic obj = (JObject)JsonConvert.DeserializeObject(bodyText); // retrieve the quant var quantArray = JsonHelper.RetrieveQuantsArray(obj.Params.QuantizationFactorsArray); _codecAction.Parameters[Constants.PARAM_NAME_QUANT_FACTORS_ARRAY] = quantArray; _codecAction.Parameters[Constants.PARAM_NAME_ENTROPY_ALGORITHM] = JsonHelper.CastTo<EntropyAlgorithm>(obj.Params.EntropyAlgorithm); string decOrHex = (string)obj.Params.DecOrHex; Tile tile = null; JObject jsonInputs = JObject.Parse(obj["Inputs"].ToString()); dynamic objInputs = JsonConvert.DeserializeObject(jsonInputs.ToString()); string y = jsonInputs["Y"].ToString(); string cb = jsonInputs["Cb"].ToString(); string cr = jsonInputs["Cr"].ToString(); if (decOrHex.Equals("hex")) { tile = Tile.FromStrings(new Triplet<string>(y, cb, cr), new HexTileSerializer()); } else { tile = Tile.FromStrings(new Triplet<string>(y, cb, cr), new IntegerTileSerializer()); } _codecAction.DoAction(tile); return Json(ReturnResult<string>.Success("Success")); } } catch (Exception ex) { return Json(ReturnResult<string>.Fail(ex.Message)); } } /// <summary> /// return an index page according to the inputs /// </summary> /// <returns></returns> [HttpPost] public async Task<IActionResult> IndexWithInputs() { try { using (var bodyStream = new StreamReader(Request.Body)) { var bodyText = await bodyStream.ReadToEndAsync(); dynamic obj = JsonConvert.DeserializeObject(bodyText); // retrieve the quant QuantizationFactorsArray quantArray = JsonHelper.RetrieveQuantsArray(obj.Params.QuantizationFactorsArray); EntropyAlgorithm algorithm = JsonHelper.CastTo<EntropyAlgorithm>(obj.Params.EntropyAlgorithm); _viewModel = new RFXDecodeViewModel(); // Updates parameters ((RFXDecodeViewModel)_viewModel).ProvideParam(quantArray, algorithm); Triplet<string> triplet = JsonHelper.RetrieveTriplet(obj.Inputs); ((RFXDecodeViewModel)_viewModel).ProvidePanelInputs(triplet.ToArray()); var envValues = new Dictionary<string, object>() { {ModelKey, _viewModel}, {isModelValid, true} }; SaveToSession(envValues); } return Json(ReturnResult<string>.Success("Success")); } catch (Exception ex) { return Json(ReturnResult<string>.Fail(ex.Message)); } } } }
36.887324
151
0.543337
[ "MIT" ]
G-arj/WindowsProtocolTestSuites
TestSuites/RDP/Tools/RDPToolSet/RDPToolSet.Web/Controllers/RFXDecodeController.cs
5,240
C#
using System; using System.Configuration; using System.Linq; using System.Net; using System.Reflection; using System.Threading.Tasks; using NetTelegramBotApi; using NetTelegramBotApi.Requests; using NetTelegramBotApi.Types; namespace TelegramBotDemo { public class Program { private static bool stopMe = false; public static void Main(string[] args) { var accessToken = ConfigurationManager.AppSettings["AccessToken"]; Console.WriteLine("Starting your bot..."); Console.WriteLine(); var t = Task.Run(() => RunBot(accessToken)); Console.ReadLine(); stopMe = true; } public static void RunBot(string accessToken) { var bot = new TelegramBot(accessToken); var me = bot.MakeRequestAsync(new GetMe()).Result; if (me == null) { Console.WriteLine("GetMe() FAILED. Do you forget to add your AccessToken to App.config?"); Console.WriteLine("(Press ENTER to quit)"); Console.ReadLine(); return; } Console.WriteLine("{0} (@{1}) connected!", me.FirstName, me.Username); Console.WriteLine(); Console.WriteLine("Find @{0} in Telegram and send him a message - it will be displayed here", me.Username); Console.WriteLine("(Press ENTER to stop listening and quit)"); Console.WriteLine(); Console.WriteLine("ATENTION! This project uses nuget package, not 'live' project in solution (because 'live' project is vNext now)"); Console.WriteLine(); string uploadedPhotoId = null; string uploadedDocumentId = null; long offset = 0; while (!stopMe) { var updates = bot.MakeRequestAsync(new GetUpdates() { Offset = offset }).Result; if (updates != null) { foreach (var update in updates) { offset = update.UpdateId + 1; if (update.Message == null) { continue; } var from = update.Message.From; var text = update.Message.Text; var photos = update.Message.Photo; Console.WriteLine( "Msg from {0} {1} ({2}) at {4}: {3}", from.FirstName, from.LastName, from.Username, text, update.Message.Date); if (photos != null) { var webClient = new WebClient(); foreach (var photo in photos) { Console.WriteLine(" New image arrived: size {1}x{2} px, {3} bytes, id: {0}", photo.FileId, photo.Height, photo.Width, photo.FileSize); var file = bot.MakeRequestAsync(new GetFile(photo.FileId)).Result; var tempFileName = System.IO.Path.GetTempFileName(); webClient.DownloadFile(file.FileDownloadUrl, tempFileName); Console.WriteLine(" Saved to {0}", tempFileName); } } if (string.IsNullOrEmpty(text)) { continue; } if (text == "/photo") { if (uploadedPhotoId == null) { var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_photo"); bot.MakeRequestAsync(reqAction).Wait(); System.Threading.Thread.Sleep(500); using (var photoData = Assembly.GetExecutingAssembly().GetManifestResourceStream("TelegramBotDemo.t_logo.png")) { var req = new SendPhoto(update.Message.Chat.Id, new FileToSend(photoData, "Telegram_logo.png")) { Caption = "Telegram_logo.png" }; var msg = bot.MakeRequestAsync(req).Result; uploadedPhotoId = msg.Photo.Last().FileId; } } else { var req = new SendPhoto(update.Message.Chat.Id, new FileToSend(uploadedPhotoId)) { Caption = "Resending photo id=" + uploadedPhotoId }; bot.MakeRequestAsync(req).Wait(); } continue; } if (text == "/doc") { if (uploadedDocumentId == null) { var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_document"); bot.MakeRequestAsync(reqAction).Wait(); System.Threading.Thread.Sleep(500); using (var docData = Assembly.GetExecutingAssembly().GetManifestResourceStream("TelegramBotDemo.Telegram_Bot_API.htm")) { var req = new SendDocument(update.Message.Chat.Id, new FileToSend(docData, "Telegram_Bot_API.htm")); var msg = bot.MakeRequestAsync(req).Result; uploadedDocumentId = msg.Document.FileId; } } else { var req = new SendDocument(update.Message.Chat.Id, new FileToSend(uploadedDocumentId)); bot.MakeRequestAsync(req).Wait(); } continue; } if (text == "/docutf8") { var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_document"); bot.MakeRequestAsync(reqAction).Wait(); System.Threading.Thread.Sleep(500); using (var docData = Assembly.GetExecutingAssembly().GetManifestResourceStream("TelegramBotDemo.Пример UTF8 filename.txt")) { var req = new SendDocument(update.Message.Chat.Id, new FileToSend(docData, "Пример UTF8 filename.txt")); var msg = bot.MakeRequestAsync(req).Result; uploadedDocumentId = msg.Document.FileId; } continue; } if (text == "/help") { var keyb = new ReplyKeyboardMarkup() { Keyboard = new[] { new[] { new KeyboardButton("/photo"), new KeyboardButton("/doc"), new KeyboardButton("/docutf8") }, new[] { new KeyboardButton("/help") } }, OneTimeKeyboard = true, ResizeKeyboard = true }; var reqAction = new SendMessage(update.Message.Chat.Id, "Here is all my commands") { ReplyMarkup = keyb }; bot.MakeRequestAsync(reqAction).Wait(); continue; } if (update.Message.Text.Length % 2 == 0) { bot.MakeRequestAsync(new SendMessage( update.Message.Chat.Id, "You wrote *" + update.Message.Text.Length + " characters*") { ParseMode = SendMessage.ParseModeEnum.Markdown }).Wait(); } else { bot.MakeRequestAsync(new ForwardMessage(update.Message.Chat.Id, update.Message.Chat.Id, update.Message.MessageId)).Wait(); } } } } } } }
48.185185
167
0.417152
[ "MIT" ]
ghorbani77/NetTelegramBotApi
TelegramBotDemo/Program.cs
9,121
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Jag.Spice.Interfaces.Models { using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// TraceInfo /// </summary> public partial class MicrosoftDynamicsCRMTraceInfo { /// <summary> /// Initializes a new instance of the MicrosoftDynamicsCRMTraceInfo /// class. /// </summary> public MicrosoftDynamicsCRMTraceInfo() { CustomInit(); } /// <summary> /// Initializes a new instance of the MicrosoftDynamicsCRMTraceInfo /// class. /// </summary> public MicrosoftDynamicsCRMTraceInfo(IList<MicrosoftDynamicsCRMErrorInfo> errorInfoList = default(IList<MicrosoftDynamicsCRMErrorInfo>)) { ErrorInfoList = errorInfoList; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// </summary> [JsonProperty(PropertyName = "ErrorInfoList")] public IList<MicrosoftDynamicsCRMErrorInfo> ErrorInfoList { get; set; } } }
28.78
144
0.625434
[ "Apache-2.0" ]
BrendanBeachBC/jag-spd-spice
interfaces/Dynamics-Autorest/Models/MicrosoftDynamicsCRMTraceInfo.cs
1,439
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using BenchmarkDotNet.Analysers; using BenchmarkDotNet.Columns; using BenchmarkDotNet.Diagnosers; using BenchmarkDotNet.Exporters; using BenchmarkDotNet.Extensions; using BenchmarkDotNet.Filters; using BenchmarkDotNet.Jobs; using BenchmarkDotNet.Loggers; using BenchmarkDotNet.Order; using BenchmarkDotNet.Validators; using BenchmarkDotNet.Reports; namespace BenchmarkDotNet.Configs { public class ManualConfig : IConfig { private readonly List<IColumnProvider> columnProviders = new List<IColumnProvider>(); private readonly List<IExporter> exporters = new List<IExporter>(); private readonly List<ILogger> loggers = new List<ILogger>(); private readonly List<IDiagnoser> diagnosers = new List<IDiagnoser>(); private readonly List<IAnalyser> analysers = new List<IAnalyser>(); private readonly List<IValidator> validators = new List<IValidator>(); private readonly List<Job> jobs = new List<Job>(); private readonly List<HardwareCounter> hardwareCounters = new List<HardwareCounter>(); private readonly List<IFilter> filters = new List<IFilter>(); private IOrderProvider orderProvider = null; private ISummaryStyle summaryStyle = null; private readonly HashSet<BenchmarkLogicalGroupRule> logicalGroupRules = new HashSet<BenchmarkLogicalGroupRule>(); public IEnumerable<IColumnProvider> GetColumnProviders() => columnProviders; public IEnumerable<ILogger> GetLoggers() => loggers; public IEnumerable<IValidator> GetValidators() => validators; public IEnumerable<Job> GetJobs() => jobs; public IEnumerable<HardwareCounter> GetHardwareCounters() => hardwareCounters; public IEnumerable<IFilter> GetFilters() => filters; public IOrderProvider GetOrderProvider() => orderProvider; public ISummaryStyle GetSummaryStyle() => summaryStyle; public IEnumerable<BenchmarkLogicalGroupRule> GetLogicalGroupRules() => logicalGroupRules; public ConfigUnionRule UnionRule { get; set; } = ConfigUnionRule.Union; public bool KeepBenchmarkFiles { get; set; } public string ArtifactsPath { get; set; } public Encoding Encoding { get; set; } public void Add(params IColumn[] newColumns) => columnProviders.AddRange(newColumns.Select(c => c.ToProvider())); public void Add(params IColumnProvider[] newColumnProviders) => columnProviders.AddRange(newColumnProviders); public void Add(params IExporter[] newExporters) => exporters.AddRange(newExporters); public void Add(params ILogger[] newLoggers) => loggers.AddRange(newLoggers); public void Add(params IDiagnoser[] newDiagnosers) => diagnosers.AddRange(newDiagnosers); public void Add(params IAnalyser[] newAnalysers) => analysers.AddRange(newAnalysers); public void Add(params IValidator[] newValidators) => validators.AddRange(newValidators); public void Add(params Job[] newJobs) => jobs.AddRange(newJobs.Select(j => j.Freeze())); // DONTTOUCH: please DO NOT remove .Freeze() call. public void Add(params HardwareCounter[] newHardwareCounters) => hardwareCounters.AddRange(newHardwareCounters); public void Add(params IFilter[] newFilters) => filters.AddRange(newFilters); public void Set(IOrderProvider provider) => orderProvider = provider ?? orderProvider; public void Set(ISummaryStyle style) => summaryStyle = style ?? summaryStyle; public void Set(Encoding encoding) => Encoding = encoding; public void Add(params BenchmarkLogicalGroupRule[] rules) => AddRules(rules); public void Add(IConfig config) { columnProviders.AddRange(config.GetColumnProviders()); exporters.AddRange(config.GetExporters()); loggers.AddRange(config.GetLoggers()); diagnosers.AddRange(config.GetDiagnosers()); analysers.AddRange(config.GetAnalysers()); jobs.AddRange(config.GetJobs()); validators.AddRange(config.GetValidators()); hardwareCounters.AddRange(config.GetHardwareCounters()); filters.AddRange(config.GetFilters()); orderProvider = config.GetOrderProvider() ?? orderProvider; KeepBenchmarkFiles |= config.KeepBenchmarkFiles; ArtifactsPath = config.ArtifactsPath ?? ArtifactsPath; Encoding = config.Encoding ?? Encoding; summaryStyle = summaryStyle ?? config.GetSummaryStyle(); AddRules(config.GetLogicalGroupRules()); } private void AddRules(IEnumerable<BenchmarkLogicalGroupRule> rules) { foreach (var rule in rules) logicalGroupRules.Add(rule); } public IEnumerable<IDiagnoser> GetDiagnosers() { if (hardwareCounters.IsEmpty()) return diagnosers; var hardwareCountersDiagnoser = DiagnosersLoader.GetImplementation<IHardwareCountersDiagnoser>(); if(hardwareCountersDiagnoser != default(IDiagnoser)) return diagnosers.Union(new [] { hardwareCountersDiagnoser }); return diagnosers; } public IEnumerable<IExporter> GetExporters() { var allDiagnosers = GetDiagnosers().ToArray(); foreach (var exporter in exporters) yield return exporter; foreach (var diagnoser in allDiagnosers) foreach (var exporter in diagnoser.Exporters) yield return exporter; var hardwareCounterDiagnoser = allDiagnosers.OfType<IHardwareCountersDiagnoser>().SingleOrDefault(); var disassemblyDiagnoser = allDiagnosers.OfType<IDisassemblyDiagnoser>().SingleOrDefault(); if (hardwareCounterDiagnoser != null && disassemblyDiagnoser != null) yield return new InstructionPointerExporter(hardwareCounterDiagnoser, disassemblyDiagnoser); } public IEnumerable<IAnalyser> GetAnalysers() { var allDiagnosers = GetDiagnosers().ToArray(); foreach (var analyser in analysers) yield return analyser; foreach (var diagnoser in allDiagnosers) foreach (var analyser in diagnoser.Analysers) yield return analyser; } public static ManualConfig CreateEmpty() => new ManualConfig(); public static ManualConfig Create(IConfig config) { var manualConfig = new ManualConfig(); manualConfig.Add(config); return manualConfig; } public static ManualConfig Union(IConfig globalConfig, IConfig localConfig) { var manualConfig = new ManualConfig(); switch (localConfig.UnionRule) { case ConfigUnionRule.AlwaysUseLocal: manualConfig.Add(localConfig); manualConfig.Add(globalConfig.GetFilters().ToArray()); // the filters should be merged anyway break; case ConfigUnionRule.AlwaysUseGlobal: manualConfig.Add(globalConfig); manualConfig.Add(localConfig.GetFilters().ToArray()); // the filters should be merged anyway break; case ConfigUnionRule.Union: manualConfig.Add(globalConfig); manualConfig.Add(localConfig); break; default: throw new ArgumentOutOfRangeException(); } return manualConfig; } public static IConfig Parse(string[] args) => new ConfigParser().Parse(args); public static void PrintOptions(ILogger logger, int prefixWidth, int outputWidth) => new ConfigParser().PrintOptions(logger, prefixWidth: prefixWidth, outputWidth: outputWidth); } }
46.085714
147
0.663236
[ "MIT" ]
dvorn/BenchmarkDotNet
src/BenchmarkDotNet/Configs/ManualConfig.cs
8,067
C#
using eSocialBr.Classes.Enums; using System; using System.Collections.Generic; using System.Text; namespace eSocialBr.Classes { /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.w3.org/2000/09/xmldsig#")] [System.Xml.Serialization.XmlRootAttribute("X509Data", Namespace = "http://www.w3.org/2000/09/xmldsig#", IsNullable = false)] public partial class X509DataType { private object[] itemsField; private ItemsChoiceType[] itemsElementNameField; /// <remarks/> [System.Xml.Serialization.XmlAnyElementAttribute()] [System.Xml.Serialization.XmlElementAttribute("X509CRL", typeof(byte[]), DataType = "base64Binary")] [System.Xml.Serialization.XmlElementAttribute("X509Certificate", typeof(byte[]), DataType = "base64Binary")] [System.Xml.Serialization.XmlElementAttribute("X509IssuerSerial", typeof(X509IssuerSerialType))] [System.Xml.Serialization.XmlElementAttribute("X509SKI", typeof(byte[]), DataType = "base64Binary")] [System.Xml.Serialization.XmlElementAttribute("X509SubjectName", typeof(string))] [System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemsElementName")] public object[] Items { get { return this.itemsField; } set { this.itemsField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("ItemsElementName")] [System.Xml.Serialization.XmlIgnoreAttribute()] public ItemsChoiceType[] ItemsElementName { get { return this.itemsElementNameField; } set { this.itemsElementNameField = value; } } } }
35.982759
129
0.637278
[ "MIT" ]
AOPack/eSocialBr
eSocialBr/eSocialBr.Classes/X509DataType.cs
2,089
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Reflection; namespace EpgTimer { public class MenuManager { private Dictionary<CtxmCode, CtxmData> DefCtxmData;//デフォルトのコンテキストメニュー private Dictionary<CtxmCode, List<ICommand>> DefCtxmCmdList;//デフォルトのコンテキストメニューのコマンドリスト private CtxmData AddInfoSearchMenu;//簡易検索用の追加メニュー private Dictionary<CtxmCode, CtxmData> WorkCtxmData;//現在のコンテキストメニュー // private Dictionary<CtxmCode, List<ICommand>> WorCtxmCmdList;//各ビューのコンテキストメニューのコマンドリスト private Dictionary<CtxmCode, List<ICommand>> WorkGestureCmdList;//各ビューのショートカット管理用のコマンドリスト private Dictionary<CtxmCode, List<ICommand>> WorkDelGesCmdList;//メニューから削除され、shortcut無効なコマンド public MenuCmds MC { get; private set; } //コマンドオプション関係 public MenuManager() { MC = new MenuCmds(); SetDefCtxmData(); SetDefGestureCmdList(); } //コンテキストメニューの定義 private void SetDefCtxmData() { //各画面のコンテキストメニュー。空にならないようとりあえず全部作っておく。 DefCtxmData = new Dictionary<CtxmCode, CtxmData>(); foreach (CtxmCode code in Enum.GetValues(typeof(CtxmCode))) { DefCtxmData.Add(code, new CtxmData(code)); } //サブメニューなど設定のあるものは、情報固定のためいったん定義する。 var cm_Separator = new CtxmItemData(EpgCmdsEx.SeparatorString, EpgCmdsEx.Separator); //予約追加サブメニュー 実行時、セパレータ以降にプリセットを展開する。 var cm_AddMenu = new CtxmItemData("予約追加", EpgCmdsEx.AddMenu); cm_AddMenu.Items.Add(new CtxmItemData("ダイアログ表示...", EpgCmds.ShowDialog, 1)); cm_AddMenu.Items.Add(new CtxmItemData(cm_Separator)); cm_AddMenu.Items.Add(new CtxmItemData("デフォルト", EpgCmds.AddOnPreset, 0));//仮 //予約変更サブメニューの各サブメニュー ////自動登録の有効/無効 var cm_ChgKeyEnabledMenu = new CtxmItemData("自動登録有効", EpgCmdsEx.ChgKeyEnabledMenu); cm_ChgKeyEnabledMenu.Items.Add(new CtxmItemData("有効 (_0)", EpgCmds.ChgKeyEnabled, 0)); cm_ChgKeyEnabledMenu.Items.Add(new CtxmItemData("無効 (_1)", EpgCmds.ChgKeyEnabled, 1)); ////プリセット変更 実行時、サブメニューにプリセットを展開する。 var cm_ChgOnPresetMenu = new CtxmItemData("プリセットへ変更", EpgCmdsEx.ChgOnPresetMenu); cm_ChgOnPresetMenu.Items.Add(new CtxmItemData("デフォルト", EpgCmds.ChgOnPreset, 0));//仮 ////予約モード変更 var cm_ChgResModeMenu = new CtxmItemData("予約モード変更", EpgCmdsEx.ChgResModeMenu); cm_ChgResModeMenu.Items.Add(new CtxmItemData("EPG予約 (_0)", EpgCmds.ChgResMode, 0)); cm_ChgResModeMenu.Items.Add(new CtxmItemData("プログラム予約 (_1)", EpgCmds.ChgResMode, 1)); ////録画モード var cm_ChgRecmodeMenu = new CtxmItemData("録画モード", EpgCmdsEx.ChgRecmodeMenu); for (int i = 0; i <= 5; i++) { cm_ChgRecmodeMenu.Items.Add(new CtxmItemData(string.Format("{0} (_{1})" , CommonManager.ConvertRecModeText(i), i), EpgCmds.ChgRecmode, i)); } ////優先度 var cm_ChgPriorityMenu = new CtxmItemData("優先度", EpgCmdsEx.ChgPriorityMenu); for (int i = 1; i <= 5; i++) { cm_ChgPriorityMenu.Items.Add(new CtxmItemData( CommonManager.ConvertPriorityText(i).Insert(1, string.Format(" (_{0})", i)), EpgCmds.ChgPriority, i)); } ////イベントリレー変更 var cm_ChgRelayMenu = new CtxmItemData("イベントリレー追従", EpgCmdsEx.ChgRelayMenu); for (int i = 0; i <= 1; i++) { cm_ChgRelayMenu.Items.Add(new CtxmItemData(string.Format("{0} (_{1})" , CommonManager.ConvertYesNoText(i), i), EpgCmds.ChgRelay, i)); } ////ぴったり変更 var cm_ChgPittariMenu = new CtxmItemData("ぴったり(?)録画", EpgCmdsEx.ChgPittariMenu); for (int i = 0; i <= 1; i++) { cm_ChgPittariMenu.Items.Add(new CtxmItemData(string.Format("{0} (_{1})" , CommonManager.ConvertYesNoText(i), i), EpgCmds.ChgPittari, i)); } ////チューナー変更、実行時、セパレータ以降に一覧を展開する。 var cm_ChgTunerMenu = new CtxmItemData("チューナー", EpgCmdsEx.ChgTunerMenu); cm_ChgTunerMenu.Items.Add(new CtxmItemData("自動", EpgCmds.ChgTuner, 0)); cm_ChgTunerMenu.Items.Add(new CtxmItemData(cm_Separator)); ////開始マージン var cm_ChgMarginStartMenu = new CtxmItemData("開始マージン", EpgCmdsEx.ChgMarginStartMenu); cm_ChgMarginStartMenu.Items.Add(new CtxmItemData("デフォルトへ変更", EpgCmds.ChgMarginStart, 0)); cm_ChgMarginStartMenu.Items.Add(new CtxmItemData("指定値へ変更...", EpgCmds.ChgMarginValue, 1)); cm_ChgMarginStartMenu.Items.Add(new CtxmItemData(cm_Separator)); new List<int> { -60, -30, -5, -1, 1, 5, 30, 60 }.ForEach(val => cm_ChgMarginStartMenu.Items.Add( new CtxmItemData(string.Format("{0:増やす : +0;減らす : -0} 秒", val), EpgCmds.ChgMarginStart, val))); ////終了マージン、複製してコマンドだけ差し替える。 var cm_ChgMarginEndMenu = new CtxmItemData("終了マージン", cm_ChgMarginStartMenu); cm_ChgMarginEndMenu.Command = EpgCmdsEx.ChgMarginEndMenu; cm_ChgMarginEndMenu.Items = cm_ChgMarginStartMenu.Items.DeepClone(); cm_ChgMarginEndMenu.Items.ForEach(menu => { if (menu.Command == EpgCmds.ChgMarginStart) menu.Command = EpgCmds.ChgMarginEnd; }); cm_ChgMarginEndMenu.Items.ForEach(menu => { if (menu.Command == EpgCmds.ChgMarginValue) menu.ID = 2; }); //予約変更サブメニュー登録 var cm_ChangeMenu = new CtxmItemData("変更", EpgCmdsEx.ChgMenu); cm_ChangeMenu.Items.Add(new CtxmItemData("ダイアログ表示...", EpgCmds.ShowDialog)); cm_ChangeMenu.Items.Add(new CtxmItemData(cm_Separator)); cm_ChangeMenu.Items.Add(new CtxmItemData("自動登録有効", cm_ChgKeyEnabledMenu)); cm_ChangeMenu.Items.Add(new CtxmItemData("プリセットへ変更", cm_ChgOnPresetMenu)); cm_ChangeMenu.Items.Add(new CtxmItemData("予約モード変更", cm_ChgResModeMenu)); cm_ChangeMenu.Items.Add(new CtxmItemData("まとめて録画設定を変更...", EpgCmds.ChgBulkRecSet)); cm_ChangeMenu.Items.Add(new CtxmItemData("まとめてジャンル絞り込みを変更...", EpgCmds.ChgGenre)); cm_ChangeMenu.Items.Add(new CtxmItemData(cm_Separator)); cm_ChangeMenu.Items.Add(new CtxmItemData("録画モード", cm_ChgRecmodeMenu)); cm_ChangeMenu.Items.Add(new CtxmItemData("優先度", cm_ChgPriorityMenu)); cm_ChangeMenu.Items.Add(new CtxmItemData("イベントリレー追従", cm_ChgRelayMenu)); cm_ChangeMenu.Items.Add(new CtxmItemData("ぴったり(?)録画", cm_ChgPittariMenu)); cm_ChangeMenu.Items.Add(new CtxmItemData("チューナー", cm_ChgTunerMenu)); cm_ChangeMenu.Items.Add(new CtxmItemData("開始マージン", cm_ChgMarginStartMenu)); cm_ChangeMenu.Items.Add(new CtxmItemData("終了マージン", cm_ChgMarginEndMenu)); CtxmData ctmd = DefCtxmData[CtxmCode.EditChgMenu]; ctmd.Items = cm_ChangeMenu.Items; //ビューモードサブメニュー var cm_ViewMenu = new CtxmItemData("表示モード", EpgCmdsEx.ViewMenu); for (int i = 0; i <= 2; i++) { cm_ViewMenu.Items.Add(new CtxmItemData(CommonManager.ConvertViewModeText(i) + string.Format(" (_{0})", i + 1), EpgCmds.ViewChgMode, i)); } cm_ViewMenu.Items.Add(new CtxmItemData(cm_Separator)); cm_ViewMenu.Items.Add(new CtxmItemData("表示設定...(_S)", EpgCmds.ViewChgSet)); cm_ViewMenu.Items.Add(new CtxmItemData("一時的な変更をクリア(_R)", EpgCmds.ViewChgReSet)); //共通メニューの追加用リスト var AddAppendMenus = new List<CtxmItemData>(); AddAppendMenus.Add(new CtxmItemData(cm_Separator)); AddAppendMenus.Add(new CtxmItemData("番組名をコピー", EpgCmds.CopyTitle)); AddAppendMenus.Add(new CtxmItemData("番組情報をコピー", EpgCmds.CopyContent)); AddAppendMenus.Add(new CtxmItemData("番組名で予約情報検索", EpgCmds.InfoSearchTitle)); AddAppendMenus.Add(new CtxmItemData("番組名をネットで検索", EpgCmds.SearchTitle)); var AddMenuSetting = new List<CtxmItemData>(); AddMenuSetting.Add(new CtxmItemData(cm_Separator)); AddMenuSetting.Add(new CtxmItemData("右クリックメニューの設定...", EpgCmds.MenuSetting)); //メニューアイテム:予約一覧 ctmd = DefCtxmData[CtxmCode.ReserveView]; ctmd.Items.Add(new CtxmItemData("予約←→無効", EpgCmds.ChgOnOff)); ctmd.Items.Add(new CtxmItemData("変更(_C)", cm_ChangeMenu)); ctmd.Items.Add(new CtxmItemData("コピーを追加", EpgCmds.CopyItem)); ctmd.Items.Add(new CtxmItemData("削除", EpgCmds.Delete)); ctmd.Items.Add(new CtxmItemData("新規プログラム予約...", EpgCmds.ShowAddDialog)); ctmd.Items.Add(new CtxmItemData("チューナー画面へジャンプ", EpgCmds.JumpTuner)); ctmd.Items.Add(new CtxmItemData("番組表へジャンプ", EpgCmds.JumpTable)); ctmd.Items.Add(new CtxmItemData("自動予約登録変更", EpgCmdsEx.ShowAutoAddDialogMenu)); ctmd.Items.Add(new CtxmItemData("番組名でキーワード予約作成...", EpgCmds.ToAutoadd)); ctmd.Items.Add(new CtxmItemData("追っかけ再生", EpgCmds.Play)); ctmd.Items.Add(new CtxmItemData("録画フォルダを開く", EpgCmdsEx.OpenFolderMenu)); ctmd.Items.AddRange(AddAppendMenus.DeepClone()); ctmd.Items.AddRange(AddMenuSetting.DeepClone()); //メニューアイテム:使用予定チューナー ctmd = DefCtxmData[CtxmCode.TunerReserveView]; ctmd.Items.Add(new CtxmItemData("予約←→無効", EpgCmds.ChgOnOff)); ctmd.Items.Add(new CtxmItemData("変更(_C)", cm_ChangeMenu)); ctmd.Items.Add(new CtxmItemData("コピーを追加", EpgCmds.CopyItem)); ctmd.Items.Add(new CtxmItemData("削除", EpgCmds.Delete)); ctmd.Items.Add(new CtxmItemData("新規プログラム予約...", EpgCmds.ShowAddDialog)); ctmd.Items.Add(new CtxmItemData("予約一覧へジャンプ", EpgCmds.JumpReserve)); ctmd.Items.Add(new CtxmItemData("番組表へジャンプ", EpgCmds.JumpTable)); ctmd.Items.Add(new CtxmItemData("自動予約登録変更", EpgCmdsEx.ShowAutoAddDialogMenu)); ctmd.Items.Add(new CtxmItemData("番組名でキーワード予約作成...", EpgCmds.ToAutoadd)); ctmd.Items.Add(new CtxmItemData("追っかけ再生", EpgCmds.Play)); ctmd.Items.Add(new CtxmItemData("録画フォルダを開く", EpgCmdsEx.OpenFolderMenu)); ctmd.Items.AddRange(AddAppendMenus.DeepClone()); ctmd.Items.AddRange(AddMenuSetting.DeepClone()); //メニューアイテム:録画済み一覧 ctmd = DefCtxmData[CtxmCode.RecInfoView]; ctmd.Items.Add(new CtxmItemData("録画情報...", EpgCmds.ShowDialog)); ctmd.Items.Add(new CtxmItemData("削除", EpgCmds.Delete)); ctmd.Items.Add(new CtxmItemData("プロテクト←→解除", EpgCmds.ProtectChange)); ctmd.Items.Add(new CtxmItemData("番組表へジャンプ", EpgCmds.JumpTable)); ctmd.Items.Add(new CtxmItemData("自動予約登録変更", EpgCmdsEx.ShowAutoAddDialogMenu)); ctmd.Items.Add(new CtxmItemData("番組名でキーワード予約作成...", EpgCmds.ToAutoadd)); ctmd.Items.Add(new CtxmItemData("再生", EpgCmds.Play)); ctmd.Items.Add(new CtxmItemData("録画フォルダを開く", EpgCmds.OpenFolder));//他の画面と違う ctmd.Items.AddRange(AddAppendMenus.DeepClone()); ctmd.Items.AddRange(AddMenuSetting.DeepClone()); //メニューアイテム:キーワード自動予約登録 ctmd = DefCtxmData[CtxmCode.EpgAutoAddView]; ctmd.Items.Add(new CtxmItemData("予約一覧(_L)", EpgCmdsEx.ShowReserveDialogMenu)); ctmd.Items.Add(new CtxmItemData("変更(_C)", cm_ChangeMenu)); ctmd.Items.Add(new CtxmItemData("コピーを追加", EpgCmds.CopyItem)); ctmd.Items.Add(new CtxmItemData("削除", EpgCmds.Delete)); ctmd.Items.Add(new CtxmItemData("予約ごと削除", EpgCmds.Delete2)); ctmd.Items.Add(new CtxmItemData("予約を自動登録に合わせる", EpgCmds.AdjustReserve)); ctmd.Items.Add(new CtxmItemData("次の予約(予約一覧)へジャンプ", EpgCmds.JumpReserve)); ctmd.Items.Add(new CtxmItemData("次の予約(チューナー画面)へジャンプ", EpgCmds.JumpTuner)); ctmd.Items.Add(new CtxmItemData("次の予約(番組表)へジャンプ", EpgCmds.JumpTable)); ctmd.Items.Add(new CtxmItemData("新規自動予約登録...", EpgCmds.ShowAddDialog)); ctmd.Items.Add(new CtxmItemData("録画フォルダを開く", EpgCmdsEx.OpenFolderMenu)); ctmd.Items.Add(new CtxmItemData(cm_Separator)); ctmd.Items.Add(new CtxmItemData("Andキーワードをコピー", EpgCmds.CopyTitle)); ctmd.Items.Add(new CtxmItemData("Andキーワードで予約情報検索", EpgCmds.InfoSearchTitle)); ctmd.Items.Add(new CtxmItemData("Andキーワードをネットで検索", EpgCmds.SearchTitle)); ctmd.Items.Add(new CtxmItemData("Notキーワードをコピー", EpgCmds.CopyNotKey)); ctmd.Items.Add(new CtxmItemData("Notキーワードに貼り付け", EpgCmds.SetNotKey)); ctmd.Items.AddRange(AddMenuSetting.DeepClone()); //メニューアイテム:プログラム自動予約登録 ctmd = DefCtxmData[CtxmCode.ManualAutoAddView]; ctmd.Items.Add(new CtxmItemData("予約一覧(_L)", EpgCmdsEx.ShowReserveDialogMenu)); ctmd.Items.Add(new CtxmItemData("変更(_C)", cm_ChangeMenu)); ctmd.Items.Add(new CtxmItemData("コピーを追加", EpgCmds.CopyItem)); ctmd.Items.Add(new CtxmItemData("削除", EpgCmds.Delete)); ctmd.Items.Add(new CtxmItemData("予約ごと削除", EpgCmds.Delete2)); ctmd.Items.Add(new CtxmItemData("予約を自動登録に合わせる", EpgCmds.AdjustReserve)); ctmd.Items.Add(new CtxmItemData("次の予約(予約一覧)へジャンプ", EpgCmds.JumpReserve)); ctmd.Items.Add(new CtxmItemData("次の予約(チューナー画面)へジャンプ", EpgCmds.JumpTuner)); ctmd.Items.Add(new CtxmItemData("次の予約(番組表)へジャンプ", EpgCmds.JumpTable)); ctmd.Items.Add(new CtxmItemData("番組名でキーワード予約作成...", EpgCmds.ToAutoadd)); ctmd.Items.Add(new CtxmItemData("新規自動予約登録...", EpgCmds.ShowAddDialog)); ctmd.Items.Add(new CtxmItemData("録画フォルダを開く", EpgCmdsEx.OpenFolderMenu)); ctmd.Items.Add(new CtxmItemData(cm_Separator)); ctmd.Items.Add(new CtxmItemData("番組名をコピー", EpgCmds.CopyTitle)); ctmd.Items.Add(new CtxmItemData("番組名で予約情報検索", EpgCmds.InfoSearchTitle)); ctmd.Items.Add(new CtxmItemData("番組名をネットで検索", EpgCmds.SearchTitle)); ctmd.Items.AddRange(AddMenuSetting.DeepClone()); //メニューアイテム:番組表 ctmd = DefCtxmData[CtxmCode.EpgView]; ctmd.Items.Add(new CtxmItemData("簡易予約/予約←→無効", EpgCmds.ChgOnOff)); ctmd.Items.Add(new CtxmItemData("予約追加(_A)", cm_AddMenu)); ctmd.Items.Add(new CtxmItemData("変更(_C)", cm_ChangeMenu)); ctmd.Items.Add(new CtxmItemData("コピーを追加", EpgCmds.CopyItem)); ctmd.Items.Add(new CtxmItemData("削除", EpgCmds.Delete)); ctmd.Items.Add(new CtxmItemData("予約一覧へジャンプ", EpgCmds.JumpReserve)); ctmd.Items.Add(new CtxmItemData("チューナー画面へジャンプ", EpgCmds.JumpTuner)); ctmd.Items.Add(new CtxmItemData("番組表(標準モード)へジャンプ", EpgCmds.JumpTable)); ctmd.Items.Add(new CtxmItemData("自動予約登録変更", EpgCmdsEx.ShowAutoAddDialogMenu)); ctmd.Items.Add(new CtxmItemData("番組名でキーワード予約作成...", EpgCmds.ToAutoadd)); ctmd.Items.Add(new CtxmItemData("追っかけ再生", EpgCmds.Play)); ctmd.Items.Add(new CtxmItemData("録画フォルダを開く", EpgCmdsEx.OpenFolderMenu)); ctmd.Items.AddRange(AddAppendMenus.DeepClone()); ctmd.Items.Add(new CtxmItemData(cm_Separator)); ctmd.Items.Add(new CtxmItemData("表示モード(_V)", cm_ViewMenu)); ctmd.Items.AddRange(AddMenuSetting.DeepClone()); //メニューアイテム:検索ダイアログ、キーワード予約ダイアログ ctmd = DefCtxmData[CtxmCode.SearchWindow]; ctmd.Items.Add(new CtxmItemData("簡易予約/予約←→無効", EpgCmds.ChgOnOff)); ctmd.Items.Add(new CtxmItemData("予約追加(_A)", cm_AddMenu)); ctmd.Items.Add(new CtxmItemData("変更(_C)", cm_ChangeMenu)); ctmd.Items.Add(new CtxmItemData("コピーを追加", EpgCmds.CopyItem)); ctmd.Items.Add(new CtxmItemData("削除", EpgCmds.Delete)); ctmd.Items.Add(new CtxmItemData("予約一覧へジャンプ", EpgCmds.JumpReserve)); ctmd.Items.Add(new CtxmItemData("チューナー画面へジャンプ", EpgCmds.JumpTuner)); ctmd.Items.Add(new CtxmItemData("番組表へジャンプ", EpgCmds.JumpTable)); ctmd.Items.Add(new CtxmItemData("自動予約登録変更", EpgCmdsEx.ShowAutoAddDialogMenu)); ctmd.Items.Add(new CtxmItemData("番組名で再検索", EpgCmds.ReSearch)); ctmd.Items.Add(new CtxmItemData("番組名で再検索(別ウィンドウ)", EpgCmds.ReSearch2)); ctmd.Items.Add(new CtxmItemData("追っかけ再生", EpgCmds.Play)); ctmd.Items.Add(new CtxmItemData("録画フォルダを開く", EpgCmdsEx.OpenFolderMenu)); ctmd.Items.AddRange(AddAppendMenus.DeepClone()); ctmd.Items.AddRange(AddMenuSetting.DeepClone()); //メニューアイテム:予約情報検索(デフォルト・複数選択) ctmd = DefCtxmData[CtxmCode.InfoSearchWindow]; ctmd.Items.Add(new CtxmItemData("一覧へジャンプ", EpgCmds.JumpListView)); ctmd.Items.Add(new CtxmItemData("番組名/ANDキーワードで再検索", EpgCmds.ReSearch)); ctmd.Items.Add(new CtxmItemData("番組名/ANDキーワードで再検索(別ウィンドウ)", EpgCmds.ReSearch2)); ctmd.Items.Add(new CtxmItemData(cm_Separator)); ctmd.Items.Add(new CtxmItemData("ダイアログ表示...", EpgCmds.ShowDialog)); ctmd.Items.Add(new CtxmItemData("有効・無効/プロテクト切替え", EpgCmds.ChgOnOff)); ctmd.Items.Add(new CtxmItemData("削除", EpgCmds.Delete)); ctmd.Items.Add(new CtxmItemData(cm_Separator)); ctmd.Items.Add(new CtxmItemData("番組名/ANDキーワードをコピー", EpgCmds.CopyTitle)); ctmd.Items.Add(new CtxmItemData("番組名/ANDキーワードをネットで検索", EpgCmds.SearchTitle)); ctmd.Items.AddRange(AddMenuSetting.DeepClone()); //メニューアイテム:予約情報検索(個別選択の追加メニュー) AddInfoSearchMenu = new CtxmData(CtxmCode.InfoSearchWindow); AddInfoSearchMenu.Items.AddRange(ctmd.Items.Take(3)); } private void SetDefGestureCmdList() { DefCtxmCmdList = new Dictionary<CtxmCode, List<ICommand>>(); foreach (var ctxm in DefCtxmData) { DefCtxmCmdList.Add(ctxm.Key, GetCmdFromMenuItem(ctxm.Value.Items).Distinct().ToList()); } } private List<ICommand> GetCmdFromMenuItem(List<CtxmItemData> items) { var clist = new List<ICommand>(); items.ForEach(item => { if (item != null && EpgCmdsEx.IsDummyCmd(item.Command) == false) { clist.Add(item.Command); } clist.AddRange(GetCmdFromMenuItem(item.Items)); }); return clist; } public void ReloadWorkData() { MC.SetWorkCmdOptions(); SetWorkCxtmData(); SetWorkGestureCmdList(); //簡易設定側の、修正済みデータの書き戻し Settings.Instance.MenuSet = GetWorkMenuSettingData(); } private void SetWorkCxtmData() { WorkCtxmData = new Dictionary<CtxmCode, CtxmData>(); foreach (var data in DefCtxmData.Values) { WorkCtxmData.Add(data.ctxmCode, GetWorkCtxmDataView(data.ctxmCode)); } //編集メニューの差し替え foreach (CtxmData ctxm in WorkCtxmData.Values) { foreach (var chgMenu in ctxm.Items.Where(item => item.Command == EpgCmdsEx.ChgMenu)) { chgMenu.Items = WorkCtxmData[CtxmCode.EditChgMenu].Items.DeepClone(); } } } private CtxmData GetWorkCtxmDataView(CtxmCode code) { CtxmData ctxm = new CtxmData(code); CtxmData ctxmDef = DefCtxmData[code]; //存在するものをコピーしていく。編集メニューは常に個別設定が有効になる。 if (Settings.Instance.MenuSet.IsManualAssign.Contains(code) == true || code == CtxmCode.EditChgMenu) { CtxmSetting ctxmEdited = Settings.Instance.MenuSet.ManualMenuItems.FindData(code); if (ctxmEdited == null) { //編集サブメニューの場合は、初期無効アイテムを削除したデフォルトセッティングを返す。 return code != CtxmCode.EditChgMenu ? ctxmDef.DeepClone() : GetDefaultChgSubMenuCtxmData(); } ctxmEdited.Items.ForEach(setMenuString => { CtxmItemData item1 = ctxmDef.Items.Find(item => item.Header == setMenuString); if (item1 != null) { ctxm.Items.Add(item1.DeepClone()); } }); } else { ctxmDef.Items.ForEach(item1 => { if (MC.WorkCmdOptions[item1.Command].IsMenuEnabled == true) { ctxm.Items.Add(item1.DeepClone()); } }); } //セパレータの整理 SweepSeparators(ctxm); return ctxm; } private void SweepSeparators(CtxmData ctxm) { //・連続したセパレータの除去 for (int i = ctxm.Items.Count - 1; i >= 1; i--) { if (ctxm.Items[i].Command == EpgCmdsEx.Separator && ctxm.Items[i - 1].Command == EpgCmdsEx.Separator) { ctxm.Items.RemoveAt(i); } } //・先頭と最後のセパレータ除去 if (ctxm.Items.Count != 0 && ctxm.Items[ctxm.Items.Count - 1].Command == EpgCmdsEx.Separator) { ctxm.Items.RemoveAt(ctxm.Items.Count - 1); } if (ctxm.Items.Count != 0 && ctxm.Items[0].Command == EpgCmdsEx.Separator) { ctxm.Items.RemoveAt(0); } } private void SetWorkGestureCmdList() { //WorCtxmCmdList = new Dictionary<CtxmCode, List<ICommand>>(); WorkGestureCmdList = new Dictionary<CtxmCode, List<ICommand>>(); WorkDelGesCmdList = new Dictionary<CtxmCode, List<ICommand>>(); foreach (var ctxm in WorkCtxmData) { var cmdlist = GetCmdFromMenuItem(ctxm.Value.Items); //var cmdlist = GetCmdFromMenuItem(ctxm.Value.Items).Distinct().ToList(); //コンテキストメニューのコマンドリスト //WorCtxmCmdList.Add(ctxm.Key, cmdlist.ToList()); //常時有効なショートカットのあるコマンドを追加 cmdlist.AddRange(DefCtxmCmdList[ctxm.Key].Where(command => MC.WorkCmdOptions[command].IsGesNeedMenu == false)); cmdlist = cmdlist.Distinct().ToList(); //無効なコマンドを除外 cmdlist = cmdlist.Where(command => MC.WorkCmdOptions[command].IsGestureEnabled == true).ToList(); WorkGestureCmdList.Add(ctxm.Key, cmdlist); //ショートカット無効なコマンドリスト WorkDelGesCmdList.Add(ctxm.Key, DefCtxmCmdList[ctxm.Key].Except(cmdlist).ToList()); } } //ショートカットをデフォルト値に戻す public void SetDefaultGestures(MenuSettingData info) { foreach (MenuCmds.CmdData item in MC.DefCmdOptions.Values.Where(item => item.IsSaveSetting == true)) { MenuSettingData.CmdSaveData data = info.EasyMenuItems.Find(d => d.GetCommand() == item.Command); if (data != null) data.SetGestuers(item.Gestures); } } //設定画面へデフォルト値を送る public MenuSettingData GetDefaultMenuSettingData() { var set = new MenuSettingData(); set.EasyMenuItems = MC.GetDefEasyMenuSetting(); set.ManualMenuItems = GetManualMenuSetting(DefCtxmData); //編集メニュー初期値の設定、差し替え set.ManualMenuItems.RemoveAll(item => item.ctxmCode == CtxmCode.EditChgMenu); set.ManualMenuItems.Add(new CtxmSetting(GetDefaultChgSubMenuCtxmData())); return set; } //設定画面へメニュー編集選択画面用の全てを含む初期値を送る public List<CtxmSetting> GetDefaultCtxmSettingForEditor() { return GetManualMenuSetting(DefCtxmData); } private CtxmData GetDefaultChgSubMenuCtxmData() { var set = new CtxmData(CtxmCode.EditChgMenu); DefCtxmData[CtxmCode.EditChgMenu].Items.ForEach(item => { //初期無効データは入れない if (MC.DefCmdOptions[item.Command].IsMenuEnabled == true) { set.Items.Add(item.DeepClone()); } }); return set; } private MenuSettingData GetWorkMenuSettingData() { var set = Settings.Instance.MenuSet.DeepClone(); set.EasyMenuItems = MC.GetWorkEasyMenuSetting(); foreach (CtxmCode code in Enum.GetValues(typeof(CtxmCode))) { //編集メニューは常にマニュアルモードと同等 if (set.IsManualAssign.Contains(code) == true || code == CtxmCode.EditChgMenu) { set.ManualMenuItems.RemoveAll(item => item.ctxmCode == code); set.ManualMenuItems.Add(new CtxmSetting(WorkCtxmData[code])); } else if (set.ManualMenuItems.Find(item => item.ctxmCode == code) == null) { set.ManualMenuItems.Add(new CtxmSetting(DefCtxmData[code])); } } return set; } private List<CtxmSetting> GetManualMenuSetting(Dictionary<CtxmCode, CtxmData> dic) { var cmManualMenuSetting = new List<CtxmSetting>(); foreach (CtxmCode code in Enum.GetValues(typeof(CtxmCode))) { cmManualMenuSetting.Add(new CtxmSetting(dic[code])); } return cmManualMenuSetting; } public bool IsGestureDisableOnView(ICommand icmd, CtxmCode code) { if (icmd == null) return false; MenuSettingData.CmdSaveData cmdData = Settings.Instance.MenuSet.EasyMenuItems.Find(data => data.GetCommand() == icmd); return cmdData != null && cmdData.IsGestureEnabled == false || WorkDelGesCmdList[code].Contains(icmd); } public List<ICommand> GetViewMenuCmdList(CtxmCode code) { return DefCtxmCmdList[code].ToList(); } public List<ICommand> GetWorkGestureCmdList(CtxmCode code) { return WorkGestureCmdList[code].ToList(); } public void CtxmGenerateContextMenuInfoSearch(ContextMenu ctxm, CtxmCode code) { CtxmData data = WorkCtxmData[code].DeepClone(); if (code != CtxmCode.InfoSearchWindow) { //他画面用の簡易検索メニューを削除 data.Items.Remove(data.Items.FirstOrDefault(d => d.Command == EpgCmds.InfoSearchTitle)); //簡易検索用のメニューを先頭に追加 var ISData = WorkCtxmData[CtxmCode.InfoSearchWindow].Items.Select(d => d.Command).ToList(); data.Items.Insert(0, new CtxmItemData(EpgCmdsEx.SeparatorString, EpgCmdsEx.Separator)); data.Items.InsertRange(0, AddInfoSearchMenu.Items.Where(item => ISData.Contains(item.Command))); SweepSeparators(data); } CtxmGenerateContextMenu(data, ctxm, code, true); } public void CtxmGenerateContextMenu(ContextMenu ctxm, CtxmCode code, bool shortcutTextforListType) { CtxmGenerateContextMenu(WorkCtxmData[code], ctxm, code, shortcutTextforListType); } private void CtxmGenerateContextMenu(CtxmData data, ContextMenu ctxm, CtxmCode code, bool shortcutTextforListType) { try { ctxm.Name = code.ToString(); CtxmConvertToMenuItems(data.Items, ctxm.Items, code, shortcutTextforListType); } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace); } } private void CtxmConvertToMenuItems(List<CtxmItemData> src, ItemCollection dest, CtxmCode code, bool shortcutTextforListType) { dest.Clear(); src.ForEach(data => { Control item; if (data.Command == EpgCmdsEx.Separator) { item = new Separator(); } else { var menu = new MenuItem(); menu.Header = data.Header; menu.Command = (EpgCmdsEx.IsDummyCmd(data.Command) ? null : data.Command); if (menu.Command != null) { if ((shortcutTextforListType == true || (MC.WorkCmdOptions[data.Command].GesTrg & MenuCmds.GestureTrg.ToView) == MenuCmds.GestureTrg.ToView) && (MC.WorkCmdOptions.ContainsKey(data.Command) == false || MC.WorkCmdOptions[data.Command].IsGestureEnabled == true) && data.ID == 0) { menu.InputGestureText = MenuBinds.GetInputGestureText(data.Command); } } menu.CommandParameter = new EpgCmdParam(typeof(MenuItem), code, data.ID); if (data.Items.Count != 0) CtxmConvertToMenuItems(data.Items, menu.Items, code, shortcutTextforListType); item = menu; } item.Tag = data.Command; item.ToolTip = GetCtxmTooltip(data.Command); ToolTipService.SetShowOnDisabled(item, true); dest.Add(item); }); } private string GetCtxmTooltip(ICommand icmd) { Func<bool, string, string, string, string> _ToggleModeTooltip = (mode, Caption, OnText, OffText) => { string ModeText = (mode == true ? OnText : OffText); string ToggleText = (mode == false ? OnText : OffText); return Caption + ModeText + " (Shift+クリックで一時的に'" + ToggleText + "')"; }; if (icmd == EpgCmds.ToAutoadd || icmd == EpgCmds.ReSearch || icmd == EpgCmds.ReSearch2) { return _ToggleModeTooltip(Settings.Instance.MenuSet.Keyword_Trim, "記号除去モード : ", "オン", "オフ"); } else if (icmd == EpgCmds.CopyTitle) { return _ToggleModeTooltip(Settings.Instance.MenuSet.CopyTitle_Trim, "記号除去モード : ", "オン", "オフ"); } else if (icmd == EpgCmds.CopyContent) { return _ToggleModeTooltip(Settings.Instance.MenuSet.CopyContentBasic, "取得モード : ", "基本情報のみ", "詳細情報"); } else if (icmd == EpgCmds.InfoSearchTitle) { return _ToggleModeTooltip(Settings.Instance.MenuSet.InfoSearchTitle_Trim, "記号除去モード : ", "オン", "オフ"); } else if (icmd == EpgCmds.SearchTitle) { return _ToggleModeTooltip(Settings.Instance.MenuSet.SearchTitle_Trim, "記号除去モード : ", "オン", "オフ"); } return null; } public void CtxmGenerateAddOnPresetItems(MenuItem menu) { CtxmGenerateOnPresetItems(menu, EpgCmds.AddOnPreset); } public void CtxmGenerateChgOnPresetItems(MenuItem menu) { CtxmGenerateOnPresetItems(menu, EpgCmds.ChgOnPreset); } public void CtxmGenerateOnPresetItems(MenuItem menu, ICommand icmd) { var delList = menu.Items.OfType<MenuItem>().Where(item => item.Command == icmd).ToList(); delList.ForEach(item => menu.Items.Remove(item)); if (menu.IsEnabled == false) return; foreach (var item in Settings.Instance.RecPresetList) { var menuItem = new MenuItem(); menuItem.Header = string.Format("プリセット - {0} (_{1})", item.DisplayName, item.ID); menuItem.Command = icmd; menuItem.CommandParameter = new EpgCmdParam(menu.CommandParameter as EpgCmdParam); (menuItem.CommandParameter as EpgCmdParam).ID = item.ID; menuItem.Tag = menuItem.Command; menu.Items.Add(menuItem); } } public void CtxmGenerateChgResModeAutoAddItems(MenuItem menu, IAutoAddTargetData info) { //クリア for (int i = menu.Items.Count - 1; i >= 2; i--) menu.Items.RemoveAt(i); if (menu.IsEnabled == false || info == null) return; CtxmGenerateChgAutoAddMenuItem(menu, info, EpgCmds.ChgResMode, true, false); if (menu.Items.Count > 2) { menu.Items.Insert(2, new Separator()); } } public void CtxmGenerateTunerMenuItems(MenuItem menu) { var delList = menu.Items.OfType<MenuItem>().Where(item => (item.CommandParameter as EpgCmdParam).ID != 0).ToList(); delList.ForEach(item => menu.Items.Remove(item)); if (menu.IsEnabled == false) return; foreach (var info in CommonManager.Instance.DB.TunerReserveList.Values.Where(info => info.tunerID != 0xFFFFFFFF) .Select(info => new TunerSelectInfo(info.tunerName, info.tunerID))) { var menuItem = new MenuItem(); menuItem.Header = string.Format("{0}", info); menuItem.Command = EpgCmds.ChgTuner; menuItem.CommandParameter = new EpgCmdParam(menu.CommandParameter as EpgCmdParam); (menuItem.CommandParameter as EpgCmdParam).ID = (int)info.ID; menuItem.Tag = menuItem.Command; menu.Items.Add(menuItem); } } public bool CtxmGenerateChgAutoAdd(MenuItem menu, IAutoAddTargetData info) { bool skipMenu = Settings.Instance.MenuSet.AutoAddSearchSkipSubMenu; CtxmClearItemMenu(menu, skipMenu); if (menu.IsEnabled == false) return false; CtxmGenerateChgAutoAddMenuItem(menu, info, EpgCmds.ShowAutoAddDialog, null, Settings.Instance.MenuSet.AutoAddFazySearch); if (menu.Items.Count == 0) return false; //候補が一つの時は直接メニューを実行出来るようにする if (skipMenu == true) CtxmPullUpSubMenu(menu, true); return true; } private void CtxmGenerateChgAutoAddMenuItem(MenuItem menu, IAutoAddTargetData info, ICommand cmd, bool? IsAutoAddEnabled, bool ByFazy) { if (info != null) { var addList = new List<AutoAddData>(); addList.AddRange(info.SearchEpgAutoAddList(IsAutoAddEnabled, ByFazy)); addList.AddRange(info.SearchManualAutoAddList(IsAutoAddEnabled)); var chkList = new List<AutoAddData>(); chkList.AddRange(info.GetEpgAutoAddList(true)); chkList.AddRange(info.GetManualAutoAddList(true)); addList.ForEach(autoAdd => { var menuItem = new MenuItem(); menuItem.IsChecked = chkList.Contains(autoAdd) && (info is ReserveData ? (info as ReserveData).IsAutoAdded : true); menuItem.Header = MenuUtil.ConvertAutoddTextMenu(autoAdd); LimitLenHeader(menuItem); if (Settings.Instance.MenuSet.AutoAddSearchToolTip == true) { menuItem.ToolTip = AutoAddDataItemEx.CreateIncetance(autoAdd).ToolTipViewAlways; } menuItem.Command = cmd; menuItem.CommandParameter = new EpgCmdParam(menu.CommandParameter as EpgCmdParam); (menuItem.CommandParameter as EpgCmdParam).Data = autoAdd.GetType();//オブジェクト入れると残るので (menuItem.CommandParameter as EpgCmdParam).ID = (int)(autoAdd.DataID); menuItem.Tag = menuItem.Command; menu.Items.Add(menuItem); }); } } public bool CtxmGenerateShowReserveDialogMenuItems(MenuItem menu, IEnumerable<AutoAddData> list) { menu.Items.Clear(); if (menu.IsEnabled == true && list != null) { var chkList = new HashSet<ReserveData>(list.GetAutoAddList(true).GetReserveList()); var addList = list.GetReserveList().FindAll(info => info.IsOver() == false);//FindAll()は通常無くても同じはず var hasStatus = addList.Any(data => string.IsNullOrWhiteSpace(new ReserveItem(data).Status) == false); foreach (var data in addList.OrderBy(info => info.StartTimeActual)) { var resItem = new ReserveItem(data); var menuItem = new MenuItem(); menuItem.IsChecked = chkList.Contains(data) && data.IsAutoAdded; menuItem.Header = resItem.StartTimeShort + " " + data.Title; LimitLenHeader(menuItem, 42, 28); //ステータスがあれば表示する if (hasStatus == true) { var headBlock = new StackPanel { Orientation = Orientation.Horizontal }; headBlock.Children.Add(new TextBlock { Text = resItem.Status, Foreground = resItem.StatusColor, Width = 25 }); headBlock.Children.Add(new TextBlock { Text = menuItem.Header as string });//折り返しも可能だがいまいちな感じ。 menuItem.Header = headBlock; } if (Settings.Instance.MenuSet.ReserveSearchToolTip == true) { menuItem.ToolTip = resItem.ToolTipViewAlways; } menuItem.Command = EpgCmds.ShowReserveDialog; menuItem.CommandParameter = new EpgCmdParam(menu.CommandParameter as EpgCmdParam); (menuItem.CommandParameter as EpgCmdParam).ID = (int)(data.ReserveID); menuItem.Tag = menuItem.Command; menu.Items.Add(menuItem); } } if (menu.Items.Count == 0) { menu.Items.Add(new object());//メニューに「>」を表示するためのダミー return false; } return true; } public void CtxmGenerateOpenFolderItems(MenuItem menu, RecSettingData recSetting = null) { CtxmClearItemMenu(menu); //ツールチップのクリアがあるので先 if (menu.IsEnabled == false) return; bool defOutPutted = false; recSetting = recSetting == null ? new RecSettingData() : recSetting; var addFolderList = new Action<List<RecFileSetInfo>, bool, string>((fldrs, recflg, header_exp) => { //ワンセグ出力未チェックでも、フォルダ設定があれば表示する。 //ただし、デフォルトフォルダは1回だけ展開して表示する。 if (defOutPutted == false && (recflg && fldrs.Count == 0 || fldrs.Any(info => info.RecFolder == "!Default"))) { defOutPutted = true; Settings.Instance.DefRecFolders.ForEach(folder => CtxmGenerateOpenFolderItem(menu, folder, header_exp + "(デフォルト) ")); } foreach (var info in fldrs.Where(info => info.RecFolder != "!Default")) { CtxmGenerateOpenFolderItem(menu, info.RecFolder, header_exp); } }); addFolderList(recSetting.RecFolderList, true, ""); addFolderList(recSetting.PartialRecFolder, recSetting.PartialRecFlag != 0, "(ワンセグ) "); //候補が一つの時は直接メニューを実行出来るようにする CtxmPullUpSubMenu(menu); } private void CtxmGenerateOpenFolderItem(MenuItem menu, string path, string header_exp = "") { var menuItem = new MenuItem(); menuItem.Header = header_exp + path; LimitLenHeader(menuItem); menuItem.Command = EpgCmds.OpenFolder; menuItem.CommandParameter = new EpgCmdParam(menu.CommandParameter as EpgCmdParam); (menuItem.CommandParameter as EpgCmdParam).Data = path; menuItem.Tag = menuItem.Command; menu.Items.Add(menuItem); } /// <summary>長すぎるとき省略してツールチップを追加する</summary> public bool LimitLenHeader(MenuItem menu, int max = 45, int pos = -1) { var header = menu.Header as string; if (header == null) return false; bool isLengthOver = header.Length > max; if (isLengthOver == true) { menu.ToolTip = ViewUtil.GetTooltipBlockStandard(header); header = CommonUtil.LimitLenString(header, max, pos); // 長すぎる場合は省略 } menu.Header = header; return isLengthOver; } private void CtxmClearItemMenu(MenuItem menu, bool? isEndDot = null) { menu.ToolTip = null; menu.Command = null; (menu.CommandParameter as EpgCmdParam).Data = null; (menu.CommandParameter as EpgCmdParam).ID = 0; menu.Items.Clear(); if (isEndDot != null) CtxmPullUpSubMenuSwitchEndDot(menu, (bool)isEndDot); } private void CtxmPullUpSubMenu(MenuItem menu, bool? isEndDot = null) { if (menu.Items.Count == 1) { var submenu = (menu.Items[0] as MenuItem); menu.ToolTip = submenu.ToolTip ?? submenu.Header; menu.Command = submenu.Command; (menu.CommandParameter as EpgCmdParam).Data = (submenu.CommandParameter as EpgCmdParam).Data; (menu.CommandParameter as EpgCmdParam).ID = (submenu.CommandParameter as EpgCmdParam).ID; menu.Items.Clear(); } if (isEndDot != null) CtxmPullUpSubMenuSwitchEndDot(menu, (bool)isEndDot); } private void CtxmPullUpSubMenuSwitchEndDot(MenuItem menu, bool isEndDot = true) { var header = menu.Header as string; if (header != null) { if (header.EndsWith("...") == true) { menu.Header = header.Substring(0, header.Length - 3); } if (isEndDot == true && menu.Items.Count == 0) { menu.Header += "..."; } } } } }
48.958621
165
0.591656
[ "MIT" ]
nexus7ici/tkntrec
EpgTimer/EpgTimer/Menu/MenuManager.cs
47,246
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. 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. */ namespace TencentCloud.Iecp.V20210914.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class VolumeConfigMapKeyToPath : AbstractModel { /// <summary> /// 健名 /// </summary> [JsonProperty("Key")] public string Key{ get; set; } /// <summary> /// 对应本地路径 /// </summary> [JsonProperty("Path")] public string Path{ get; set; } /// <summary> /// 对应权限模式 /// </summary> [JsonProperty("Mode")] public string Mode{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "Key", this.Key); this.SetParamSimple(map, prefix + "Path", this.Path); this.SetParamSimple(map, prefix + "Mode", this.Mode); } } }
28.844828
81
0.610281
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Iecp/V20210914/Models/VolumeConfigMapKeyToPath.cs
1,701
C#
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace DevAssessment.iOS { public class Application { // This is the main entry point of the application. static void Main(string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main(args, null, "AppDelegate"); } } }
23.095238
91
0.635052
[ "MIT" ]
abdul-wasey/DevAssessment
src/DevAssessment.iOS/Main.cs
487
C#
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculus.com/licenses/LICENSE-3.3 Unless required by applicable law or agreed to in writing, the Oculus VR SDK 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.Runtime.InteropServices; using System.Text.RegularExpressions; using UnityEngine; using VR = UnityEngine.VR; /// <summary> /// Manages an Oculus Rift head-mounted display (HMD). /// </summary> public class OVRDisplay { /// <summary> /// Specifies the size and field-of-view for one eye texture. /// </summary> public struct EyeRenderDesc { /// <summary> /// The horizontal and vertical size of the texture. /// </summary> public Vector2 resolution; /// <summary> /// The angle of the horizontal and vertical field of view in degrees. /// </summary> public Vector2 fov; } /// <summary> /// Contains latency measurements for a single frame of rendering. /// </summary> public struct LatencyData { /// <summary> /// The time it took to render both eyes in seconds. /// </summary> public float render; /// <summary> /// The time it took to perform TimeWarp in seconds. /// </summary> public float timeWarp; /// <summary> /// The time between the end of TimeWarp and scan-out in seconds. /// </summary> public float postPresent; public float renderError; public float timeWarpError; } private bool needsConfigureTexture; private EyeRenderDesc[] eyeDescs = new EyeRenderDesc[2]; /// <summary> /// Creates an instance of OVRDisplay. Called by OVRManager. /// </summary> public OVRDisplay() { UpdateTextures(); } /// <summary> /// Updates the internal state of the OVRDisplay. Called by OVRManager. /// </summary> public void Update() { UpdateTextures(); } /// <summary> /// Occurs when the head pose is reset. /// </summary> public event System.Action RecenteredPose; /// <summary> /// Recenters the head pose. /// </summary> public void RecenterPose() { VR.InputTracking.Recenter(); if (RecenteredPose != null) { RecenteredPose(); } } /// <summary> /// Gets the current linear acceleration of the head. /// </summary> public Vector3 acceleration { get { if (!OVRManager.isHmdPresent) return Vector3.zero; OVRPose ret = OVRPlugin.GetEyeAcceleration(OVRPlugin.Eye.None).ToOVRPose(); return ret.position; } } /// <summary> /// Gets the current angular acceleration of the head. /// </summary> public Quaternion angularAcceleration { get { if (!OVRManager.isHmdPresent) return Quaternion.identity; OVRPose ret = OVRPlugin.GetEyeAcceleration(OVRPlugin.Eye.None).ToOVRPose(); return ret.orientation; } } /// <summary> /// Gets the current linear velocity of the head. /// </summary> public Vector3 velocity { get { if (!OVRManager.isHmdPresent) return Vector3.zero; OVRPose ret = OVRPlugin.GetEyeVelocity(OVRPlugin.Eye.None).ToOVRPose(); return ret.position; } } /// <summary> /// Gets the current angular velocity of the head. /// </summary> public Quaternion angularVelocity { get { if (!OVRManager.isHmdPresent) return Quaternion.identity; OVRPose ret = OVRPlugin.GetEyeVelocity(OVRPlugin.Eye.None).ToOVRPose(); return ret.orientation; } } /// <summary> /// Gets the resolution and field of view for the given eye. /// </summary> public EyeRenderDesc GetEyeRenderDesc(VR.VRNode eye) { return eyeDescs[(int)eye]; } /// <summary> /// Gets the current measured latency values. /// </summary> public LatencyData latency { get { if (!OVRManager.isHmdPresent) return new LatencyData(); string latency = OVRPlugin.latency; var r = new Regex("Render: ([0-9]+[.][0-9]+)ms, TimeWarp: ([0-9]+[.][0-9]+)ms, PostPresent: ([0-9]+[.][0-9]+)ms", RegexOptions.None); var ret = new LatencyData(); Match match = r.Match(latency); if (match.Success) { ret.render = float.Parse(match.Groups[1].Value); ret.timeWarp = float.Parse(match.Groups[2].Value); ret.postPresent = float.Parse(match.Groups[3].Value); } return ret; } } /// <summary> /// Gets the recommended MSAA level for optimal quality/performance the current device. /// </summary> public int recommendedMSAALevel { get { return OVRPlugin.recommendedMSAALevel; } } private void UpdateTextures() { ConfigureEyeDesc(VR.VRNode.LeftEye); ConfigureEyeDesc(VR.VRNode.RightEye); } private void ConfigureEyeDesc(VR.VRNode eye) { if (!OVRManager.isHmdPresent) return; OVRPlugin.Sizei size = OVRPlugin.GetEyeTextureSize((OVRPlugin.Eye)eye); OVRPlugin.Frustumf frust = OVRPlugin.GetEyeFrustum((OVRPlugin.Eye)eye); eyeDescs[(int)eye] = new EyeRenderDesc() { resolution = new Vector2(size.w, size.h), fov = Mathf.Rad2Deg * new Vector2(frust.fovX, frust.fovY), }; } }
25.484848
145
0.637167
[ "MIT" ]
mrayy/TxKit
Assets/Libraries/OVR/Scripts/OVRDisplay.cs
5,887
C#
#if NETFRAMEWORK using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Dependencies; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using Microsoft.Owin.Hosting; using Owin; namespace Stl.Testing { public class OwinWebApiServerOptions { public string Urls { get; set; } = null!; public Action<IServiceProvider,IAppBuilder> ConfigureBuilder { get; set; } = null!; public Action<IServiceProvider,HttpConfiguration> SetupHttpConfiguration { get; set; } = null!; } internal class OwinWebApiServer : IServer { private readonly IServiceProvider _serviceProvider; private readonly ServerAddressesFeature _serverAddresses; private bool _hasStarted; #pragma warning disable 169 private int _stopping; #pragma warning restore 169 private readonly OwinWebApiServerOptions options; //private readonly CancellationTokenSource _stopCts = new CancellationTokenSource(); //private readonly TaskCompletionSource _stoppedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); private IDisposable _application = null!; public IFeatureCollection Features { get; } public Task StartAsync<TContext>(IHttpApplication<TContext> application, CancellationToken cancellationToken) { if (_hasStarted) throw new InvalidOperationException("The server has already started and/or has not been cleaned up yet"); _hasStarted = true; string baseAddress = options.Urls; Action<IAppBuilder> configureBuilder = (appBuilder) => options.ConfigureBuilder(_serviceProvider, appBuilder); Action<HttpConfiguration> setupConfiguration = (config) => options.SetupHttpConfiguration(_serviceProvider, config); _application = WebApp.Start(baseAddress, new WebApiStartup(_serviceProvider, setupConfiguration, configureBuilder).Configuration); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { _application?.Dispose(); _application = null!; return Task.CompletedTask; } public void Dispose() { StopAsync(new CancellationToken(canceled: true)).GetAwaiter().GetResult(); } public OwinWebApiServer(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; options = serviceProvider.GetRequiredService<IOptions<OwinWebApiServerOptions>>().Value; Features = new FeatureCollection(); _serverAddresses = new ServerAddressesFeature(); Features.Set<IServerAddressesFeature>(_serverAddresses); _serverAddresses.Addresses.Add(options.Urls); } } internal class WebApiStartup { private readonly IServiceProvider serviceProvider; private readonly Action<HttpConfiguration> _setupConfiguration; private readonly Action<IAppBuilder> _configureAppBuilder; public WebApiStartup(IServiceProvider serviceProvider, Action<HttpConfiguration> setupConfiguration, Action<IAppBuilder> configureAppBuilder) { this.serviceProvider = serviceProvider; _setupConfiguration = setupConfiguration; _configureAppBuilder = configureAppBuilder; } public void Configuration(IAppBuilder appBuilder) { // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888 // Configure Web API for self-host. var config = new HttpConfiguration(); Configure(config); if (_configureAppBuilder != null) _configureAppBuilder(appBuilder); var appBuilders = serviceProvider.GetServices<Action<IAppBuilder>>(); foreach (var service in appBuilders) { service(appBuilder); } appBuilder.UseWebApi(config); } private void Configure(HttpConfiguration config) { if (_setupConfiguration != null) _setupConfiguration(config); var configBuilders = serviceProvider.GetServices<Action<HttpConfiguration>>(); foreach (var service in configBuilders) { service(config); } config.DependencyResolver = new DefaultDependencyResolver(serviceProvider); config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}" ); } } public class DefaultDependencyResolver : IDependencyResolver { private IServiceProvider serviceProvider; public DefaultDependencyResolver(IServiceProvider serviceProvider) { this.serviceProvider = serviceProvider; } public object GetService(Type serviceType) { var service = this.serviceProvider.GetService(serviceType); return service; } public IEnumerable<object> GetServices(Type serviceType) { var services = this.serviceProvider.GetServices(serviceType); return services!; } public void Dispose() { } public IDependencyScope BeginScope() { return this; } } internal class GenericWebHostService : IHostedService { private readonly IServer server; public GenericWebHostService(IServer server) => this.server = server; public async Task StartAsync(CancellationToken cancellationToken) { await server.StartAsync(new HostingApplication(), cancellationToken); } public async Task StopAsync(CancellationToken cancellationToken) { await server.StopAsync(cancellationToken); } } } #endif
34.719101
142
0.662783
[ "MIT" ]
MessiDaGod/Stl.Fusion
src/Stl.Testing/Compatibility/OwinWebApiServer.cs
6,180
C#
using ComposerCore.Extensibility; namespace ComposerCore.CompositionalQueries { public class SimpleValueQuery : ICompositionalQuery { public SimpleValueQuery(object value) { Value = value; } #region Implementation of ICompositionalQuery public object Query(IComposer composer) { return Value; } #endregion public override string ToString() { return $"SimpleValueQuery('{Value}')"; } public object Value { get; } } }
20.214286
55
0.583039
[ "MIT" ]
clay-one/composer-core
src/ComposerCore/CompositionalQueries/SimpleValueQuery.cs
568
C#
using Mapster; using Meiam.System.Hostd.Authorization; using Meiam.System.Hostd.Extensions; using Meiam.System.Interfaces; using Meiam.System.Model; using Meiam.System.Model.Dto; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using SqlSugar; using System; using System.Linq; using System.Threading.Tasks; namespace Meiam.System.Hostd.Controllers.System { /// <summary> /// 权限定义 /// </summary> [Route("api/[controller]/[action]")] [ApiController] public class PowersController : BaseController { /// <summary> /// 会话管理接口 /// </summary> private readonly TokenManager _tokenManager; /// <summary> /// 日志管理接口 /// </summary> private readonly ILogger<PowersController> _logger; /// <summary> /// 权限定义接口 /// </summary> private readonly ISysPowerService _powerService; /// <summary> /// 角色权限接口 /// </summary> private readonly ISysRolePowerService _rolePowerService; /// <summary> /// 工作单元接口 /// </summary> private readonly IUnitOfWork _unitOfWork; public PowersController(TokenManager tokenManager, ISysPowerService powerService, ISysRolePowerService rolePowerService, ILogger<PowersController> logger, IUnitOfWork unitOfWork) { _tokenManager = tokenManager; _powerService = powerService; _rolePowerService = rolePowerService; _logger = logger; _unitOfWork = unitOfWork; } /// <summary> /// 查询权限定义列表 /// </summary> /// <returns></returns> [HttpPost] [Authorization] public IActionResult Query([FromBody] PowersQueryDto parm) { //开始拼装查询条件 var predicate = Expressionable.Create<Sys_Power>(); predicate = predicate.AndIF(!string.IsNullOrEmpty(parm.Name), m => m.Name.Contains(parm.Name) || m.Page.Contains(parm.Name)); var response = _powerService.GetPages(predicate.ToExpression(), parm); return toResponse(response); } /// <summary> /// 查询权限定义 /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpGet] [Authorization] public IActionResult Get(string id) { if (!string.IsNullOrEmpty(id)) { return toResponse(_powerService.GetId(id)); } return toResponse(_powerService.GetAll()); } /// <summary> /// 添加权限定义 /// </summary> /// <returns></returns> [HttpPost] [Authorization(Power = "PRIV_POWERS_CREATE")] public IActionResult Create([FromBody] PowersCreateDto parm) { if (_powerService.Any(m => m.Name == parm.Name)) { return toResponse(StatusCodeType.Error, $"添加 {parm.Name} 失败,该数据已存在,不能重复!"); } //从 Dto 映射到 实体 var power = parm.Adapt<Sys_Power>().ToCreate(_tokenManager.GetSessionInfo()); return toResponse(_powerService.Add(power)); } /// <summary> /// 更新权限定义 /// </summary> /// <returns></returns> [HttpPost] [Authorization(Power = "PRIV_POWERS_UPDATE")] public IActionResult Update([FromBody] PowersUpdateDto parm) { if (_powerService.Any(m => m.Name == parm.Name && m.ID != parm.ID)) { return toResponse(StatusCodeType.Error, $"更新 {parm.Name} 失败,该数据已存在,不能重复!"); } var userSession = _tokenManager.GetSessionInfo(); return toResponse(_powerService.Update(m => m.ID == parm.ID, m => new Sys_Power() { Name = parm.Name, Remark = parm.Remark, Page = parm.Page, Description = parm.Description, UpdateID = userSession.UserID, UpdateName = userSession.UserName, UpdateTime = DateTime.Now })); } /// <summary> /// 删除权限定义 /// </summary> /// <returns></returns> [HttpGet] [Authorization(Power = "PRIV_POWERS_DELETE")] public IActionResult Delete(string id) { if (string.IsNullOrEmpty(id)) { return toResponse(StatusCodeType.Error, "删除权限 Id 不能为空"); } try { _unitOfWork.BeginTran(); _rolePowerService.Delete(o => o.PowerUID == id); _powerService.Delete(id); _unitOfWork.CommitTran(); return toResponse(StatusCodeType.Success); } catch (Exception) { _unitOfWork.RollbackTran(); throw; } } } }
29.236686
186
0.541996
[ "Apache-2.0" ]
91270/Meiam.System
Meiam.System.Hostd/Controllers/System/PowersController.cs
5,187
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Detector { public partial class Detector { /// <summary> /// PageStyle control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlLink PageStyle; /// <summary> /// formMain control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm formMain; /// <summary> /// SiteMapDataSource control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.SiteMapDataSource SiteMapDataSource; /// <summary> /// Menu control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Repeater Menu; /// <summary> /// body control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ContentPlaceHolder body; /// <summary> /// stats control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::FiftyOne.Foundation.UI.Web.Stats stats; } }
34.785714
89
0.506776
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
51Degrees/.NET-Device-Detection
Detector Web Site/Detector.Master.designer.cs
2,437
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(AudioSource))] public class SoundOnCollision : MonoBehaviour { public AudioClip sound; public float volume = 1.0f; void OnCollisionEnter(Collision c) { if (!c.other.gameObject.GetComponent<Player>()) { return; } this.GetComponent<AudioSource>().PlayOneShot(this.sound, this.volume); } }
23.315789
75
0.697517
[ "MIT" ]
jehna/bumper-car-deluxe
Assets/Scripts/SoundOnCollision.cs
445
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.imm.Transform; using Aliyun.Acs.imm.Transform.V20170906; namespace Aliyun.Acs.imm.Model.V20170906 { public class UpdateImageRequest : RpcAcsRequest<UpdateImageResponse> { public UpdateImageRequest() : base("imm", "2017-09-06", "UpdateImage", "imm", "openAPI") { Method = MethodType.POST; } private string project; private string externalId; private string sourceType; private string remarksB; private string remarksA; private string imageUri; private string remarksArrayA; private string remarksArrayB; private string sourceUri; private string sourcePosition; private string remarksD; private string remarksC; private string setId; public string Project { get { return project; } set { project = value; DictionaryUtil.Add(QueryParameters, "Project", value); } } public string ExternalId { get { return externalId; } set { externalId = value; DictionaryUtil.Add(QueryParameters, "ExternalId", value); } } public string SourceType { get { return sourceType; } set { sourceType = value; DictionaryUtil.Add(QueryParameters, "SourceType", value); } } public string RemarksB { get { return remarksB; } set { remarksB = value; DictionaryUtil.Add(QueryParameters, "RemarksB", value); } } public string RemarksA { get { return remarksA; } set { remarksA = value; DictionaryUtil.Add(QueryParameters, "RemarksA", value); } } public string ImageUri { get { return imageUri; } set { imageUri = value; DictionaryUtil.Add(QueryParameters, "ImageUri", value); } } public string RemarksArrayA { get { return remarksArrayA; } set { remarksArrayA = value; DictionaryUtil.Add(QueryParameters, "RemarksArrayA", value); } } public string RemarksArrayB { get { return remarksArrayB; } set { remarksArrayB = value; DictionaryUtil.Add(QueryParameters, "RemarksArrayB", value); } } public string SourceUri { get { return sourceUri; } set { sourceUri = value; DictionaryUtil.Add(QueryParameters, "SourceUri", value); } } public string SourcePosition { get { return sourcePosition; } set { sourcePosition = value; DictionaryUtil.Add(QueryParameters, "SourcePosition", value); } } public string RemarksD { get { return remarksD; } set { remarksD = value; DictionaryUtil.Add(QueryParameters, "RemarksD", value); } } public string RemarksC { get { return remarksC; } set { remarksC = value; DictionaryUtil.Add(QueryParameters, "RemarksC", value); } } public string SetId { get { return setId; } set { setId = value; DictionaryUtil.Add(QueryParameters, "SetId", value); } } public override bool CheckShowJsonItemName() { return false; } public override UpdateImageResponse GetResponse(UnmarshallerContext unmarshallerContext) { return UpdateImageResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
18.368852
96
0.623159
[ "Apache-2.0" ]
chys0404/aliyun-openapi-net-sdk
aliyun-net-sdk-imm/Imm/Model/V20170906/UpdateImageRequest.cs
4,482
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WpfApp1_FullDotNet.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
34.612903
151
0.584343
[ "MIT" ]
jupaol/learning.containers
netBuildServer/src/FullNetFramework4.7/WpfApp1_FullDotNet/Properties/Settings.Designer.cs
1,075
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class SplashSceneController : MonoBehaviour { public Slider slider; // public Text progressText; void Start () { // LoadLevel(); slider.gameObject.SetActive(false); // progressText.gameObject.SetActive(false); } public void LoadLevel() { slider.gameObject.SetActive(true); // progressText.gameObject.SetActive(true); StartCoroutine(LoadAsyncLevel()); } IEnumerator LoadAsyncLevel() { AsyncOperation operation = SceneManager.LoadSceneAsync(1); while (!operation.isDone) { float progress = Mathf.Clamp01(operation.progress / 0.9f); int processInt = ((int)progress * 100); slider.value = progress; if (processInt < 1) processInt = 1; // progressText.text = (processInt) + " %"; // progressText.text =( progress * 100) + " 100%"; // Debug.Log(progress); yield return null; } } }
24.553191
70
0.60052
[ "Apache-2.0" ]
oviebd/Ninza-Struggle
Assets/Scripts/Ui/SplashSceneController.cs
1,156
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Clean.Architecture.Web.Migrations { public partial class initial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Categories", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), CategoryName = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Categories", x => x.Id); }); migrationBuilder.CreateTable( name: "UserRoles", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), UserRoleName = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_UserRoles", x => x.Id); }); migrationBuilder.CreateTable( name: "Users", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), UserName = table.Column<string>(type: "nvarchar(max)", nullable: true), UserEmail = table.Column<string>(type: "nvarchar(max)", nullable: true), UserPassword = table.Column<string>(type: "nvarchar(max)", nullable: true), UserRoleId = table.Column<int>(type: "int", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Users", x => x.Id); table.ForeignKey( name: "FK_Users_UserRoles_UserRoleId", column: x => x.UserRoleId, principalTable: "UserRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Posts", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Title = table.Column<string>(type: "nvarchar(max)", nullable: true), Content = table.Column<string>(type: "nvarchar(max)", nullable: true), DatePublished = table.Column<DateTime>(type: "datetime2", nullable: false), UserId = table.Column<int>(type: "int", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Posts", x => x.Id); table.ForeignKey( name: "FK_Posts_Users_UserId", column: x => x.UserId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Category_Posts", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), CategoryId = table.Column<int>(type: "int", nullable: false), PostId = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Category_Posts", x => x.Id); table.ForeignKey( name: "FK_Category_Posts_Categories_CategoryId", column: x => x.CategoryId, principalTable: "Categories", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Category_Posts_Posts_PostId", column: x => x.PostId, principalTable: "Posts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_Category_Posts_CategoryId", table: "Category_Posts", column: "CategoryId"); migrationBuilder.CreateIndex( name: "IX_Category_Posts_PostId", table: "Category_Posts", column: "PostId"); migrationBuilder.CreateIndex( name: "IX_Posts_UserId", table: "Posts", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_Users_UserRoleId", table: "Users", column: "UserRoleId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Category_Posts"); migrationBuilder.DropTable( name: "Categories"); migrationBuilder.DropTable( name: "Posts"); migrationBuilder.DropTable( name: "Users"); migrationBuilder.DropTable( name: "UserRoles"); } } }
40.157534
95
0.464097
[ "MIT" ]
hasibibrahimi/Clean.Architecture
src/Clean.Architecture.Web/Migrations/20210713082941_initial.cs
5,865
C#
using System; using System.Collections.Generic; namespace TranscendenceChat.ServerClient.Entities.Ws.Requests { public class CreateGroupChatRequest : BaseRequest { public List<long> Participants { get; set; } public string GroupName { get; set; } } public class CreateGroupChatResponse : BaseResponse { public Guid GroupId { get; set; } } }
20.947368
61
0.673367
[ "MIT" ]
tamifist/Transcendence
TranscendenceChat.ServerClient/Ws/Requests/CreateGroupChatRequest.cs
400
C#
/* * RESTAPI Service * * RESTful API * * OpenAPI spec version: 2.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; namespace IO.Swagger.Model { /// <summary> /// Sample not found /// </summary> [DataContract] public partial class SampleGetSamplesScalarByStreamNotFoundResponseBody : IEquatable<SampleGetSamplesScalarByStreamNotFoundResponseBody>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="SampleGetSamplesScalarByStreamNotFoundResponseBody" /> class. /// </summary> [JsonConstructorAttribute] protected SampleGetSamplesScalarByStreamNotFoundResponseBody() { } /// <summary> /// Initializes a new instance of the <see cref="SampleGetSamplesScalarByStreamNotFoundResponseBody" /> class. /// </summary> /// <param name="message">Message of error (required).</param> /// <param name="requestId">Request ID (required).</param> public SampleGetSamplesScalarByStreamNotFoundResponseBody(string message = default(string), string requestId = default(string)) { // to ensure "message" is required (not null) if (message == null) { throw new InvalidDataException("message is a required property for SampleGetSamplesScalarByStreamNotFoundResponseBody and cannot be null"); } else { this.Message = message; } // to ensure "requestId" is required (not null) if (requestId == null) { throw new InvalidDataException("requestId is a required property for SampleGetSamplesScalarByStreamNotFoundResponseBody and cannot be null"); } else { this.RequestId = requestId; } } /// <summary> /// Message of error /// </summary> /// <value>Message of error</value> [DataMember(Name="message", EmitDefaultValue=false)] public string Message { get; set; } /// <summary> /// Request ID /// </summary> /// <value>Request ID</value> [DataMember(Name="request_id", EmitDefaultValue=false)] public string RequestId { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class SampleGetSamplesScalarByStreamNotFoundResponseBody {\n"); sb.Append(" Message: ").Append(Message).Append("\n"); sb.Append(" RequestId: ").Append(RequestId).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as SampleGetSamplesScalarByStreamNotFoundResponseBody); } /// <summary> /// Returns true if SampleGetSamplesScalarByStreamNotFoundResponseBody instances are equal /// </summary> /// <param name="input">Instance of SampleGetSamplesScalarByStreamNotFoundResponseBody to be compared</param> /// <returns>Boolean</returns> public bool Equals(SampleGetSamplesScalarByStreamNotFoundResponseBody input) { if (input == null) return false; return ( this.Message == input.Message || (this.Message != null && this.Message.Equals(input.Message)) ) && ( this.RequestId == input.RequestId || (this.RequestId != null && this.RequestId.Equals(input.RequestId)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Message != null) hashCode = hashCode * 59 + this.Message.GetHashCode(); if (this.RequestId != null) hashCode = hashCode * 59 + this.RequestId.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
35.682927
161
0.584928
[ "MIT" ]
GeoSCADA/Driver-SELogger
IO.Swagger/Model/SampleGetSamplesScalarByStreamNotFoundResponseBody.cs
5,852
C#
namespace RayCarrot.RCP.Metro { /// <summary> /// The Rayman version for TPLS /// </summary> public enum Utility_Rayman1_TPLS_RaymanVersion { /// <summary> /// Auto detect version /// </summary> Auto, /// <summary> /// Version 1.00 /// </summary> Ray_1_00, /// <summary> /// Version 1.10 /// </summary> Ray_1_10, /// <summary> /// Version 1.12 - 0 /// </summary> Ray_1_12_0, /// <summary> /// Version 1.12 - 1 /// </summary> Ray_1_12_1, /// <summary> /// Version 1.12 - 2 /// </summary> Ray_1_12_2, /// <summary> /// Version 1.20 /// </summary> Ray_1_20, /// <summary> /// Version 1.21 /// </summary> Ray_1_21, /// <summary> /// Version 1.21 Chinese /// </summary> Ray_1_21_Chinese } }
18.981132
50
0.419483
[ "MIT" ]
RayCarrot/RayCarrot.RCP.Metro
src/RayCarrot.RCP.Metro/Utilities/Games/Rayman 1/TPLS/Utility_Rayman1_TPLS_RaymanVersion.cs
1,008
C#
namespace Legion.Repositories { using System; using System.Threading.Tasks; using Legion.Configuration; using Legion.Models.Data; using MongoDB.Driver; using MongoDB.Driver.Linq; public class UserRepository : IUserRepository { private readonly IMongoCollection<User> userCollection; public UserRepository(IMongoDatabase mongoDatabase) { this.userCollection = mongoDatabase.GetCollection<User>(Constants.UserCollection); } public async Task AddUser(User user) { var existingUser = await this.IsExistingUser(user.Username); if (existingUser) { throw new Exception("User already Exists"); } user.Username = user.Username.ToLower(); await this.userCollection.InsertOneAsync(user); } public async Task UpdateUser(User user) { var existingUser = await this.IsExistingUser(user.Username); if (!existingUser) { throw new Exception("User does not exist"); } user.Username = user.Username.ToLower(); await this.userCollection.ReplaceOneAsync( u => u.Username == user.Username, user, new UpdateOptions { IsUpsert = true, }); } public async Task<User> GetUserByUsername(string username) { var sanitisedUsername = username.ToLower(); return await this.userCollection.AsQueryable().Where(u => u.Username == sanitisedUsername).FirstOrDefaultAsync(); } public async Task<bool> IsExistingUser(string username) { var sanitisedUsername = username.ToLower(); return await this.userCollection.AsQueryable().AnyAsync(u => u.Username == sanitisedUsername); } public async Task<bool> IsRepositoryEmpty() { return await this.userCollection.AsQueryable().AnyAsync(); } } }
28.739726
125
0.583889
[ "MIT" ]
blacktau/legion-react-dotnet-mongo
Legion/Repositories/UserRepository.cs
2,098
C#
#region Copyright (C) 2017 Kevin (OSS开源实验室) 公众号:osscore /*************************************************************************** *   文件功能描述:OSSCore插件 —— 阿里云 短信请求实体 * *   创建人: Kevin * 创建人Email:1985088337@qq.com * 创建日期:2017-10-22 * *****************************************************************************/ #endregion using System.Collections.Generic; using OSS.Common.Resp; namespace OSS.Clients.SMS.Ali.Reqs { public class SendAliSmsReq { /// <summary> /// 模板编号 /// </summary> public string template_code { get; set; } /// <summary> /// 手机号码 /// </summary> public IList<string> PhoneNums { get; set; } /// <summary> /// 签名 /// </summary> public string sign_name { get; set; } /// <summary> /// 内容数据 /// </summary> public Dictionary<string, string> body_paras { get; set; } } public class SendAliSmsResp : Resp { /// <summary> /// 状态码-返回OK代表请求成功,其他错误码详见错误码列表 /// </summary> public string Code { get; set; } /// <summary> /// 状态码的描述 /// </summary> public string Message { get; set; } /// <summary> /// 发送回执ID,可根据该ID查询具体的发送状态 /// </summary> public string BizId { get; set; } /// <summary> /// 请求ID /// </summary> public string RequestId { get; set; } } }
22.363636
78
0.447832
[ "Apache-2.0" ]
KevinWG/OSS.Clients.SaaS
SMS/OSS.Clients.SMS.Ali/Reqs/SendReq.cs
1,694
C#
 // Copyright (c) Dark Crystal Games. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using UnityEditor; using UnityEngine; using DarkCrystal.CommandLine; namespace DarkCrystal.Sample { public class CommandLineWindowWithParameter : CommandLineWindow { protected override string DescriptionText => "Type command. Examples:\n" + " self.Name\n" + " self.Name = \"My Enemy\"\n" + " As well as all default resolver options\n\n"; protected override IGlobalObjectResolver Resolver => ResolversHub.CharacterResolver; private int CurrentEnemy; [MenuItem("Tools/CommandLineWindowWithParameter")] static void Init() { (EditorWindow.GetWindow(typeof(CommandLineWindowWithParameter)) as CommandLineWindowWithParameter).Show(); } protected override void OnGUIInternal() { GUILayout.BeginHorizontal(); for (int i = 0; i < World.Enemies.Length; i++) { GUIStyle guiStyle = new GUIStyle(GUI.skin.button); if (i == CurrentEnemy) { guiStyle.normal.textColor = Color.red; } if (GUILayout.Button("Enemy " + i, guiStyle)) CurrentEnemy = i; } GUILayout.EndHorizontal(); base.OnGUIInternal(); } protected override void Run() { try { var result = CommandLine.Execute(CommandLineText, World.Enemies[CurrentEnemy], ResolversHub.CharacterResolver); OutputText = result?.ToString() ?? "<null>"; } catch (TokenException exception) { OutputText = exception.ToString(); } catch (Exception exception) { OutputText = exception.ToString(); } } } }
31.84375
127
0.561825
[ "MIT" ]
KsanfFillum/DarkLine
DarkCrystal/Sample/EditorWindows/CommandLineWindowWithParameter.cs
2,040
C#
#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.Globalization; using System.IO; using System.Text; #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #elif ASPNETCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Tests.Utilities { [TestFixture] public class DateTimeUtilsTests : TestFixtureBase { [Test] public void RoundTripDateTimeMinAndMax() { RoundtripDateIso(DateTime.MinValue); RoundtripDateIso(DateTime.MaxValue); } private static void RoundtripDateIso(DateTime value) { StringWriter sw = new StringWriter(); DateTimeUtils.WriteDateTimeString(sw, value, DateFormatHandling.IsoDateFormat, null, CultureInfo.InvariantCulture); string minDateText = sw.ToString(); object dt; DateTimeUtils.TryParseDateIso(minDateText, DateParseHandling.DateTime, DateTimeZoneHandling.RoundtripKind, out dt); DateTime parsedDt = (DateTime)dt; Assert.AreEqual(value, parsedDt); } [Test] public void FailingDateTimeParse() { string text = "2000-12-15T22:11:03.055+23:30"; DateTime oldDt; bool success = DateTime.TryParseExact(text, "yyyy-MM-ddTHH:mm:ss.FFFFFFFK", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out oldDt); Console.WriteLine("Success: " + success); Console.WriteLine("DateTime: " + oldDt); Assert.IsTrue(success); } [Test] public void NewDateTimeParse() { AssertNewDateTimeParseEqual("999x-12-31T23:59:59"); AssertNewDateTimeParseEqual("9999x12-31T23:59:59"); AssertNewDateTimeParseEqual("9999-1x-31T23:59:59"); AssertNewDateTimeParseEqual("9999-12x31T23:59:59"); AssertNewDateTimeParseEqual("9999-12-3xT23:59:59"); AssertNewDateTimeParseEqual("9999-12-31x23:59:59"); AssertNewDateTimeParseEqual("9999-12-31T2x:59:59"); AssertNewDateTimeParseEqual("9999-12-31T23x59:59"); AssertNewDateTimeParseEqual("9999-12-31T23:5x:59"); AssertNewDateTimeParseEqual("9999-12-31T23:59x59"); AssertNewDateTimeParseEqual("9999-12-31T23:59:5x"); AssertNewDateTimeParseEqual("9999-12-31T23:59:5"); AssertNewDateTimeParseEqual("9999-12-31T23:59:59.x"); AssertNewDateTimeParseEqual("9999-12-31T23:59:59.99999999"); //AssertNewDateTimeParseEqual("9999-12-31T23:59:59.", null); // DateTime.TryParse is bugged and should return null AssertNewDateTimeParseEqual("2000-12-15T22:11:03.055Z"); AssertNewDateTimeParseEqual("2000-12-15T22:11:03.055"); AssertNewDateTimeParseEqual("2000-12-15T22:11:03.055+00:00"); AssertNewDateTimeParseEqual("2000-12-15T22:11:03.055+23:30"); AssertNewDateTimeParseEqual("2000-12-15T22:11:03.055-23:30"); AssertNewDateTimeParseEqual("2000-12-15T22:11:03.055+11:30"); AssertNewDateTimeParseEqual("2000-12-15T22:11:03.055-11:30"); AssertNewDateTimeParseEqual("2000-12-15T22:11:03Z"); AssertNewDateTimeParseEqual("2000-12-15T22:11:03"); AssertNewDateTimeParseEqual("2000-12-15T22:11:03+00:00"); AssertNewDateTimeParseEqual("2000-12-15T22:11:03+23:30"); AssertNewDateTimeParseEqual("2000-12-15T22:11:03-23:30"); AssertNewDateTimeParseEqual("2000-12-15T22:11:03+11:30"); AssertNewDateTimeParseEqual("2000-12-15T22:11:03-11:30"); AssertNewDateTimeParseEqual("0001-01-01T00:00:00Z"); AssertNewDateTimeParseEqual("0001-01-01T00:00:00"); // this is DateTime.MinDate //AssertNewDateTimeParseEqual("0001-01-01T00:00:00+00:00"); // when the timezone is negative then this breaks //AssertNewDateTimeParseEqual("0001-01-01T00:00:00+23:30"); // I don't know why a different value is returned from DateTime.TryParse, I think it is a bug in .NET AssertNewDateTimeParseEqual("0001-01-01T00:00:00-23:30"); //AssertNewDateTimeParseEqual("0001-01-01T00:00:00+11:30"); // when the timezone is negative then this breaks AssertNewDateTimeParseEqual("0001-01-01T00:00:00-12:00"); AssertNewDateTimeParseEqual("9999-12-31T23:59:59.9999999Z"); AssertNewDateTimeParseEqual("9999-12-31T23:59:59.9999999"); // this is DateTime.MaxDate AssertNewDateTimeParseEqual("9999-12-31T23:59:59.9999999+00:00", DateTime.MaxValue); // DateTime.TryParse fails instead of returning MaxDate in some timezones AssertNewDateTimeParseEqual("9999-12-31T23:59:59.9999999+23:30"); AssertNewDateTimeParseEqual("9999-12-31T23:59:59.9999999-23:30", DateTime.MaxValue); // DateTime.TryParse fails instead of returning MaxDate in some timezones AssertNewDateTimeParseEqual("9999-12-31T23:59:59.9999999+11:30", DateTime.MaxValue); // DateTime.TryParse fails instead of returning MaxDate in some timezones AssertNewDateTimeParseEqual("9999-12-31T23:59:59.9999999-11:30", DateTime.MaxValue); // DateTime.TryParse fails instead of returning MaxDate in some timezones } private void AssertNewDateTimeParseEqual(string text, object oldDate) { object oldDt; if (TryParseDateIso(text, DateParseHandling.DateTime, DateTimeZoneHandling.RoundtripKind, out oldDt)) { oldDate = oldDt; } object newDt; DateTimeUtils.TryParseDateIso(text, DateParseHandling.DateTime, DateTimeZoneHandling.RoundtripKind, out newDt); if (!Equals(oldDate, newDt)) { Assert.AreEqual(oldDate, newDt, "DateTime parse not equal. Text: '{0}' Old ticks: {1} New ticks: {2}".FormatWith( CultureInfo.InvariantCulture, text, oldDate != null ? ((DateTime)oldDate).Ticks : (long?)null, newDt != null ? ((DateTime)newDt).Ticks : (long?)null )); } } private void AssertNewDateTimeParseEqual(string text) { Console.WriteLine("Parsing date text: " + text); object oldDt; TryParseDateIso(text, DateParseHandling.DateTime, DateTimeZoneHandling.RoundtripKind, out oldDt); AssertNewDateTimeParseEqual(text, oldDt); } #if !NET20 [Test] public void NewDateTimeOffsetParse() { AssertNewDateTimeOffsetParseEqual("0001-01-01T00:00:00"); AssertNewDateTimeOffsetParseEqual("2000-12-15T22:11:03.055Z"); AssertNewDateTimeOffsetParseEqual("2000-12-15T22:11:03.055"); AssertNewDateTimeOffsetParseEqual("2000-12-15T22:11:03.055+00:00"); AssertNewDateTimeOffsetParseEqual("2000-12-15T22:11:03.055+13:30"); AssertNewDateTimeOffsetParseEqual("2000-12-15T22:11:03.055-13:30"); AssertNewDateTimeOffsetParseEqual("2000-12-15T22:11:03Z"); AssertNewDateTimeOffsetParseEqual("2000-12-15T22:11:03"); AssertNewDateTimeOffsetParseEqual("2000-12-15T22:11:03+00:00"); AssertNewDateTimeOffsetParseEqual("2000-12-15T22:11:03+13:30"); AssertNewDateTimeOffsetParseEqual("2000-12-15T22:11:03-13:30"); AssertNewDateTimeOffsetParseEqual("0001-01-01T00:00:00Z"); AssertNewDateTimeOffsetParseEqual("0001-01-01T00:00:00+00:00"); AssertNewDateTimeOffsetParseEqual("0001-01-01T00:00:00+13:30"); AssertNewDateTimeOffsetParseEqual("0001-01-01T00:00:00-13:30"); AssertNewDateTimeOffsetParseEqual("9999-12-31T23:59:59.9999999Z"); AssertNewDateTimeOffsetParseEqual("9999-12-31T23:59:59.9999999"); AssertNewDateTimeOffsetParseEqual("9999-12-31T23:59:59.9999999+00:00"); AssertNewDateTimeOffsetParseEqual("9999-12-31T23:59:59.9999999+13:30"); AssertNewDateTimeOffsetParseEqual("9999-12-31T23:59:59.9999999-13:30"); } private void AssertNewDateTimeOffsetParseEqual(string text) { object oldDt; object newDt; TryParseDateIso(text, DateParseHandling.DateTimeOffset, DateTimeZoneHandling.Unspecified, out oldDt); DateTimeUtils.TryParseDateIso(text, DateParseHandling.DateTimeOffset, DateTimeZoneHandling.Unspecified, out newDt); if (!Equals(oldDt, newDt)) { Assert.AreEqual(oldDt, newDt, "DateTimeOffset parse not equal. Text: '{0}' Old ticks: {1} New ticks: {2}".FormatWith( CultureInfo.InvariantCulture, text, ((DateTime)oldDt).Ticks, ((DateTime)newDt).Ticks)); } } #endif internal static bool TryParseDateIso(string text, DateParseHandling dateParseHandling, DateTimeZoneHandling dateTimeZoneHandling, out object dt) { const string isoDateFormat = "yyyy-MM-ddTHH:mm:ss.FFFFFFFK"; #if !NET20 if (dateParseHandling == DateParseHandling.DateTimeOffset) { DateTimeOffset dateTimeOffset; if (DateTimeOffset.TryParseExact(text, isoDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out dateTimeOffset)) { dt = dateTimeOffset; return true; } } else #endif { DateTime dateTime; if (DateTime.TryParseExact(text, isoDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out dateTime)) { dateTime = DateTimeUtils.EnsureDateTime(dateTime, dateTimeZoneHandling); dt = dateTime; return true; } } dt = null; return false; } } }
47.012195
173
0.658885
[ "MIT" ]
Daniel-Oberlin/RepoTools---.NET
Newtonsoft.Json-6.0.8/Src/Newtonsoft.Json.Tests/Utilities/DateTimeUtilsTests.cs
11,567
C#
using System; using System.Xml.Serialization; namespace OpenTrack.ManualSoap.Requests { [Serializable] public class PartAddPart { [XmlElement] public string PartNumber { get; set; } [XmlElement] public string Manufacturer { get; set; } [XmlElement] public string PartDescription { get; set; } [XmlElement] public string StockingGroup { get; set; } [XmlElement] public string Status { get; set; } [XmlElement] public string BinLocation { get; set; } [XmlElement] public string ShelfLocation { get; set; } [XmlElement] public decimal Cost { get; set; } [XmlElement] public decimal ListPrice { get; set; } [XmlElement] public decimal TradePrice { get; set; } [XmlElement(ElementName = "CPS")] public string Cps { get; set; } } }
22.095238
51
0.580819
[ "MIT" ]
BFrench81/OpenTrack.NET
OpenTrack.Lib/ManualSoap/Requests/PartAddPart.cs
928
C#
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using BenchmarkDotNet.Attributes; using Elastic.Apm.Logging; using Elastic.Apm.Tests.Utilities; namespace Elastic.Apm.Benchmarks { /// <summary> /// Benchmarks related to tracer (like starting a transaction, span, etc.) /// </summary> [MemoryDiagnoser] public class TracerBenchmarks { private ApmAgent _agent; [GlobalSetup(Target = nameof(SimpleTransactionsWith1SpanWithStackTrace))] public void SetupWithStackTraceForAllSpans() => _agent = new ApmAgent(new AgentComponents(payloadSender: new MockPayloadSender(), configurationReader: new MockConfigSnapshot(spanFramesMinDurationInMilliseconds: "-1ms"))); [GlobalSetup(Target = nameof(SimpleTransactionsWith1SpanWithoutStackTrace))] public void SetupWithTurnedOffStackTrace() => _agent = new ApmAgent(new AgentComponents(payloadSender: new MockPayloadSender(), configurationReader: new MockConfigSnapshot(spanFramesMinDurationInMilliseconds: "0ms"))); [GlobalSetup(Target = nameof(Simple100Transaction10Spans))] public void DefaultAgentSetup() { var noopLogger = new NoopLogger(); _agent = new ApmAgent(new AgentComponents(payloadSender: new MockPayloadSender(), logger: noopLogger, configurationReader: new MockConfigSnapshot(noopLogger))); } [GlobalSetup(Target = nameof(DebugLogSimpleTransaction10Spans))] public void DebugAgentSetup() { var testLogger = new PerfTestLogger(LogLevel.Debug); _agent = new ApmAgent(new AgentComponents(payloadSender: new MockPayloadSender(), logger: testLogger, configurationReader: new MockConfigSnapshot(testLogger, "Debug"))); } [Benchmark] public void SimpleTransactionsWith1SpanWithStackTrace() => _agent.Tracer.CaptureTransaction("transaction", "perfTransaction", transaction => { transaction.CaptureSpan("span", "perfSpan", () => { }); }); [Benchmark] public void SimpleTransactionsWith1SpanWithoutStackTrace() => _agent.Tracer.CaptureTransaction("transaction", "perfTransaction", transaction => { transaction.CaptureSpan("span", "perfSpan", () => { }); }); [GlobalCleanup] public void GlobalCleanup() => _agent.Dispose(); [Benchmark] public void Simple100Transaction10Spans() => _agent.Tracer.CaptureTransaction("transaction", "perfTransaction", transaction => { for (var j = 0; j < 10; j++) transaction.CaptureSpan("span", "perfSpan", () => { }); }); [Benchmark] public void DebugLogSimpleTransaction10Spans() => _agent.Tracer.CaptureTransaction("transaction", "perfTransaction", transaction => { for (var j = 0; j < 10; j++) transaction.CaptureSpan("span", "perfSpan", () => { }); }); } }
38.712329
104
0.742746
[ "Apache-2.0" ]
AAimson/apm-agent-dotnet
test/Elastic.Apm.Benchmarks/TracerBenchmarks.cs
2,826
C#
using System; using System.Threading; using UnityEngine; namespace ETModel { [ObjectSystem] public class MoveComponentUpdateSystem : UpdateSystem<MoveComponent> { public override void Update(MoveComponent self) { self.Update(); } } public class MoveComponent : Component { public Vector3 Target; // 开启移动协程的Unit的位置 public Vector3 StartPos; // 开启移动协程的时间 public long StartTime; public long needTime; public ETTaskCompletionSource moveTcs; public void Update() { MoveToAsync(); } #region MoveToAsync void MoveToAsync() { if (this.moveTcs == null) { this.GetParent<Unit>().GetComponent<AnimatorComponent>().AnimSet(MotionType.None); return; } Unit unit = this.GetParent<Unit>(); long timeNow = TimeHelper.Now(); if (timeNow - this.StartTime >= this.needTime) { unit.Position = this.Target; ETTaskCompletionSource tcs = this.moveTcs; this.moveTcs = null; tcs.SetResult(); return; } this.GetParent<Unit>().GetComponent<AnimatorComponent>().AnimSet(MotionType.Move); float amount = (timeNow - this.StartTime) * 1f / this.needTime; unit.Position = Vector3.Lerp(this.StartPos, this.Target, amount); } public ETTask MoveToAsync(Vector3 target, float speedValue, CancellationToken cancellationToken) { Unit unit = this.GetParent<Unit>(); if ((target - this.Target).magnitude < 0.1f) { return ETTask.CompletedTask; } this.Target = target; this.StartPos = unit.Position; this.StartTime = TimeHelper.Now(); float distance = (this.Target - this.StartPos).magnitude; if (Math.Abs(distance) < 0.1f) { return ETTask.CompletedTask; } this.needTime = (long)(distance / speedValue * 1000); this.moveTcs = new ETTaskCompletionSource(); cancellationToken.Register(() => { this.moveTcs = null; }); return this.moveTcs.Task; } #endregion } }
23.858696
104
0.594533
[ "MIT" ]
xfs81150082/TumoET
Unity/Assets/Model/Module/Demo/MoveComponent.cs
2,235
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("FormCore")] [assembly: AssemblyDescription("https://github.com/pmq20/FormCore")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FormCore")] [assembly: AssemblyCopyright("Copyright (c) 2018 Minqi Pan, Xiang Yan, Chenhui Yu")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1e09f3fc-831e-4871-9b7e-a43ef42c70c7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.35.0.0")] [assembly: AssemblyFileVersion("0.35.0.0")]
40.25
85
0.727398
[ "MIT" ]
pmq20/FormCore
Backend/Properties/AssemblyInfo.cs
1,451
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; using Csla; using Csla.Serialization; namespace Csla.Test.BasicModern { [Serializable] public class Child : BusinessBase<Child> { public static readonly PropertyInfo<int> IdProperty = RegisterProperty<int>(nameof(Id)); public int Id { get { return GetProperty(IdProperty); } set { SetProperty(IdProperty, value); } } public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(nameof(Name)); [Required] public string Name { get { return GetProperty(NameProperty); } set { SetProperty(NameProperty, value); } } private void Child_Create(int id, string name) { using (BypassPropertyChecks) { Id = id; Name = name; } } private void Child_Fetch(int id, string name) { using (BypassPropertyChecks) { Id = id; Name = name; } } private void Child_Insert() { } private void Child_Update() { } private void Child_DeleteSelf() { } } }
20.724138
102
0.642263
[ "MIT" ]
Alstig/csla
Source/Csla.test/BasicModern/Child.cs
1,204
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace TemplateV2.Models.ServiceModels { public class RegisterRequest : IValidatableObject { [Required] [DataType(DataType.EmailAddress)] [Display(Name = "Email address")] public string EmailAddress { get; set; } [Required] [DataType(DataType.Password)] public string Password { get; set; } [Required] [DataType(DataType.Password)] [Display(Name = "Confirm password")] public string PasswordConfirm { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (Password != PasswordConfirm) { yield return new ValidationResult("Passwords do not match"); } } } }
27.870968
90
0.622685
[ "MIT" ]
chriskid824/MVC
TemplateV2.Models/ServiceModels/Account/RegisterRequest.cs
864
C#
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using NUnit.Framework; using StandardAnalyzer = Lucene.Net.Analysis.Standard.StandardAnalyzer; using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using IndexWriter = Lucene.Net.Index.IndexWriter; using IndexReader = Lucene.Net.Index.IndexReader; using Term = Lucene.Net.Index.Term; using RAMDirectory = Lucene.Net.Store.RAMDirectory; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using Directory = Lucene.Net.Store.Directory; using MockRAMDirectory = Lucene.Net.Store.MockRAMDirectory; using QueryParser = Lucene.Net.QueryParsers.QueryParser; namespace Lucene.Net.Search { /// <summary> Tests {@link FuzzyQuery}. /// /// </summary> [TestFixture] public class TestFuzzyQuery:LuceneTestCase { [Test] public virtual void TestFuzziness() { RAMDirectory directory = new RAMDirectory(); IndexWriter writer = new IndexWriter(directory, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); AddDoc("aaaaa", writer); AddDoc("aaaab", writer); AddDoc("aaabb", writer); AddDoc("aabbb", writer); AddDoc("abbbb", writer); AddDoc("bbbbb", writer); AddDoc("ddddd", writer); writer.Optimize(); writer.Close(); IndexSearcher searcher = new IndexSearcher(directory, true); FuzzyQuery query = new FuzzyQuery(new Term("field", "aaaaa"), FuzzyQuery.defaultMinSimilarity, 0); ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(3, hits.Length); // same with prefix query = new FuzzyQuery(new Term("field", "aaaaa"), FuzzyQuery.defaultMinSimilarity, 1); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(3, hits.Length); query = new FuzzyQuery(new Term("field", "aaaaa"), FuzzyQuery.defaultMinSimilarity, 2); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(3, hits.Length); query = new FuzzyQuery(new Term("field", "aaaaa"), FuzzyQuery.defaultMinSimilarity, 3); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(3, hits.Length); query = new FuzzyQuery(new Term("field", "aaaaa"), FuzzyQuery.defaultMinSimilarity, 4); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(2, hits.Length); query = new FuzzyQuery(new Term("field", "aaaaa"), FuzzyQuery.defaultMinSimilarity, 5); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); query = new FuzzyQuery(new Term("field", "aaaaa"), FuzzyQuery.defaultMinSimilarity, 6); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); // test scoring query = new FuzzyQuery(new Term("field", "bbbbb"), FuzzyQuery.defaultMinSimilarity, 0); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(3, hits.Length, "3 documents should match"); List<String> order = new List<string>(new[] {"bbbbb", "abbbb", "aabbb"}); for (int i = 0; i < hits.Length; i++) { String term = searcher.Doc(hits[i].Doc).Get("field"); //System.out.println(hits[i].score); Assert.AreEqual(order[i], term); } // test BooleanQuery.maxClauseCount int savedClauseCount = BooleanQuery.MaxClauseCount; try { BooleanQuery.MaxClauseCount = 2; // This query would normally return 3 documents, because 3 terms match (see above): query = new FuzzyQuery(new Term("field", "bbbbb"), FuzzyQuery.defaultMinSimilarity, 0); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(2, hits.Length, "only 2 documents should match"); order = new List<string>(new[] {"bbbbb", "abbbb"}); for (int i = 0; i < hits.Length; i++) { String term = searcher.Doc(hits[i].Doc).Get("field"); //System.out.println(hits[i].score); Assert.AreEqual(order[i], term); } } finally { BooleanQuery.MaxClauseCount = savedClauseCount; } // not similar enough: query = new FuzzyQuery(new Term("field", "xxxxx"), FuzzyQuery.defaultMinSimilarity, 0); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); query = new FuzzyQuery(new Term("field", "aaccc"), FuzzyQuery.defaultMinSimilarity, 0); // edit distance to "aaaaa" = 3 hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); // query identical to a word in the index: query = new FuzzyQuery(new Term("field", "aaaaa"), FuzzyQuery.defaultMinSimilarity, 0); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(3, hits.Length); Assert.AreEqual(searcher.Doc(hits[0].Doc).Get("field"), ("aaaaa")); // default allows for up to two edits: Assert.AreEqual(searcher.Doc(hits[1].Doc).Get("field"), ("aaaab")); Assert.AreEqual(searcher.Doc(hits[2].Doc).Get("field"), ("aaabb")); // query similar to a word in the index: query = new FuzzyQuery(new Term("field", "aaaac"), FuzzyQuery.defaultMinSimilarity, 0); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(3, hits.Length); Assert.AreEqual(searcher.Doc(hits[0].Doc).Get("field"), ("aaaaa")); Assert.AreEqual(searcher.Doc(hits[1].Doc).Get("field"), ("aaaab")); Assert.AreEqual(searcher.Doc(hits[2].Doc).Get("field"), ("aaabb")); // now with prefix query = new FuzzyQuery(new Term("field", "aaaac"), FuzzyQuery.defaultMinSimilarity, 1); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(3, hits.Length); Assert.AreEqual(searcher.Doc(hits[0].Doc).Get("field"), ("aaaaa")); Assert.AreEqual(searcher.Doc(hits[1].Doc).Get("field"), ("aaaab")); Assert.AreEqual(searcher.Doc(hits[2].Doc).Get("field"), ("aaabb")); query = new FuzzyQuery(new Term("field", "aaaac"), FuzzyQuery.defaultMinSimilarity, 2); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(3, hits.Length); Assert.AreEqual(searcher.Doc(hits[0].Doc).Get("field"), ("aaaaa")); Assert.AreEqual(searcher.Doc(hits[1].Doc).Get("field"), ("aaaab")); Assert.AreEqual(searcher.Doc(hits[2].Doc).Get("field"), ("aaabb")); query = new FuzzyQuery(new Term("field", "aaaac"), FuzzyQuery.defaultMinSimilarity, 3); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(3, hits.Length); Assert.AreEqual(searcher.Doc(hits[0].Doc).Get("field"), ("aaaaa")); Assert.AreEqual(searcher.Doc(hits[1].Doc).Get("field"), ("aaaab")); Assert.AreEqual(searcher.Doc(hits[2].Doc).Get("field"), ("aaabb")); query = new FuzzyQuery(new Term("field", "aaaac"), FuzzyQuery.defaultMinSimilarity, 4); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(2, hits.Length); Assert.AreEqual(searcher.Doc(hits[0].Doc).Get("field"), ("aaaaa")); Assert.AreEqual(searcher.Doc(hits[1].Doc).Get("field"), ("aaaab")); query = new FuzzyQuery(new Term("field", "aaaac"), FuzzyQuery.defaultMinSimilarity, 5); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); query = new FuzzyQuery(new Term("field", "ddddX"), FuzzyQuery.defaultMinSimilarity, 0); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); Assert.AreEqual(searcher.Doc(hits[0].Doc).Get("field"), ("ddddd")); // now with prefix query = new FuzzyQuery(new Term("field", "ddddX"), FuzzyQuery.defaultMinSimilarity, 1); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); Assert.AreEqual(searcher.Doc(hits[0].Doc).Get("field"), ("ddddd")); query = new FuzzyQuery(new Term("field", "ddddX"), FuzzyQuery.defaultMinSimilarity, 2); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); Assert.AreEqual(searcher.Doc(hits[0].Doc).Get("field"), ("ddddd")); query = new FuzzyQuery(new Term("field", "ddddX"), FuzzyQuery.defaultMinSimilarity, 3); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); Assert.AreEqual(searcher.Doc(hits[0].Doc).Get("field"), ("ddddd")); query = new FuzzyQuery(new Term("field", "ddddX"), FuzzyQuery.defaultMinSimilarity, 4); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); Assert.AreEqual(searcher.Doc(hits[0].Doc).Get("field"), ("ddddd")); query = new FuzzyQuery(new Term("field", "ddddX"), FuzzyQuery.defaultMinSimilarity, 5); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); // different field = no match: query = new FuzzyQuery(new Term("anotherfield", "ddddX"), FuzzyQuery.defaultMinSimilarity, 0); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); searcher.Close(); directory.Close(); } [Test] public virtual void TestFuzzinessLong() { RAMDirectory directory = new RAMDirectory(); IndexWriter writer = new IndexWriter(directory, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); AddDoc("aaaaaaa", writer); AddDoc("segment", writer); writer.Optimize(); writer.Close(); IndexSearcher searcher = new IndexSearcher(directory, true); FuzzyQuery query; // not similar enough: query = new FuzzyQuery(new Term("field", "xxxxx"), FuzzyQuery.defaultMinSimilarity, 0); ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); // edit distance to "aaaaaaa" = 3, this matches because the string is longer than // in testDefaultFuzziness so a bigger difference is allowed: query = new FuzzyQuery(new Term("field", "aaaaccc"), FuzzyQuery.defaultMinSimilarity, 0); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); Assert.AreEqual(searcher.Doc(hits[0].Doc).Get("field"), ("aaaaaaa")); // now with prefix query = new FuzzyQuery(new Term("field", "aaaaccc"), FuzzyQuery.defaultMinSimilarity, 1); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); Assert.AreEqual(searcher.Doc(hits[0].Doc).Get("field"), ("aaaaaaa")); query = new FuzzyQuery(new Term("field", "aaaaccc"), FuzzyQuery.defaultMinSimilarity, 4); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); Assert.AreEqual(searcher.Doc(hits[0].Doc).Get("field"), ("aaaaaaa")); query = new FuzzyQuery(new Term("field", "aaaaccc"), FuzzyQuery.defaultMinSimilarity, 5); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); // no match, more than half of the characters is wrong: query = new FuzzyQuery(new Term("field", "aaacccc"), FuzzyQuery.defaultMinSimilarity, 0); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); // now with prefix query = new FuzzyQuery(new Term("field", "aaacccc"), FuzzyQuery.defaultMinSimilarity, 2); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); // "student" and "stellent" are indeed similar to "segment" by default: query = new FuzzyQuery(new Term("field", "student"), FuzzyQuery.defaultMinSimilarity, 0); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); query = new FuzzyQuery(new Term("field", "stellent"), FuzzyQuery.defaultMinSimilarity, 0); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); // now with prefix query = new FuzzyQuery(new Term("field", "student"), FuzzyQuery.defaultMinSimilarity, 1); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); query = new FuzzyQuery(new Term("field", "stellent"), FuzzyQuery.defaultMinSimilarity, 1); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); query = new FuzzyQuery(new Term("field", "student"), FuzzyQuery.defaultMinSimilarity, 2); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); query = new FuzzyQuery(new Term("field", "stellent"), FuzzyQuery.defaultMinSimilarity, 2); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); // "student" doesn't match anymore thanks to increased minimum similarity: query = new FuzzyQuery(new Term("field", "student"), 0.6f, 0); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); Assert.Throws<ArgumentException>(() => new FuzzyQuery(new Term("field", "student"), 1.1f), "Expected ArgumentException"); Assert.Throws<ArgumentException>(() => new FuzzyQuery(new Term("field", "student"), -0.1f), "Expected ArgumentException"); searcher.Close(); directory.Close(); } [Test] public virtual void TestTokenLengthOpt() { RAMDirectory directory = new RAMDirectory(); IndexWriter writer = new IndexWriter(directory, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); AddDoc("12345678911", writer); AddDoc("segment", writer); writer.Optimize(); writer.Close(); IndexSearcher searcher = new IndexSearcher(directory, true); Query query; // term not over 10 chars, so optimization shortcuts query = new FuzzyQuery(new Term("field", "1234569"), 0.9f); ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); // 10 chars, so no optimization query = new FuzzyQuery(new Term("field", "1234567891"), 0.9f); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); // over 10 chars, so no optimization query = new FuzzyQuery(new Term("field", "12345678911"), 0.9f); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); // over 10 chars, no match query = new FuzzyQuery(new Term("field", "sdfsdfsdfsdf"), 0.9f); hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); } [Test] public virtual void TestGiga() { StandardAnalyzer analyzer = new StandardAnalyzer(Util.Version.LUCENE_CURRENT); Directory index = new MockRAMDirectory(); IndexWriter w = new IndexWriter(index, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED); AddDoc("Lucene in Action", w); AddDoc("Lucene for Dummies", w); // addDoc("Giga", w); AddDoc("Giga byte", w); AddDoc("ManagingGigabytesManagingGigabyte", w); AddDoc("ManagingGigabytesManagingGigabytes", w); AddDoc("The Art of Computer Science", w); AddDoc("J. K. Rowling", w); AddDoc("JK Rowling", w); AddDoc("Joanne K Roling", w); AddDoc("Bruce Willis", w); AddDoc("Willis bruce", w); AddDoc("Brute willis", w); AddDoc("B. willis", w); IndexReader r = w.GetReader(); w.Close(); Query q = new QueryParser(Util.Version.LUCENE_CURRENT, "field", analyzer).Parse("giga~0.9"); // 3. search IndexSearcher searcher = new IndexSearcher(r); ScoreDoc[] hits = searcher.Search(q, 10).ScoreDocs; Assert.AreEqual(1, hits.Length); Assert.AreEqual(searcher.Doc(hits[0].Doc).Get("field"), "Giga byte"); r.Close(); } private void AddDoc(System.String text, IndexWriter writer) { Document doc = new Document(); doc.Add(new Field("field", text, Field.Store.YES, Field.Index.ANALYZED)); writer.AddDocument(doc); } } }
48.830645
120
0.623287
[ "Apache-2.0" ]
Anomalous-Software/Lucene.NET
test/core/Search/TestFuzzyQuery.cs
18,165
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Generic; using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace System.Diagnostics { /// <summary> /// Activity represents operation with context to be used for logging. /// Activity has operation name, Id, start time and duration, tags and baggage. /// /// Current activity can be accessed with static AsyncLocal variable Activity.Current. /// /// Activities should be created with constructor, configured as necessary /// and then started with Activity.Start method which maintains parent-child /// relationships for the activities and sets Activity.Current. /// /// When activity is finished, it should be stopped with static Activity.Stop method. /// /// No methods on Activity allow exceptions to escape as a response to bad inputs. /// They are thrown and caught (that allows Debuggers and Monitors to see the error) /// but the exception is suppressed, and the operation does something reasonable (typically /// doing nothing). /// </summary> public partial class Activity : IDisposable { #pragma warning disable CA1825 // Array.Empty<T>() doesn't exist in all configurations private static readonly IEnumerable<KeyValuePair<string, string?>> s_emptyBaggageTags = new KeyValuePair<string, string?>[0]; private static readonly IEnumerable<KeyValuePair<string, object?>> s_emptyTagObjects = new KeyValuePair<string, object?>[0]; private static readonly IEnumerable<ActivityLink> s_emptyLinks = new ActivityLink[0]; private static readonly IEnumerable<ActivityEvent> s_emptyEvents = new ActivityEvent[0]; #pragma warning restore CA1825 private static readonly ActivitySource s_defaultSource = new ActivitySource(string.Empty); private const byte ActivityTraceFlagsIsSet = 0b_1_0000000; // Internal flag to indicate if flags have been set private const int RequestIdMaxLength = 1024; // Used to generate an ID it represents the machine and process we are in. private static readonly string s_uniqSuffix = "-" + GetRandomNumber().ToString("x") + "."; // A unique number inside the appdomain, randomized between appdomains. // Int gives enough randomization and keeps hex-encoded s_currentRootId 8 chars long for most applications private static long s_currentRootId = (uint)GetRandomNumber(); private static ActivityIdFormat s_defaultIdFormat; /// <summary> /// Normally if the ParentID is defined, the format of that is used to determine the /// format used by the Activity. However if ForceDefaultFormat is set to true, the /// ID format will always be the DefaultIdFormat even if the ParentID is define and is /// a different format. /// </summary> public static bool ForceDefaultIdFormat { get; set; } private string? _traceState; private State _state; private int _currentChildId; // A unique number for all children of this activity. // State associated with ID. private string? _id; private string? _rootId; // State associated with ParentId. private string? _parentId; // W3C formats private string? _parentSpanId; private string? _traceId; private string? _spanId; private byte _w3CIdFlags; private byte _parentTraceFlags; private TagsLinkedList? _tags; private BaggageLinkedList? _baggage; private DiagLinkedList<ActivityLink>? _links; private DiagLinkedList<ActivityEvent>? _events; private Dictionary<string, object>? _customProperties; private string? _displayName; private ActivityStatusCode _statusCode; private string? _statusDescription; private Activity? _previousActiveActivity; /// <summary> /// Gets status code of the current activity object. /// </summary> public ActivityStatusCode Status => _statusCode; /// <summary> /// Gets the status description of the current activity object. /// </summary> public string? StatusDescription => _statusDescription; /// <summary> /// Sets the status code and description on the current activity object. /// </summary> /// <param name="code">The status code</param> /// <param name="description">The error status description</param> /// <returns><see langword="this" /> for convenient chaining.</returns> /// <remarks> /// When passing code value different than ActivityStatusCode.Error, the Activity.StatusDescription will reset to null value. /// The description paramater will be respected only when passing ActivityStatusCode.Error value. /// </remarks> public Activity SetStatus(ActivityStatusCode code, string? description = null) { _statusCode = code; _statusDescription = code == ActivityStatusCode.Error ? description : null; return this; } /// <summary> /// Gets the relationship between the Activity, its parents, and its children in a Trace. /// </summary> public ActivityKind Kind { get; private set; } = ActivityKind.Internal; /// <summary> /// An operation name is a COARSEST name that is useful grouping/filtering. /// The name is typically a compile-time constant. Names of Rest APIs are /// reasonable, but arguments (e.g. specific accounts etc), should not be in /// the name but rather in the tags. /// </summary> public string OperationName { get; } /// <summary>Gets or sets the display name of the Activity</summary> /// <remarks> /// DisplayName is intended to be used in a user interface and need not be the same as OperationName. /// </remarks> public string DisplayName { get => _displayName ?? OperationName; set => _displayName = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary>Get the ActivitySource object associated with this Activity.</summary> /// <remarks> /// All Activities created from public constructors will have a singleton source where the source name is an empty string. /// Otherwise, the source will hold the object that created the Activity through ActivitySource.StartActivity. /// </remarks> public ActivitySource Source { get; private set; } /// <summary> /// If the Activity that created this activity is from the same process you can get /// that Activity with Parent. However, this can be null if the Activity has no /// parent (a root activity) or if the Parent is from outside the process. /// </summary> /// <seealso cref="ParentId"/> public Activity? Parent { get; private set; } /// <summary> /// If the Activity has ended (<see cref="Stop"/> or <see cref="SetEndTime"/> was called) then this is the delta /// between <see cref="StartTimeUtc"/> and end. If Activity is not ended and <see cref="SetEndTime"/> was not called then this is /// <see cref="TimeSpan.Zero"/>. /// </summary> public TimeSpan Duration { get; private set; } /// <summary> /// The time that operation started. It will typically be initialized when <see cref="Start"/> /// is called, but you can set at any time via <see cref="SetStartTime(DateTime)"/>. /// </summary> public DateTime StartTimeUtc { get; private set; } /// <summary> /// This is an ID that is specific to a particular request. Filtering /// to a particular ID insures that you get only one request that matches. /// Id has a hierarchical structure: '|root-id.id1_id2.id3_' Id is generated when /// <see cref="Start"/> is called by appending suffix to Parent.Id /// or ParentId; Activity has no Id until it started /// <para/> /// See <see href="https://github.com/dotnet/corefx/blob/master/src/System.Diagnostics.DiagnosticSource/src/ActivityUserGuide.md#id-format"/> for more details /// </summary> /// <example> /// Id looks like '|a000b421-5d183ab6.1.8e2d4c28_1.':<para /> /// - '|a000b421-5d183ab6.' - Id of the first, top-most, Activity created<para /> /// - '|a000b421-5d183ab6.1.' - Id of a child activity. It was started in the same process as the first activity and ends with '.'<para /> /// - '|a000b421-5d183ab6.1.8e2d4c28_' - Id of the grand child activity. It was started in another process and ends with '_'<para /> /// 'a000b421-5d183ab6' is a <see cref="RootId"/> for the first Activity and all its children /// </example> public string? Id { #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif get { // if we represented it as a traceId-spanId, convert it to a string. // We can do this concatenation with a stackalloced Span<char> if we actually used Id a lot. if (_id == null && _spanId != null) { // Convert flags to binary. Span<char> flagsChars = stackalloc char[2]; HexConverter.ToCharsBuffer((byte)((~ActivityTraceFlagsIsSet) & _w3CIdFlags), flagsChars, 0, HexConverter.Casing.Lower); string id = "00-" + _traceId + "-" + _spanId + "-" + flagsChars.ToString(); Interlocked.CompareExchange(ref _id, id, null); } return _id; } } /// <summary> /// If the parent for this activity comes from outside the process, the activity /// does not have a Parent Activity but MAY have a ParentId (which was deserialized from /// from the parent). This accessor fetches the parent ID if it exists at all. /// Note this can be null if this is a root Activity (it has no parent) /// <para/> /// See <see href="https://github.com/dotnet/corefx/blob/master/src/System.Diagnostics.DiagnosticSource/src/ActivityUserGuide.md#id-format"/> for more details /// </summary> public string? ParentId { #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif get { // if we represented it as a traceId-spanId, convert it to a string. if (_parentId == null) { if (_parentSpanId != null) { Span<char> flagsChars = stackalloc char[2]; HexConverter.ToCharsBuffer((byte)((~ActivityTraceFlagsIsSet) & _parentTraceFlags), flagsChars, 0, HexConverter.Casing.Lower); string parentId = "00-" + _traceId + "-" + _parentSpanId + "-" + flagsChars.ToString(); Interlocked.CompareExchange(ref _parentId, parentId, null); } else if (Parent != null) { Interlocked.CompareExchange(ref _parentId, Parent.Id, null); } } return _parentId; } } /// <summary> /// Root Id is substring from Activity.Id (or ParentId) between '|' (or beginning) and first '.'. /// Filtering by root Id allows to find all Activities involved in operation processing. /// RootId may be null if Activity has neither ParentId nor Id. /// See <see href="https://github.com/dotnet/corefx/blob/master/src/System.Diagnostics.DiagnosticSource/src/ActivityUserGuide.md#id-format"/> for more details /// </summary> public string? RootId { get { //we expect RootId to be requested at any time after activity is created, //possibly even before it was started for sampling or logging purposes //Presumably, it will be called by logging systems for every log record, so we cache it. if (_rootId == null) { string? rootId = null; if (Id != null) { rootId = GetRootId(Id); } else if (ParentId != null) { rootId = GetRootId(ParentId); } if (rootId != null) { Interlocked.CompareExchange(ref _rootId, rootId, null); } } return _rootId; } } /// <summary> /// Tags are string-string key-value pairs that represent information that will /// be logged along with the Activity to the logging system. This information /// however is NOT passed on to the children of this activity. /// </summary> /// <seealso cref="Baggage"/> public IEnumerable<KeyValuePair<string, string?>> Tags { get => _tags?.EnumerateStringValues() ?? s_emptyBaggageTags; } /// <summary> /// List of the tags which represent information that will be logged along with the Activity to the logging system. /// This information however is NOT passed on to the children of this activity. /// </summary> public IEnumerable<KeyValuePair<string, object?>> TagObjects { get => _tags ?? s_emptyTagObjects; } /// <summary> /// Events is the list of all <see cref="ActivityEvent" /> objects attached to this Activity object. /// If there is not any <see cref="ActivityEvent" /> object attached to the Activity object, Events will return empty list. /// </summary> public IEnumerable<ActivityEvent> Events { get => _events ?? s_emptyEvents; } /// <summary> /// Links is the list of all <see cref="ActivityLink" /> objects attached to this Activity object. /// If there is no any <see cref="ActivityLink" /> object attached to the Activity object, Links will return empty list. /// </summary> public IEnumerable<ActivityLink> Links { get => _links ?? s_emptyLinks; } /// <summary> /// Baggage is string-string key-value pairs that represent information that will /// be passed along to children of this activity. Baggage is serialized /// when requests leave the process (along with the ID). Typically Baggage is /// used to do fine-grained control over logging of the activity and any children. /// In general, if you are not using the data at runtime, you should be using Tags /// instead. /// </summary> public IEnumerable<KeyValuePair<string, string?>> Baggage { get { for (Activity? activity = this; activity != null; activity = activity.Parent) { if (activity._baggage != null) { return Iterate(activity); } } return s_emptyBaggageTags; static IEnumerable<KeyValuePair<string, string?>> Iterate(Activity? activity) { Debug.Assert(activity != null); do { if (activity._baggage != null) { for (DiagNode<KeyValuePair<string, string?>>? current = activity._baggage.First; current != null; current = current.Next) { yield return current.Value; } } activity = activity.Parent; } while (activity != null); } } } /// <summary> /// Returns the value of the key-value pair added to the activity with <see cref="AddBaggage(string, string)"/>. /// Returns null if that key does not exist. /// </summary> public string? GetBaggageItem(string key) { foreach (KeyValuePair<string, string?> keyValue in Baggage) if (key == keyValue.Key) return keyValue.Value; return null; } /// <summary> /// Returns the value of the Activity tag mapped to the input key/>. /// Returns null if that key does not exist. /// </summary> /// <param name="key">The tag key string.</param> /// <returns>The tag value mapped to the input key.</returns> public object? GetTagItem(string key) => _tags?.Get(key) ?? null; /* Constructors Builder methods */ /// <summary> /// Note that Activity has a 'builder' pattern, where you call the constructor, a number of 'Set*' and 'Add*' APIs and then /// call <see cref="Start"/> to build the activity. You MUST call <see cref="Start"/> before using it. /// </summary> /// <param name="operationName">Operation's name <see cref="OperationName"/></param> public Activity(string operationName) { Source = s_defaultSource; // Allow data by default in the constructor to keep the compatability. IsAllDataRequested = true; if (string.IsNullOrEmpty(operationName)) { NotifyError(new ArgumentException(SR.OperationNameInvalid)); } OperationName = operationName; } /// <summary> /// Update the Activity to have a tag with an additional 'key' and value 'value'. /// This shows up in the <see cref="Tags"/> enumeration. It is meant for information that /// is useful to log but not needed for runtime control (for the latter, <see cref="Baggage"/>) /// </summary> /// <returns><see langword="this" /> for convenient chaining.</returns> /// <param name="key">The tag key name</param> /// <param name="value">The tag value mapped to the input key</param> public Activity AddTag(string key, string? value) => AddTag(key, (object?) value); /// <summary> /// Update the Activity to have a tag with an additional 'key' and value 'value'. /// This shows up in the <see cref="TagObjects"/> enumeration. It is meant for information that /// is useful to log but not needed for runtime control (for the latter, <see cref="Baggage"/>) /// </summary> /// <returns><see langword="this" /> for convenient chaining.</returns> /// <param name="key">The tag key name</param> /// <param name="value">The tag value mapped to the input key</param> public Activity AddTag(string key, object? value) { KeyValuePair<string, object?> kvp = new KeyValuePair<string, object?>(key, value); if (_tags != null || Interlocked.CompareExchange(ref _tags, new TagsLinkedList(kvp), null) != null) { _tags.Add(kvp); } return this; } /// <summary> /// Add or update the Activity tag with the input key and value. /// If the input value is null /// - if the collection has any tag with the same key, then this tag will get removed from the collection. /// - otherwise, nothing will happen and the collection will not change. /// If the input value is not null /// - if the collection has any tag with the same key, then the value mapped to this key will get updated with the new input value. /// - otherwise, the key and value will get added as a new tag to the collection. /// </summary> /// <param name="key">The tag key name</param> /// <param name="value">The tag value mapped to the input key</param> /// <returns><see langword="this" /> for convenient chaining.</returns> public Activity SetTag(string key, object? value) { KeyValuePair<string, object?> kvp = new KeyValuePair<string, object?>(key, value); if (_tags != null || Interlocked.CompareExchange(ref _tags, new TagsLinkedList(kvp, set: true), null) != null) { _tags.Set(kvp); } return this; } /// <summary> /// Add <see cref="ActivityEvent" /> object to the <see cref="Events" /> list. /// </summary> /// <param name="e"> object of <see cref="ActivityEvent"/> to add to the attached events list.</param> /// <returns><see langword="this" /> for convenient chaining.</returns> public Activity AddEvent(ActivityEvent e) { if (_events != null || Interlocked.CompareExchange(ref _events, new DiagLinkedList<ActivityEvent>(e), null) != null) { _events.Add(e); } return this; } /// <summary> /// Update the Activity to have baggage with an additional 'key' and value 'value'. /// This shows up in the <see cref="Baggage"/> enumeration as well as the <see cref="GetBaggageItem(string)"/> /// method. /// Baggage is meant for information that is needed for runtime control. For information /// that is simply useful to show up in the log with the activity use <see cref="Tags"/>. /// Returns 'this' for convenient chaining. /// </summary> /// <returns><see langword="this" /> for convenient chaining.</returns> public Activity AddBaggage(string key, string? value) { KeyValuePair<string, string?> kvp = new KeyValuePair<string, string?>(key, value); if (_baggage != null || Interlocked.CompareExchange(ref _baggage, new BaggageLinkedList(kvp), null) != null) { _baggage.Add(kvp); } return this; } /// <summary> /// Add or update the Activity baggage with the input key and value. /// If the input value is null /// - if the collection has any baggage with the same key, then this baggage will get removed from the collection. /// - otherwise, nothing will happen and the collection will not change. /// If the input value is not null /// - if the collection has any baggage with the same key, then the value mapped to this key will get updated with the new input value. /// - otherwise, the key and value will get added as a new baggage to the collection. /// </summary> /// <param name="key">The baggage key name</param> /// <param name="value">The baggage value mapped to the input key</param> /// <returns><see langword="this" /> for convenient chaining.</returns> public Activity SetBaggage(string key, string? value) { KeyValuePair<string, string?> kvp = new KeyValuePair<string, string?>(key, value); if (_baggage != null || Interlocked.CompareExchange(ref _baggage, new BaggageLinkedList(kvp, set: true), null) != null) { _baggage.Set(kvp); } return this; } /// <summary> /// Updates the Activity To indicate that the activity with ID <paramref name="parentId"/> /// caused this activity. This is intended to be used only at 'boundary' /// scenarios where an activity from another process logically started /// this activity. The Parent ID shows up the Tags (as well as the ParentID /// property), and can be used to reconstruct the causal tree. /// Returns 'this' for convenient chaining. /// </summary> /// <param name="parentId">The id of the parent operation.</param> public Activity SetParentId(string parentId) { if (Parent != null) { NotifyError(new InvalidOperationException(SR.SetParentIdOnActivityWithParent)); } else if (ParentId != null || _parentSpanId != null) { NotifyError(new InvalidOperationException(SR.ParentIdAlreadySet)); } else if (string.IsNullOrEmpty(parentId)) { NotifyError(new ArgumentException(SR.ParentIdInvalid)); } else { _parentId = parentId; } return this; } /// <summary> /// Set the parent ID using the W3C convention using a TraceId and a SpanId. This /// constructor has the advantage that no string manipulation is needed to set the ID. /// </summary> public Activity SetParentId(ActivityTraceId traceId, ActivitySpanId spanId, ActivityTraceFlags activityTraceFlags = ActivityTraceFlags.None) { if (Parent != null) { NotifyError(new InvalidOperationException(SR.SetParentIdOnActivityWithParent)); } else if (ParentId != null || _parentSpanId != null) { NotifyError(new InvalidOperationException(SR.ParentIdAlreadySet)); } else { _traceId = traceId.ToHexString(); // The child will share the parent's traceId. _parentSpanId = spanId.ToHexString(); ActivityTraceFlags = activityTraceFlags; _parentTraceFlags = (byte) activityTraceFlags; } return this; } /// <summary> /// Update the Activity to set start time /// </summary> /// <param name="startTimeUtc">Activity start time in UTC (Greenwich Mean Time)</param> /// <returns><see langword="this" /> for convenient chaining.</returns> public Activity SetStartTime(DateTime startTimeUtc) { if (startTimeUtc.Kind != DateTimeKind.Utc) { NotifyError(new InvalidOperationException(SR.StartTimeNotUtc)); } else { StartTimeUtc = startTimeUtc; } return this; } /// <summary> /// Update the Activity to set <see cref="Duration"/> /// as a difference between <see cref="StartTimeUtc"/> /// and <paramref name="endTimeUtc"/>. /// </summary> /// <param name="endTimeUtc">Activity stop time in UTC (Greenwich Mean Time)</param> /// <returns><see langword="this" /> for convenient chaining.</returns> public Activity SetEndTime(DateTime endTimeUtc) { if (endTimeUtc.Kind != DateTimeKind.Utc) { NotifyError(new InvalidOperationException(SR.EndTimeNotUtc)); } else { Duration = endTimeUtc - StartTimeUtc; if (Duration.Ticks <= 0) Duration = new TimeSpan(1); // We want Duration of 0 to mean 'EndTime not set) } return this; } /// <summary> /// Get the context of the activity. Context becomes valid only if the activity has been started. /// otherwise will default context. /// </summary> public ActivityContext Context => new ActivityContext(TraceId, SpanId, ActivityTraceFlags, TraceStateString); /// <summary> /// Starts activity /// <list type="bullet"> /// <item>Sets <see cref="Parent"/> to hold <see cref="Current"/>.</item> /// <item>Sets <see cref="Current"/> to this activity.</item> /// <item>If <see cref="StartTimeUtc"/> was not set previously, sets it to <see cref="DateTime.UtcNow"/>.</item> /// <item>Generates a unique <see cref="Id"/> for this activity.</item> /// </list> /// Use <see cref="DiagnosticSource.StartActivity(Activity, object)"/> to start activity and write start event. /// </summary> /// <seealso cref="DiagnosticSource.StartActivity(Activity, object)"/> /// <seealso cref="SetStartTime(DateTime)"/> public Activity Start() { // Has the ID already been set (have we called Start()). if (_id != null || _spanId != null) { NotifyError(new InvalidOperationException(SR.ActivityStartAlreadyStarted)); } else { _previousActiveActivity = Current; if (_parentId == null && _parentSpanId is null) { if (_previousActiveActivity != null) { // The parent change should not form a loop. We are actually guaranteed this because // 1. Un-started activities can't be 'Current' (thus can't be 'parent'), we throw if you try. // 2. All started activities have a finite parent change (by inductive reasoning). Parent = _previousActiveActivity; } } if (StartTimeUtc == default) StartTimeUtc = GetUtcNow(); if (IdFormat == ActivityIdFormat.Unknown) { // Figure out what format to use. IdFormat = ForceDefaultIdFormat ? DefaultIdFormat : Parent != null ? Parent.IdFormat : _parentSpanId != null ? ActivityIdFormat.W3C : _parentId == null ? DefaultIdFormat : IsW3CId(_parentId) ? ActivityIdFormat.W3C : ActivityIdFormat.Hierarchical; } // Generate the ID in the appropriate format. if (IdFormat == ActivityIdFormat.W3C) GenerateW3CId(); else _id = GenerateHierarchicalId(); SetCurrent(this); Source.NotifyActivityStart(this); } return this; } /// <summary> /// Stops activity: sets <see cref="Current"/> to <see cref="Parent"/>. /// If end time was not set previously, sets <see cref="Duration"/> as a difference between <see cref="DateTime.UtcNow"/> and <see cref="StartTimeUtc"/> /// Use <see cref="DiagnosticSource.StopActivity(Activity, object)"/> to stop activity and write stop event. /// </summary> /// <seealso cref="DiagnosticSource.StopActivity(Activity, object)"/> /// <seealso cref="SetEndTime(DateTime)"/> public void Stop() { if (_id == null && _spanId == null) { NotifyError(new InvalidOperationException(SR.ActivityNotStarted)); return; } if (!IsStopped) { IsStopped = true; if (Duration == TimeSpan.Zero) { SetEndTime(GetUtcNow()); } Source.NotifyActivityStop(this); SetCurrent(_previousActiveActivity); } } /* W3C support functionality (see https://w3c.github.io/trace-context) */ /// <summary> /// Holds the W3C 'tracestate' header as a string. /// /// Tracestate is intended to carry information supplemental to trace identity contained /// in traceparent. List of key value pairs carried by tracestate convey information /// about request position in multiple distributed tracing graphs. It is typically used /// by distributed tracing systems and should not be used as a general purpose baggage /// as this use may break correlation of a distributed trace. /// /// Logically it is just a kind of baggage (if flows just like baggage), but because /// it is expected to be special cased (it has its own HTTP header), it is more /// convenient/efficient if it is not lumped in with other baggage. /// </summary> public string? TraceStateString { get { for (Activity? activity = this; activity != null; activity = activity.Parent) { string? val = activity._traceState; if (val != null) return val; } return null; } set { _traceState = value; } } /// <summary> /// If the Activity has the W3C format, this returns the ID for the SPAN part of the Id. /// Otherwise it returns a zero SpanId. /// </summary> public ActivitySpanId SpanId { #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif get { if (_spanId is null) { if (_id != null && IdFormat == ActivityIdFormat.W3C) { ActivitySpanId activitySpanId = ActivitySpanId.CreateFromString(_id.AsSpan(36, 16)); string spanId = activitySpanId.ToHexString(); Interlocked.CompareExchange(ref _spanId, spanId, null); } } return new ActivitySpanId(_spanId); } } /// <summary> /// If the Activity has the W3C format, this returns the ID for the TraceId part of the Id. /// Otherwise it returns a zero TraceId. /// </summary> public ActivityTraceId TraceId { get { if (_traceId is null) { TrySetTraceIdFromParent(); } return new ActivityTraceId(_traceId); } } /// <summary> /// True if the W3CIdFlags.Recorded flag is set. /// </summary> public bool Recorded { get => (ActivityTraceFlags & ActivityTraceFlags.Recorded) != 0; } /// <summary> /// Indicate if the this Activity object should be populated with all the propagation info and also all other /// properties such as Links, Tags, and Events. /// </summary> public bool IsAllDataRequested { get; set;} /// <summary> /// Return the flags (defined by the W3C ID specification) associated with the activity. /// </summary> public ActivityTraceFlags ActivityTraceFlags { get { if (!W3CIdFlagsSet) { TrySetTraceFlagsFromParent(); } return (ActivityTraceFlags)((~ActivityTraceFlagsIsSet) & _w3CIdFlags); } set { _w3CIdFlags = (byte)(ActivityTraceFlagsIsSet | (byte)value); } } /// <summary> /// If the parent Activity ID has the W3C format, this returns the ID for the SpanId part of the ParentId. /// Otherwise it returns a zero SpanId. /// </summary> public ActivitySpanId ParentSpanId { #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif get { if (_parentSpanId is null) { string? parentSpanId = null; if (_parentId != null && IsW3CId(_parentId)) { try { parentSpanId = ActivitySpanId.CreateFromString(_parentId.AsSpan(36, 16)).ToHexString(); } catch { } } else if (Parent != null && Parent.IdFormat == ActivityIdFormat.W3C) { parentSpanId = Parent.SpanId.ToHexString(); } if (parentSpanId != null) { Interlocked.CompareExchange(ref _parentSpanId, parentSpanId, null); } } return new ActivitySpanId(_parentSpanId); } } /// <summary> /// When starting an Activity which does not have a parent context, the Trace Id will automatically be generated using random numbers. /// TraceIdGenerator can be used to override the runtime's default Trace Id generation algorithm. /// </summary> /// <remarks> /// - TraceIdGenerator needs to be set only if the default Trace Id generation is not enough for the app scenario. /// - When setting TraceIdGenerator, ensure it is performant enough to avoid any slowness in the Activity starting operation. /// - If TraceIdGenerator is set multiple times, the last set will be the one used for the Trace Id generation. /// - Setting TraceIdGenerator to null will re-enable the default Trace Id generation algorithm. /// </remarks> public static Func<ActivityTraceId>? TraceIdGenerator { get; set; } /* static state (configuration) */ /// <summary> /// Activity tries to use the same format for IDs as its parent. /// However if the activity has no parent, it has to do something. /// This determines the default format we use. /// </summary> public static ActivityIdFormat DefaultIdFormat { get { if (s_defaultIdFormat == ActivityIdFormat.Unknown) { #if W3C_DEFAULT_ID_FORMAT s_defaultIdFormat = LocalAppContextSwitches.DefaultActivityIdFormatIsHierarchial ? ActivityIdFormat.Hierarchical : ActivityIdFormat.W3C; #else s_defaultIdFormat = ActivityIdFormat.Hierarchical; #endif // W3C_DEFAULT_ID_FORMAT } return s_defaultIdFormat; } set { if (!(ActivityIdFormat.Hierarchical <= value && value <= ActivityIdFormat.W3C)) throw new ArgumentException(SR.ActivityIdFormatInvalid); s_defaultIdFormat = value; } } /// <summary> /// Sets IdFormat on the Activity before it is started. It takes precedence over /// Parent.IdFormat, ParentId format, DefaultIdFormat and ForceDefaultIdFormat. /// </summary> public Activity SetIdFormat(ActivityIdFormat format) { if (_id != null || _spanId != null) { NotifyError(new InvalidOperationException(SR.SetFormatOnStartedActivity)); } else { IdFormat = format; } return this; } /// <summary> /// Returns true if 'id' has the format of a WC3 id see https://w3c.github.io/trace-context /// </summary> private static bool IsW3CId(string id) { // A W3CId is // * 2 hex chars Version (ff is invalid) // * 1 char - char // * 32 hex chars traceId // * 1 char - char // * 16 hex chars spanId // * 1 char - char // * 2 hex chars flags // = 55 chars (see https://w3c.github.io/trace-context) // The version (00-fe) is used to indicate that this is a WC3 ID. return id.Length == 55 && ('0' <= id[0] && id[0] <= '9' || 'a' <= id[0] && id[0] <= 'f') && ('0' <= id[1] && id[1] <= '9' || 'a' <= id[1] && id[1] <= 'f') && (id[0] != 'f' || id[1] != 'f'); } #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif internal static bool TryConvertIdToContext(string traceParent, string? traceState, bool isRemote, out ActivityContext context) { context = default; if (!IsW3CId(traceParent)) { return false; } ReadOnlySpan<char> traceIdSpan = traceParent.AsSpan(3, 32); ReadOnlySpan<char> spanIdSpan = traceParent.AsSpan(36, 16); if (!ActivityTraceId.IsLowerCaseHexAndNotAllZeros(traceIdSpan) || !ActivityTraceId.IsLowerCaseHexAndNotAllZeros(spanIdSpan) || !HexConverter.IsHexLowerChar(traceParent[53]) || !HexConverter.IsHexLowerChar(traceParent[54])) { return false; } context = new ActivityContext( new ActivityTraceId(traceIdSpan.ToString()), new ActivitySpanId(spanIdSpan.ToString()), (ActivityTraceFlags) ActivityTraceId.HexByteFromChars(traceParent[53], traceParent[54]), traceState, isRemote); return true; } /// <summary> /// Dispose will stop the Activity if it is already started and notify any event listeners. Nothing will happen otherwise. /// </summary> public void Dispose() { if (!IsStopped) { Stop(); } Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } /// <summary> /// SetCustomProperty allow attaching any custom object to this Activity object. /// If the property name was previously associated with other object, SetCustomProperty will update to use the new propert value instead. /// </summary> /// <param name="propertyName"> The name to associate the value with.<see cref="OperationName"/></param> /// <param name="propertyValue">The object to attach and map to the property name.</param> public void SetCustomProperty(string propertyName, object? propertyValue) { if (_customProperties == null) { Interlocked.CompareExchange(ref _customProperties, new Dictionary<string, object>(), null); } lock (_customProperties) { if (propertyValue == null) { _customProperties.Remove(propertyName); } else { _customProperties[propertyName] = propertyValue!; } } } /// <summary> /// GetCustomProperty retrieve previously attached object mapped to the property name. /// </summary> /// <param name="propertyName"> The name to get the associated object with.</param> /// <returns>The object mapped to the property name. Or null if there is no mapping previously done with this property name.</returns> public object? GetCustomProperty(string propertyName) { // We don't check null name here as the dictionary is performing this check anyway. if (_customProperties == null) { return null; } object? ret; lock (_customProperties) { ret = _customProperties.TryGetValue(propertyName, out object? o) ? o! : null; } return ret; } internal static Activity Create(ActivitySource source, string name, ActivityKind kind, string? parentId, ActivityContext parentContext, IEnumerable<KeyValuePair<string, object?>>? tags, IEnumerable<ActivityLink>? links, DateTimeOffset startTime, ActivityTagsCollection? samplerTags, ActivitySamplingResult request, bool startIt, ActivityIdFormat idFormat) { Activity activity = new Activity(name); activity.Source = source; activity.Kind = kind; activity.IdFormat = idFormat; if (links != null) { using (IEnumerator<ActivityLink> enumerator = links.GetEnumerator()) { if (enumerator.MoveNext()) { activity._links = new DiagLinkedList<ActivityLink>(enumerator); } } } if (tags != null) { using (IEnumerator<KeyValuePair<string, object?>> enumerator = tags.GetEnumerator()) { if (enumerator.MoveNext()) { activity._tags = new TagsLinkedList(enumerator); } } } if (samplerTags != null) { if (activity._tags == null) { activity._tags = new TagsLinkedList(samplerTags!); } else { activity._tags.Add(samplerTags!); } } if (parentId != null) { activity._parentId = parentId; } else if (parentContext != default) { activity._traceId = parentContext.TraceId.ToString(); if (parentContext.SpanId != default) { activity._parentSpanId = parentContext.SpanId.ToString(); } activity.ActivityTraceFlags = parentContext.TraceFlags; activity._parentTraceFlags = (byte) parentContext.TraceFlags; activity._traceState = parentContext.TraceState; } activity.IsAllDataRequested = request == ActivitySamplingResult.AllData || request == ActivitySamplingResult.AllDataAndRecorded; if (request == ActivitySamplingResult.AllDataAndRecorded) { activity.ActivityTraceFlags |= ActivityTraceFlags.Recorded; } if (startTime != default) { activity.StartTimeUtc = startTime.UtcDateTime; } if (startIt) { activity.Start(); } return activity; } /// <summary> /// Set the ID (lazily, avoiding strings if possible) to a W3C ID (using the /// traceId from the parent if possible /// </summary> private void GenerateW3CId() { // Called from .Start() // Get the TraceId from the parent or make a new one. if (_traceId is null) { if (!TrySetTraceIdFromParent()) { Func<ActivityTraceId>? traceIdGenerator = TraceIdGenerator; ActivityTraceId id = traceIdGenerator == null ? ActivityTraceId.CreateRandom() : traceIdGenerator(); _traceId = id.ToHexString(); } } if (!W3CIdFlagsSet) { TrySetTraceFlagsFromParent(); } // Create a new SpanID. _spanId = ActivitySpanId.CreateRandom().ToHexString(); } private static void NotifyError(Exception exception) { // Throw and catch the exception. This lets it be seen by the debugger // ETW, and other monitoring tools. However we immediately swallow the // exception. We may wish in the future to allow users to hook this // in other useful ways but for now we simply swallow the exceptions. try { throw exception; } catch { } } /// <summary> /// Returns a new ID using the Hierarchical Id /// </summary> private string GenerateHierarchicalId() { // Called from .Start() string ret; if (Parent != null) { // Normal start within the process Debug.Assert(!string.IsNullOrEmpty(Parent.Id)); ret = AppendSuffix(Parent.Id, Interlocked.Increment(ref Parent._currentChildId).ToString(), '.'); } else if (ParentId != null) { // Start from outside the process (e.g. incoming HTTP) Debug.Assert(ParentId.Length != 0); //sanitize external RequestId as it may not be hierarchical. //we cannot update ParentId, we must let it be logged exactly as it was passed. string parentId = ParentId[0] == '|' ? ParentId : '|' + ParentId; char lastChar = parentId[parentId.Length - 1]; if (lastChar != '.' && lastChar != '_') { parentId += '.'; } ret = AppendSuffix(parentId, Interlocked.Increment(ref s_currentRootId).ToString("x"), '_'); } else { // A Root Activity (no parent). ret = GenerateRootId(); } // Useful place to place a conditional breakpoint. return ret; } private string GetRootId(string id) { // If this is a W3C ID it has the format Version2-TraceId32-SpanId16-Flags2 // and the root ID is the TraceId. if (IdFormat == ActivityIdFormat.W3C) return id.Substring(3, 32); //id MAY start with '|' and contain '.'. We return substring between them //ParentId MAY NOT have hierarchical structure and we don't know if initially rootId was started with '|', //so we must NOT include first '|' to allow mixed hierarchical and non-hierarchical request id scenarios int rootEnd = id.IndexOf('.'); if (rootEnd < 0) rootEnd = id.Length; int rootStart = id[0] == '|' ? 1 : 0; return id.Substring(rootStart, rootEnd - rootStart); } private string AppendSuffix(string parentId, string suffix, char delimiter) { #if DEBUG suffix = OperationName.Replace('.', '-') + "-" + suffix; #endif if (parentId.Length + suffix.Length < RequestIdMaxLength) return parentId + suffix + delimiter; //Id overflow: //find position in RequestId to trim int trimPosition = RequestIdMaxLength - 9; // overflow suffix + delimiter length is 9 while (trimPosition > 1) { if (parentId[trimPosition - 1] == '.' || parentId[trimPosition - 1] == '_') break; trimPosition--; } //ParentId is not valid Request-Id, let's generate proper one. if (trimPosition == 1) return GenerateRootId(); //generate overflow suffix string overflowSuffix = ((int)GetRandomNumber()).ToString("x8"); return parentId.Substring(0, trimPosition) + overflowSuffix + '#'; } #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif private static unsafe long GetRandomNumber() { // Use the first 8 bytes of the GUID as a random number. Guid g = Guid.NewGuid(); return *((long*)&g); } private static bool ValidateSetCurrent(Activity? activity) { bool canSet = activity == null || (activity.Id != null && !activity.IsStopped); if (!canSet) { NotifyError(new InvalidOperationException(SR.ActivityNotRunning)); } return canSet; } #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif private bool TrySetTraceIdFromParent() { Debug.Assert(_traceId is null); if (Parent != null && Parent.IdFormat == ActivityIdFormat.W3C) { _traceId = Parent.TraceId.ToHexString(); } else if (_parentId != null && IsW3CId(_parentId)) { try { _traceId = ActivityTraceId.CreateFromString(_parentId.AsSpan(3, 32)).ToHexString(); } catch { } } return _traceId != null; } #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif private void TrySetTraceFlagsFromParent() { Debug.Assert(!W3CIdFlagsSet); if (!W3CIdFlagsSet) { if (Parent != null) { ActivityTraceFlags = Parent.ActivityTraceFlags; } else if (_parentId != null && IsW3CId(_parentId)) { if (HexConverter.IsHexLowerChar(_parentId[53]) && HexConverter.IsHexLowerChar(_parentId[54])) { _w3CIdFlags = (byte)(ActivityTraceId.HexByteFromChars(_parentId[53], _parentId[54]) | ActivityTraceFlagsIsSet); } else { _w3CIdFlags = ActivityTraceFlagsIsSet; } } } } private bool W3CIdFlagsSet { get => (_w3CIdFlags & ActivityTraceFlagsIsSet) != 0; } /// <summary> /// Indicates whether this <see cref="Activity"/> object is stopped /// </summary> /// <remarks> /// When subscribing to <see cref="Activity"/> stop event using <see cref="ActivityListener.ActivityStopped"/>, the received <see cref="Activity"/> object in the event callback will have <see cref="IsStopped"/> as true. /// </remarks> public bool IsStopped { get => (_state & State.IsStopped) != 0; private set { if (value) { _state |= State.IsStopped; } else { _state &= ~State.IsStopped; } } } /// <summary> /// Returns the format for the ID. /// </summary> public ActivityIdFormat IdFormat { get => (ActivityIdFormat)(_state & State.FormatFlags); private set => _state = (_state & ~State.FormatFlags) | (State)((byte)value & (byte)State.FormatFlags); } private sealed class BaggageLinkedList : IEnumerable<KeyValuePair<string, string?>> { private DiagNode<KeyValuePair<string, string?>>? _first; public BaggageLinkedList(KeyValuePair<string, string?> firstValue, bool set = false) => _first = ((set && firstValue.Value == null) ? null : new DiagNode<KeyValuePair<string, string?>>(firstValue)); public DiagNode<KeyValuePair<string, string?>>? First => _first; public void Add(KeyValuePair<string, string?> value) { DiagNode<KeyValuePair<string, string?>> newNode = new DiagNode<KeyValuePair<string, string?>>(value); lock (this) { newNode.Next = _first; _first = newNode; } } public void Set(KeyValuePair<string, string?> value) { if (value.Value == null) { Remove(value.Key); return; } lock (this) { DiagNode<KeyValuePair<string, string?>>? current = _first; while (current != null) { if (current.Value.Key == value.Key) { current.Value = value; return; } current = current.Next; } DiagNode<KeyValuePair<string, string?>> newNode = new DiagNode<KeyValuePair<string, string?>>(value); newNode.Next = _first; _first = newNode; } } public void Remove(string key) { lock (this) { if (_first == null) { return; } if (_first.Value.Key == key) { _first = _first.Next; return; } DiagNode<KeyValuePair<string, string?>> previous = _first; while (previous.Next != null) { if (previous.Next.Value.Key == key) { previous.Next = previous.Next.Next; return; } previous = previous.Next; } } } // Note: Some consumers use this GetEnumerator dynamically to avoid allocations. public Enumerator<KeyValuePair<string, string?>> GetEnumerator() => new Enumerator<KeyValuePair<string, string?>>(_first); IEnumerator<KeyValuePair<string, string?>> IEnumerable<KeyValuePair<string, string?>>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } private sealed class TagsLinkedList : IEnumerable<KeyValuePair<string, object?>> { private DiagNode<KeyValuePair<string, object?>>? _first; private DiagNode<KeyValuePair<string, object?>>? _last; private StringBuilder? _stringBuilder; public TagsLinkedList(KeyValuePair<string, object?> firstValue, bool set = false) => _last = _first = ((set && firstValue.Value == null) ? null : new DiagNode<KeyValuePair<string, object?>>(firstValue)); public TagsLinkedList(IEnumerator<KeyValuePair<string, object?>> e) { _last = _first = new DiagNode<KeyValuePair<string, object?>>(e.Current); while (e.MoveNext()) { _last.Next = new DiagNode<KeyValuePair<string, object?>>(e.Current); _last = _last.Next; } } public TagsLinkedList(IEnumerable<KeyValuePair<string, object?>> list) => Add(list); // Add doesn't take the lock because it is called from the Activity creation before sharing the activity object to the caller. public void Add(IEnumerable<KeyValuePair<string, object?>> list) { IEnumerator<KeyValuePair<string, object?>> e = list.GetEnumerator(); if (!e.MoveNext()) { return; } if (_first == null) { _last = _first = new DiagNode<KeyValuePair<string, object?>>(e.Current); } else { _last!.Next = new DiagNode<KeyValuePair<string, object?>>(e.Current); _last = _last.Next; } while (e.MoveNext()) { _last.Next = new DiagNode<KeyValuePair<string, object?>>(e.Current); _last = _last.Next; } } public void Add(KeyValuePair<string, object?> value) { DiagNode<KeyValuePair<string, object?>> newNode = new DiagNode<KeyValuePair<string, object?>>(value); lock (this) { if (_first == null) { _first = _last = newNode; return; } Debug.Assert(_last != null); _last!.Next = newNode; _last = newNode; } } public object? Get(string key) { // We don't take the lock here so it is possible the Add/Remove operations mutate the list during the Get operation. DiagNode<KeyValuePair<string, object?>>? current = _first; while (current != null) { if (current.Value.Key == key) { return current.Value.Value; } current = current.Next; } return null; } public void Remove(string key) { lock (this) { if (_first == null) { return; } if (_first.Value.Key == key) { _first = _first.Next; if (_first is null) { _last = null; } return; } DiagNode<KeyValuePair<string, object?>> previous = _first; while (previous.Next != null) { if (previous.Next.Value.Key == key) { if (object.ReferenceEquals(_last, previous.Next)) { _last = previous; } previous.Next = previous.Next.Next; return; } previous = previous.Next; } } } public void Set(KeyValuePair<string, object?> value) { if (value.Value == null) { Remove(value.Key); return; } lock (this) { DiagNode<KeyValuePair<string, object?>>? current = _first; while (current != null) { if (current.Value.Key == value.Key) { current.Value = value; return; } current = current.Next; } DiagNode<KeyValuePair<string, object?>> newNode = new DiagNode<KeyValuePair<string, object?>>(value); if (_first == null) { _first = _last = newNode; return; } Debug.Assert(_last != null); _last!.Next = newNode; _last = newNode; } } // Note: Some consumers use this GetEnumerator dynamically to avoid allocations. public Enumerator<KeyValuePair<string, object?>> GetEnumerator() => new Enumerator<KeyValuePair<string, object?>>(_first); IEnumerator<KeyValuePair<string, object?>> IEnumerable<KeyValuePair<string, object?>>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public IEnumerable<KeyValuePair<string, string?>> EnumerateStringValues() { DiagNode<KeyValuePair<string, object?>>? current = _first; while (current != null) { if (current.Value.Value is string || current.Value.Value == null) { yield return new KeyValuePair<string, string?>(current.Value.Key, (string?)current.Value.Value); } current = current.Next; }; } public override string ToString() { lock (this) { if (_first == null) { return string.Empty; } _stringBuilder ??= new StringBuilder(); _stringBuilder.Append(_first.Value.Key); _stringBuilder.Append(':'); _stringBuilder.Append(_first.Value.Value); DiagNode<KeyValuePair<string, object?>>? current = _first.Next; while (current != null) { _stringBuilder.Append(", "); _stringBuilder.Append(current.Value.Key); _stringBuilder.Append(':'); _stringBuilder.Append(current.Value.Value); current = current.Next; } string result = _stringBuilder.ToString(); _stringBuilder.Clear(); return result; } } } [Flags] private enum State : byte { None = 0, FormatUnknown = 0b_0_00000_00, FormatHierarchical = 0b_0_00000_01, FormatW3C = 0b_0_00000_10, FormatFlags = 0b_0_00000_11, IsStopped = 0b_1_00000_00, } } /// <summary> /// These flags are defined by the W3C standard along with the ID for the activity. /// </summary> [Flags] public enum ActivityTraceFlags { None = 0b_0_0000000, Recorded = 0b_0_0000001, // The Activity (or more likely its parents) has been marked as useful to record } /// <summary> /// The possibilities for the format of the ID /// </summary> public enum ActivityIdFormat { Unknown = 0, // ID format is not known. Hierarchical = 1, //|XXXX.XX.X_X ... see https://github.com/dotnet/corefx/blob/master/src/System.Diagnostics.DiagnosticSource/src/ActivityUserGuide.md#id-format W3C = 2, // 00-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXX-XX see https://w3c.github.io/trace-context/ }; /// <summary> /// A TraceId is the format the W3C standard requires for its ID for the entire trace. /// It represents 16 binary bytes of information, typically displayed as 32 characters /// of Hexadecimal. A TraceId is a STRUCT, and does contain the 16 bytes of binary information /// so there is value in passing it by reference. It does know how to convert to and /// from its Hexadecimal string representation, tries to avoid changing formats until /// it has to, and caches the string representation after it was created. /// It is mostly useful as an exchange type. /// </summary> #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif public readonly struct ActivityTraceId : IEquatable<ActivityTraceId> { private readonly string? _hexString; internal ActivityTraceId(string? hexString) => _hexString = hexString; /// <summary> /// Create a new TraceId with at random number in it (very likely to be unique) /// </summary> public static ActivityTraceId CreateRandom() { Span<byte> span = stackalloc byte[sizeof(ulong) * 2]; SetToRandomBytes(span); return CreateFromBytes(span); } public static ActivityTraceId CreateFromBytes(ReadOnlySpan<byte> idData) { if (idData.Length != 16) throw new ArgumentOutOfRangeException(nameof(idData)); return new ActivityTraceId(HexConverter.ToString(idData, HexConverter.Casing.Lower)); } public static ActivityTraceId CreateFromUtf8String(ReadOnlySpan<byte> idData) => new ActivityTraceId(idData); public static ActivityTraceId CreateFromString(ReadOnlySpan<char> idData) { if (idData.Length != 32 || !ActivityTraceId.IsLowerCaseHexAndNotAllZeros(idData)) throw new ArgumentOutOfRangeException(nameof(idData)); return new ActivityTraceId(idData.ToString()); } /// <summary> /// Returns the TraceId as a 32 character hexadecimal string. /// </summary> public string ToHexString() { return _hexString ?? "00000000000000000000000000000000"; } /// <summary> /// Returns the TraceId as a 32 character hexadecimal string. /// </summary> public override string ToString() => ToHexString(); public static bool operator ==(ActivityTraceId traceId1, ActivityTraceId traceId2) { return traceId1._hexString == traceId2._hexString; } public static bool operator !=(ActivityTraceId traceId1, ActivityTraceId traceId2) { return traceId1._hexString != traceId2._hexString; } public bool Equals(ActivityTraceId traceId) { return _hexString == traceId._hexString; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is ActivityTraceId traceId) return _hexString == traceId._hexString; return false; } public override int GetHashCode() { return ToHexString().GetHashCode(); } /// <summary> /// This is exposed as CreateFromUtf8String, but we are modifying fields, so the code needs to be in a constructor. /// </summary> /// <param name="idData"></param> private ActivityTraceId(ReadOnlySpan<byte> idData) { if (idData.Length != 32) throw new ArgumentOutOfRangeException(nameof(idData)); Span<ulong> span = stackalloc ulong[2]; if (!Utf8Parser.TryParse(idData.Slice(0, 16), out span[0], out _, 'x')) { // Invalid Id, use random https://github.com/dotnet/runtime/issues/29859 _hexString = CreateRandom()._hexString; return; } if (!Utf8Parser.TryParse(idData.Slice(16, 16), out span[1], out _, 'x')) { // Invalid Id, use random https://github.com/dotnet/runtime/issues/29859 _hexString = CreateRandom()._hexString; return; } if (BitConverter.IsLittleEndian) { span[0] = BinaryPrimitives.ReverseEndianness(span[0]); span[1] = BinaryPrimitives.ReverseEndianness(span[1]); } _hexString = HexConverter.ToString(MemoryMarshal.AsBytes(span), HexConverter.Casing.Lower); } /// <summary> /// Copy the bytes of the TraceId (16 total) into the 'destination' span. /// </summary> public void CopyTo(Span<byte> destination) { ActivityTraceId.SetSpanFromHexChars(ToHexString().AsSpan(), destination); } /// <summary> /// Sets the bytes in 'outBytes' to be random values. outBytes.Length must be either 8 or 16 bytes. /// </summary> /// <param name="outBytes"></param> internal static unsafe void SetToRandomBytes(Span<byte> outBytes) { Debug.Assert(outBytes.Length == 16 || outBytes.Length == 8); RandomNumberGenerator r = RandomNumberGenerator.Current; Unsafe.WriteUnaligned(ref outBytes[0], r.Next()); if (outBytes.Length == 16) { Unsafe.WriteUnaligned(ref outBytes[8], r.Next()); } } /// <summary> /// Converts 'idData' which is assumed to be HEX Unicode characters to binary /// puts it in 'outBytes' /// </summary> internal static void SetSpanFromHexChars(ReadOnlySpan<char> charData, Span<byte> outBytes) { Debug.Assert(outBytes.Length * 2 == charData.Length); for (int i = 0; i < outBytes.Length; i++) outBytes[i] = HexByteFromChars(charData[i * 2], charData[i * 2 + 1]); } internal static byte HexByteFromChars(char char1, char char2) { int hi = HexConverter.FromLowerChar(char1); int lo = HexConverter.FromLowerChar(char2); if ((hi | lo) == 0xFF) { throw new ArgumentOutOfRangeException("idData"); } return (byte)((hi << 4) | lo); } internal static bool IsLowerCaseHexAndNotAllZeros(ReadOnlySpan<char> idData) { // Verify lower-case hex and not all zeros https://w3c.github.io/trace-context/#field-value bool isNonZero = false; int i = 0; for (; i < idData.Length; i++) { char c = idData[i]; if (!HexConverter.IsHexLowerChar(c)) { return false; } if (c != '0') { isNonZero = true; } } return isNonZero; } } /// <summary> /// A SpanId is the format the W3C standard requires for its ID for a single span in a trace. /// It represents 8 binary bytes of information, typically displayed as 16 characters /// of Hexadecimal. A SpanId is a STRUCT, and does contain the 8 bytes of binary information /// so there is value in passing it by reference. It does know how to convert to and /// from its Hexadecimal string representation, tries to avoid changing formats until /// it has to, and caches the string representation after it was created. /// It is mostly useful as an exchange type. /// </summary> #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif public readonly struct ActivitySpanId : IEquatable<ActivitySpanId> { private readonly string? _hexString; internal ActivitySpanId(string? hexString) => _hexString = hexString; /// <summary> /// Create a new SpanId with at random number in it (very likely to be unique) /// </summary> public static unsafe ActivitySpanId CreateRandom() { ulong id; ActivityTraceId.SetToRandomBytes(new Span<byte>(&id, sizeof(ulong))); return new ActivitySpanId(HexConverter.ToString(new ReadOnlySpan<byte>(&id, sizeof(ulong)), HexConverter.Casing.Lower)); } public static ActivitySpanId CreateFromBytes(ReadOnlySpan<byte> idData) { if (idData.Length != 8) throw new ArgumentOutOfRangeException(nameof(idData)); return new ActivitySpanId(HexConverter.ToString(idData, HexConverter.Casing.Lower)); } public static ActivitySpanId CreateFromUtf8String(ReadOnlySpan<byte> idData) => new ActivitySpanId(idData); public static ActivitySpanId CreateFromString(ReadOnlySpan<char> idData) { if (idData.Length != 16 || !ActivityTraceId.IsLowerCaseHexAndNotAllZeros(idData)) throw new ArgumentOutOfRangeException(nameof(idData)); return new ActivitySpanId(idData.ToString()); } /// <summary> /// Returns the SpanId as a 16 character hexadecimal string. /// </summary> /// <returns></returns> public string ToHexString() { return _hexString ?? "0000000000000000"; } /// <summary> /// Returns SpanId as a hex string. /// </summary> public override string ToString() => ToHexString(); public static bool operator ==(ActivitySpanId spanId1, ActivitySpanId spandId2) { return spanId1._hexString == spandId2._hexString; } public static bool operator !=(ActivitySpanId spanId1, ActivitySpanId spandId2) { return spanId1._hexString != spandId2._hexString; } public bool Equals(ActivitySpanId spanId) { return _hexString == spanId._hexString; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is ActivitySpanId spanId) return _hexString == spanId._hexString; return false; } public override int GetHashCode() { return ToHexString().GetHashCode(); } private unsafe ActivitySpanId(ReadOnlySpan<byte> idData) { if (idData.Length != 16) { throw new ArgumentOutOfRangeException(nameof(idData)); } if (!Utf8Parser.TryParse(idData, out ulong id, out _, 'x')) { // Invalid Id, use random https://github.com/dotnet/runtime/issues/29859 _hexString = CreateRandom()._hexString; return; } if (BitConverter.IsLittleEndian) { id = BinaryPrimitives.ReverseEndianness(id); } _hexString = HexConverter.ToString(new ReadOnlySpan<byte>(&id, sizeof(ulong)), HexConverter.Casing.Lower); } /// <summary> /// Copy the bytes of the TraceId (8 bytes total) into the 'destination' span. /// </summary> public void CopyTo(Span<byte> destination) { ActivityTraceId.SetSpanFromHexChars(ToHexString().AsSpan(), destination); } } }
40.293907
227
0.544031
[ "MIT" ]
333fred/runtime
src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.cs
78,694
C#
using GalaSoft.MvvmLight.Messaging; using Logic.Messages.SchluesselMessages; using Logic.UI.SchluesselverwaltungViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using UI.Desktop.Schluesselverwaltung; namespace Vereinsverwaltung.UI.Desktop.Schluesselverwaltung { /// <summary> /// Interaktionslogik für SchluesselverteilungSchluesselUebersichtView.xaml /// </summary> public partial class SchluesselverteilungSchluesselUebersichtView : UserControl { public SchluesselverteilungSchluesselUebersichtView() { InitializeComponent(); Messenger.Default.Register<OpenSchluesselzuteilungMessage>(this, "SchluesselverteilungSchluesselUebersicht", m => ReceiveOpenSchluesselzuteilungMessage(m)); Messenger.Default.Register<OpenSchluesselRueckgabeMessage>(this, "SchluesselverteilungSchluesselUebersicht", m => ReceiveOpenSchluesselRueckgabeMessage(m)); } private void ReceiveOpenSchluesselRueckgabeMessage(OpenSchluesselRueckgabeMessage m) { var view = new SchluesselRueckgabeStammdatenView() { Owner = Application.Current.MainWindow }; if (view.DataContext is SchluesselRueckgabeStammdatenViewModel model) { model.SetInformation(m.ID, m.AuswahlTypes); } view.ShowDialog(); } private void ReceiveOpenSchluesselzuteilungMessage(OpenSchluesselzuteilungMessage m) { var view = new SchluesselzuteilungStammdatenView() { Owner = Application.Current.MainWindow }; if (view.DataContext is SchluesselzuteilungStammdatenViewModel model) { model.BySchluesselID(m.ID); } view.ShowDialog(); } } }
34.746032
168
0.699406
[ "MIT" ]
Maersmann/Vereinsverwaltung
Vereinsverwaltung/UI/UI.Desktop/Schluesselverwaltung/SchluesselverteilungSchluesselUebersichtView.xaml.cs
2,192
C#
namespace SqlToCsharp { using System.Collections.Generic; static class TupleExtensions { public static IEnumerable<(T item, int index)> Indexed<T>(this IEnumerable<T> items) { int index = 0; foreach (var item in items) { yield return (item, index); ++index; } } } }
21.555556
92
0.502577
[ "MIT" ]
guitarrapc/SqlToCsharp
src/SqlToCsharp/ValueTupleExtensions.cs
390
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class NextScenePoint : MonoBehaviour { public delegate void ChangeScene(int sceneIndex); public static event ChangeScene changeScene; void OnCollisionEnter2D(Collision2D other) { if(other.gameObject.CompareTag("Player")) changeScene?.Invoke(SceneManager.GetActiveScene().buildIndex + 1); } }
27
81
0.745098
[ "MIT" ]
WesleyTavaresGameDev/RabbitPlatform
RabbitPlatform/Assets/2.Scripts/SceneSystem/NextScenePoint.cs
461
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Knowdes { public enum MetaDataType { Unset = 0, Title = 10, Tags = 11, Author = 12, CreationDate = 13, LastChangedDate = 14, Comment = 15, Description = 16, PreviewImage = 17 } static class MetaDataTypeMethods { public static string GetName(this MetaDataType type) { switch (type) { case MetaDataType.Unset: return "Metadatum hinzufügen"; case MetaDataType.Title: return "Titel"; case MetaDataType.Author: return "Autoren"; case MetaDataType.CreationDate: return "Erstellungsdatum"; case MetaDataType.LastChangedDate: return "Änderungsdatum"; case MetaDataType.Tags: return "Schlagwörter"; case MetaDataType.Comment: return "Kommentar"; case MetaDataType.Description: return "Beschreibung"; case MetaDataType.PreviewImage: return "Vorschaubild"; default: throw new NotImplementedException(); } } } }
27.882353
60
0.50211
[ "MIT" ]
BlackLambert/knowdes
Knowdes Project/Assets/Scripts/Data/MetaData/MetaDataType.cs
1,427
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FeelTheField { class PrintTheField { public static void PrintField(char[,] field) { StringBuilder fillTheField = new StringBuilder(); for (int i = 0; i < field.GetLength(0); i++) { for (int j = 0; j < field.GetLength(1); j++) { fillTheField.Append(field[i, j]); } fillTheField.AppendLine(); } Console.WriteLine(fillTheField); } public static void FillWithChar(char[,] inputChar, char addChar) { for (int i = 0; i < inputChar.GetLength(0); i++) { for (int j = 0; j < inputChar.GetLength(1); j++) { inputChar[i, j] = addChar; } } } } }
25.578947
72
0.476337
[ "MIT" ]
tutzy/SHADDA-BI-BORAN-WYL-Game
game/FeelTheField/PrintTheField.cs
974
C#
namespace BuddyApiClient.Core.Models.Request { public abstract record SortQuery : CollectionQuery { public SortDirection? SortDirection { get; set; } protected abstract string? GetSortBy(); private string? GetSortDirection() { return SortDirection switch { Request.SortDirection.Ascending => "ASC", Request.SortDirection.Descending => "DESC", _ => null }; } private void AddSortBy(QueryStringParameters parameters) { parameters.Add("sort_by", GetSortBy); } private void AddSortDirection(QueryStringParameters parameters) { parameters.Add("sort_direction", GetSortDirection); } protected override void AddParameters(QueryStringParameters parameters) { base.AddParameters(parameters); AddSortBy(parameters); AddSortDirection(parameters); } } }
27.459459
79
0.587598
[ "MIT" ]
logikfabrik/BuddyApiClient
src/BuddyApiClient/Core/Models/Request/SortQuery.cs
1,018
C#
using System; using System.Collections.Generic; using System.Text; namespace Poco.Evolved.SQL.Database { /// <summary> /// The type of the database to use an appropriate SQL dialect. /// </summary> public enum DatabaseType { /// <summary> /// A generic dialect using ANSI SQL. This dialect may not work with every database. /// </summary> Generic, /// <summary> /// A dialect for Firebird. /// </summary> Firebird, /// <summary> /// A dialect for Microsoft SQL Server. (only generic support for now) /// </summary> MSSQLServer, /// <summary> /// A dialect for MySQL. (only generic support for now) /// </summary> MySQL, /// <summary> /// A dialect for Oracle. (only generic support for now) /// </summary> Oracle, /// <summary> /// A dialect for PostgreSQL. (only generic support for now) /// </summary> PostgreSQL, /// <summary> /// A dialect for SQLite. /// </summary> SQLite } }
23.708333
92
0.52812
[ "MIT" ]
spiegelp/Poco.Evolved
Poco.Evolved.SQL/Database/DatabaseType.cs
1,140
C#
using System; using System.Buffers; using System.IO; using Cursively.Inputs; namespace Cursively { /// <summary> /// Helpers to create inputs that describe CSV data streams synchronously. /// </summary> public static class CsvSyncInput { /// <summary> /// Creates an input that can describe the contents of a given <see cref="Stream"/> to an /// instance of <see cref="CsvReaderVisitorBase"/>, synchronously. /// </summary> /// <param name="csvStream"> /// The <see cref="Stream"/> that contains the CSV data. /// </param> /// <returns> /// An instance of <see cref="CsvSyncStreamInput"/> wrapping <paramref name="csvStream"/>. /// </returns> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="csvStream"/> is non-<see langword="null"/> and its /// <see cref="Stream.CanRead"/> is <see langword="false"/>. /// </exception> public static CsvSyncStreamInput ForStream(Stream csvStream) { csvStream = csvStream ?? Stream.Null; if (!csvStream.CanRead) { throw new ArgumentException("Stream does not support reading.", nameof(csvStream)); } return new CsvSyncStreamInput((byte)',', csvStream, 65536, ArrayPool<byte>.Shared, true); } /// <summary> /// Creates an input that can describe the contents of a given file to an instance of /// <see cref="CsvReaderVisitorBase"/>, synchronously using memory-mapping. /// </summary> /// <param name="csvFilePath"> /// <para> /// The path to the file that contains the CSV data. /// </para> /// <para> /// The only validation that Cursively does is <see cref="string.IsNullOrWhiteSpace"/>. /// </para> /// </param> /// <returns> /// An instance of <see cref="CsvMemoryMappedFileInput"/> wrapping /// <paramref name="csvFilePath"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="csvFilePath"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="csvFilePath"/> is non-<see langword="null"/>, but is either /// empty or whitespace-only. /// </exception> public static CsvMemoryMappedFileInput ForMemoryMappedFile(string csvFilePath) { if (csvFilePath is null) { throw new ArgumentNullException(nameof(csvFilePath)); } if (string.IsNullOrWhiteSpace(csvFilePath)) { throw new ArgumentException("Cannot be blank", nameof(csvFilePath)); } return new CsvMemoryMappedFileInput((byte)',', csvFilePath, true); } /// <summary> /// Creates an input that can describe the contents of a given /// <see cref="ReadOnlyMemory{T}"/> of bytes to an instance of /// <see cref="CsvReaderVisitorBase"/>, synchronously. /// </summary> /// <param name="memory"> /// The <see cref="ReadOnlyMemory{T}"/> of bytes that contains the CSV data. /// </param> /// <returns> /// An instance of <see cref="CsvReadOnlyMemoryInput"/> wrapping <paramref name="memory"/>. /// </returns> public static CsvReadOnlyMemoryInput ForMemory(ReadOnlyMemory<byte> memory) { return new CsvReadOnlyMemoryInput((byte)',', memory, true); } /// <summary> /// Creates an input that can describe the contents of a given /// <see cref="ReadOnlySequence{T}"/> of bytes to an instance of /// <see cref="CsvReaderVisitorBase"/>, synchronously. /// </summary> /// <param name="sequence"> /// The <see cref="ReadOnlySequence{T}"/> of bytes that contains the CSV data. /// </param> /// <returns> /// An instance of <see cref="CsvReadOnlySequenceInput"/> wrapping <paramref name="sequence"/>. /// </returns> public static CsvReadOnlySequenceInput ForSequence(ReadOnlySequence<byte> sequence) { return new CsvReadOnlySequenceInput((byte)',', sequence, true); } } }
39.881818
103
0.578527
[ "MIT" ]
airbreather/Cursively
src/Cursively/CsvSyncInput.cs
4,389
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; public class TodoContext : DbContext { public TodoContext (DbContextOptions<TodoContext> options) : base(options) { } public DbSet<TodoItem> TodoItem { get; set; } }
22.375
66
0.667598
[ "MIT" ]
TedLinTech/webapi
aspdotnetcore/TodoApi/Data/TodoContext.cs
358
C#
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; using System.Collections; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X500; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X500.Style; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix { public class PkixNameConstraintValidator { // TODO Implement X500Name and styles //private static readonly DerObjectIdentifier SerialNumberOid = Rfc4519Style.SerialNumber; private static readonly DerObjectIdentifier SerialNumberOid = new DerObjectIdentifier("2.5.4.5"); private ISet excludedSubtreesDN = new HashSet(); private ISet excludedSubtreesDNS = new HashSet(); private ISet excludedSubtreesEmail = new HashSet(); private ISet excludedSubtreesURI = new HashSet(); private ISet excludedSubtreesIP = new HashSet(); private ISet permittedSubtreesDN; private ISet permittedSubtreesDNS; private ISet permittedSubtreesEmail; private ISet permittedSubtreesURI; private ISet permittedSubtreesIP; public PkixNameConstraintValidator() { } private static bool WithinDNSubtree( Asn1Sequence dns, Asn1Sequence subtree) { if (subtree.Count < 1 || subtree.Count > dns.Count) return false; for (int j = 0; j < subtree.Count; ++j) { // both subtree and dns are a ASN.1 Name and the elements are a RDN Rdn subtreeRdn = Rdn.GetInstance(subtree[j]); Rdn dnsRdn = Rdn.GetInstance(dns[j]); // check if types and values of all naming attributes are matching, other types which are not restricted are allowed, see https://tools.ietf.org/html/rfc5280#section-7.1 // Two relative distinguished names // RDN1 and RDN2 match if they have the same number of naming attributes // and for each naming attribute in RDN1 there is a matching naming attribute in RDN2. // NOTE: this is checking the attributes in the same order, which might be not necessary, if this is a problem also IETFUtils.rDNAreEqual mus tbe changed. // use new RFC 5280 comparison, NOTE: this is now different from with RFC 3280, where only binary comparison is used // obey RFC 5280 7.1 // special treatment of serialNumber for GSMA SGP.22 RSP specification if (subtreeRdn.Count == 1 && dnsRdn.Count == 1 && subtreeRdn.GetFirst().GetType().Equals(SerialNumberOid) && dnsRdn.GetFirst().GetType().Equals(SerialNumberOid)) { if (!BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(dnsRdn.GetFirst().Value.ToString(), subtreeRdn.GetFirst().Value.ToString())) return false; } else if (!IetfUtilities.RdnAreEqual(subtreeRdn, dnsRdn)) { return false; } } return true; } public void CheckPermittedDN(Asn1Sequence dns) //throws PkixNameConstraintValidatorException { CheckPermittedDN(permittedSubtreesDN, dns); } public void CheckExcludedDN(Asn1Sequence dns) //throws PkixNameConstraintValidatorException { CheckExcludedDN(excludedSubtreesDN, dns); } private void CheckPermittedDN(ISet permitted, Asn1Sequence dns) //throws PkixNameConstraintValidatorException { if (permitted == null) { return; } if ((permitted.Count == 0) && dns.Count == 0) { return; } IEnumerator it = permitted.GetEnumerator(); while (it.MoveNext()) { Asn1Sequence subtree = (Asn1Sequence)it.Current; if (WithinDNSubtree(dns, subtree)) { return; } } throw new PkixNameConstraintValidatorException( "Subject distinguished name is not from a permitted subtree"); } private void CheckExcludedDN(ISet excluded, Asn1Sequence dns) //throws PkixNameConstraintValidatorException { if (excluded.IsEmpty) { return; } IEnumerator it = excluded.GetEnumerator(); while (it.MoveNext()) { Asn1Sequence subtree = (Asn1Sequence)it.Current; if (WithinDNSubtree(dns, subtree)) { throw new PkixNameConstraintValidatorException( "Subject distinguished name is from an excluded subtree"); } } } private ISet IntersectDN(ISet permitted, ISet dns) { ISet intersect = new HashSet(); for (IEnumerator it = dns.GetEnumerator(); it.MoveNext(); ) { Asn1Sequence dn = Asn1Sequence.GetInstance(((GeneralSubtree)it .Current).Base.Name.ToAsn1Object()); if (permitted == null) { if (dn != null) { intersect.Add(dn); } } else { IEnumerator _iter = permitted.GetEnumerator(); while (_iter.MoveNext()) { Asn1Sequence subtree = (Asn1Sequence)_iter.Current; if (WithinDNSubtree(dn, subtree)) { intersect.Add(dn); } else if (WithinDNSubtree(subtree, dn)) { intersect.Add(subtree); } } } } return intersect; } private ISet UnionDN(ISet excluded, Asn1Sequence dn) { if (excluded.IsEmpty) { if (dn == null) { return excluded; } excluded.Add(dn); return excluded; } else { ISet intersect = new HashSet(); IEnumerator it = excluded.GetEnumerator(); while (it.MoveNext()) { Asn1Sequence subtree = (Asn1Sequence)it.Current; if (WithinDNSubtree(dn, subtree)) { intersect.Add(subtree); } else if (WithinDNSubtree(subtree, dn)) { intersect.Add(dn); } else { intersect.Add(subtree); intersect.Add(dn); } } return intersect; } } private ISet IntersectEmail(ISet permitted, ISet emails) { ISet intersect = new HashSet(); for (IEnumerator it = emails.GetEnumerator(); it.MoveNext(); ) { string email = ExtractNameAsString(((GeneralSubtree)it.Current) .Base); if (permitted == null) { if (email != null) { intersect.Add(email); } } else { IEnumerator it2 = permitted.GetEnumerator(); while (it2.MoveNext()) { string _permitted = (string)it2.Current; intersectEmail(email, _permitted, intersect); } } } return intersect; } private ISet UnionEmail(ISet excluded, string email) { if (excluded.IsEmpty) { if (email == null) { return excluded; } excluded.Add(email); return excluded; } else { ISet union = new HashSet(); IEnumerator it = excluded.GetEnumerator(); while (it.MoveNext()) { string _excluded = (string)it.Current; UnionEmail(_excluded, email, union); } return union; } } /** * Returns the intersection of the permitted IP ranges in * <code>permitted</code> with <code>ip</code>. * * @param permitted A <code>Set</code> of permitted IP addresses with * their subnet mask as byte arrays. * @param ips The IP address with its subnet mask. * @return The <code>Set</code> of permitted IP ranges intersected with * <code>ip</code>. */ private ISet IntersectIP(ISet permitted, ISet ips) { ISet intersect = new HashSet(); for (IEnumerator it = ips.GetEnumerator(); it.MoveNext(); ) { byte[] ip = Asn1OctetString.GetInstance( ((GeneralSubtree)it.Current).Base.Name).GetOctets(); if (permitted == null) { if (ip != null) { intersect.Add(ip); } } else { IEnumerator it2 = permitted.GetEnumerator(); while (it2.MoveNext()) { byte[] _permitted = (byte[])it2.Current; intersect.AddAll(IntersectIPRange(_permitted, ip)); } } } return intersect; } /** * Returns the union of the excluded IP ranges in <code>excluded</code> * with <code>ip</code>. * * @param excluded A <code>Set</code> of excluded IP addresses with their * subnet mask as byte arrays. * @param ip The IP address with its subnet mask. * @return The <code>Set</code> of excluded IP ranges unified with * <code>ip</code> as byte arrays. */ private ISet UnionIP(ISet excluded, byte[] ip) { if (excluded.IsEmpty) { if (ip == null) { return excluded; } excluded.Add(ip); return excluded; } else { ISet union = new HashSet(); IEnumerator it = excluded.GetEnumerator(); while (it.MoveNext()) { byte[] _excluded = (byte[])it.Current; union.AddAll(UnionIPRange(_excluded, ip)); } return union; } } /** * Calculates the union if two IP ranges. * * @param ipWithSubmask1 The first IP address with its subnet mask. * @param ipWithSubmask2 The second IP address with its subnet mask. * @return A <code>Set</code> with the union of both addresses. */ private ISet UnionIPRange(byte[] ipWithSubmask1, byte[] ipWithSubmask2) { ISet set = new HashSet(); // difficult, adding always all IPs is not wrong if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Arrays.AreEqual(ipWithSubmask1, ipWithSubmask2)) { set.Add(ipWithSubmask1); } else { set.Add(ipWithSubmask1); set.Add(ipWithSubmask2); } return set; } /** * Calculates the interesction if two IP ranges. * * @param ipWithSubmask1 The first IP address with its subnet mask. * @param ipWithSubmask2 The second IP address with its subnet mask. * @return A <code>Set</code> with the single IP address with its subnet * mask as a byte array or an empty <code>Set</code>. */ private ISet IntersectIPRange(byte[] ipWithSubmask1, byte[] ipWithSubmask2) { if (ipWithSubmask1.Length != ipWithSubmask2.Length) { //Collections.EMPTY_SET; return new HashSet(); } byte[][] temp = ExtractIPsAndSubnetMasks(ipWithSubmask1, ipWithSubmask2); byte[] ip1 = temp[0]; byte[] subnetmask1 = temp[1]; byte[] ip2 = temp[2]; byte[] subnetmask2 = temp[3]; byte[][] minMax = MinMaxIPs(ip1, subnetmask1, ip2, subnetmask2); byte[] min; byte[] max; max = Min(minMax[1], minMax[3]); min = Max(minMax[0], minMax[2]); // minimum IP address must be bigger than max if (CompareTo(min, max) == 1) { //return Collections.EMPTY_SET; return new HashSet(); } // OR keeps all significant bits byte[] ip = Or(minMax[0], minMax[2]); byte[] subnetmask = Or(subnetmask1, subnetmask2); //return new HashSet( ICollectionsingleton(IpWithSubnetMask(ip, subnetmask)); ISet hs = new HashSet(); hs.Add(IpWithSubnetMask(ip, subnetmask)); return hs; } /** * Concatenates the IP address with its subnet mask. * * @param ip The IP address. * @param subnetMask Its subnet mask. * @return The concatenated IP address with its subnet mask. */ private byte[] IpWithSubnetMask(byte[] ip, byte[] subnetMask) { int ipLength = ip.Length; byte[] temp = new byte[ipLength * 2]; Array.Copy(ip, 0, temp, 0, ipLength); Array.Copy(subnetMask, 0, temp, ipLength, ipLength); return temp; } /** * Splits the IP addresses and their subnet mask. * * @param ipWithSubmask1 The first IP address with the subnet mask. * @param ipWithSubmask2 The second IP address with the subnet mask. * @return An array with two elements. Each element contains the IP address * and the subnet mask in this order. */ private byte[][] ExtractIPsAndSubnetMasks( byte[] ipWithSubmask1, byte[] ipWithSubmask2) { int ipLength = ipWithSubmask1.Length / 2; byte[] ip1 = new byte[ipLength]; byte[] subnetmask1 = new byte[ipLength]; Array.Copy(ipWithSubmask1, 0, ip1, 0, ipLength); Array.Copy(ipWithSubmask1, ipLength, subnetmask1, 0, ipLength); byte[] ip2 = new byte[ipLength]; byte[] subnetmask2 = new byte[ipLength]; Array.Copy(ipWithSubmask2, 0, ip2, 0, ipLength); Array.Copy(ipWithSubmask2, ipLength, subnetmask2, 0, ipLength); return new byte[][] {ip1, subnetmask1, ip2, subnetmask2}; } /** * Based on the two IP addresses and their subnet masks the IP range is * computed for each IP address - subnet mask pair and returned as the * minimum IP address and the maximum address of the range. * * @param ip1 The first IP address. * @param subnetmask1 The subnet mask of the first IP address. * @param ip2 The second IP address. * @param subnetmask2 The subnet mask of the second IP address. * @return A array with two elements. The first/second element contains the * min and max IP address of the first/second IP address and its * subnet mask. */ private byte[][] MinMaxIPs( byte[] ip1, byte[] subnetmask1, byte[] ip2, byte[] subnetmask2) { int ipLength = ip1.Length; byte[] min1 = new byte[ipLength]; byte[] max1 = new byte[ipLength]; byte[] min2 = new byte[ipLength]; byte[] max2 = new byte[ipLength]; for (int i = 0; i < ipLength; i++) { min1[i] = (byte)(ip1[i] & subnetmask1[i]); max1[i] = (byte)(ip1[i] & subnetmask1[i] | ~subnetmask1[i]); min2[i] = (byte)(ip2[i] & subnetmask2[i]); max2[i] = (byte)(ip2[i] & subnetmask2[i] | ~subnetmask2[i]); } return new byte[][] { min1, max1, min2, max2 }; } private void CheckPermittedEmail(ISet permitted, string email) //throws PkixNameConstraintValidatorException { if (permitted == null) { return; } IEnumerator it = permitted.GetEnumerator(); while (it.MoveNext()) { string str = ((string)it.Current); if (EmailIsConstrained(email, str)) { return; } } if (email.Length == 0 && permitted.Count == 0) { return; } throw new PkixNameConstraintValidatorException( "Subject email address is not from a permitted subtree."); } private void CheckExcludedEmail(ISet excluded, string email) //throws PkixNameConstraintValidatorException { if (excluded.IsEmpty) { return; } IEnumerator it = excluded.GetEnumerator(); while (it.MoveNext()) { string str = (string)it.Current; if (EmailIsConstrained(email, str)) { throw new PkixNameConstraintValidatorException( "Email address is from an excluded subtree."); } } } /** * Checks if the IP <code>ip</code> is included in the permitted ISet * <code>permitted</code>. * * @param permitted A <code>Set</code> of permitted IP addresses with * their subnet mask as byte arrays. * @param ip The IP address. * @throws PkixNameConstraintValidatorException * if the IP is not permitted. */ private void CheckPermittedIP(ISet permitted, byte[] ip) //throws PkixNameConstraintValidatorException { if (permitted == null) { return; } IEnumerator it = permitted.GetEnumerator(); while (it.MoveNext()) { byte[] ipWithSubnet = (byte[])it.Current; if (IsIPConstrained(ip, ipWithSubnet)) { return; } } if (ip.Length == 0 && permitted.Count == 0) { return; } throw new PkixNameConstraintValidatorException( "IP is not from a permitted subtree."); } /** * Checks if the IP <code>ip</code> is included in the excluded ISet * <code>excluded</code>. * * @param excluded A <code>Set</code> of excluded IP addresses with their * subnet mask as byte arrays. * @param ip The IP address. * @throws PkixNameConstraintValidatorException * if the IP is excluded. */ private void CheckExcludedIP(ISet excluded, byte[] ip) //throws PkixNameConstraintValidatorException { if (excluded.IsEmpty) { return; } IEnumerator it = excluded.GetEnumerator(); while (it.MoveNext()) { byte[] ipWithSubnet = (byte[])it.Current; if (IsIPConstrained(ip, ipWithSubnet)) { throw new PkixNameConstraintValidatorException( "IP is from an excluded subtree."); } } } /** * Checks if the IP address <code>ip</code> is constrained by * <code>constraint</code>. * * @param ip The IP address. * @param constraint The constraint. This is an IP address concatenated with * its subnetmask. * @return <code>true</code> if constrained, <code>false</code> * otherwise. */ private bool IsIPConstrained(byte[] ip, byte[] constraint) { int ipLength = ip.Length; if (ipLength != (constraint.Length / 2)) { return false; } byte[] subnetMask = new byte[ipLength]; Array.Copy(constraint, ipLength, subnetMask, 0, ipLength); byte[] permittedSubnetAddress = new byte[ipLength]; byte[] ipSubnetAddress = new byte[ipLength]; // the resulting IP address by applying the subnet mask for (int i = 0; i < ipLength; i++) { permittedSubnetAddress[i] = (byte)(constraint[i] & subnetMask[i]); ipSubnetAddress[i] = (byte)(ip[i] & subnetMask[i]); } return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Arrays.AreEqual(permittedSubnetAddress, ipSubnetAddress); } private bool EmailIsConstrained(string email, string constraint) { string sub = email.Substring(email.IndexOf('@') + 1); // a particular mailbox if (constraint.IndexOf('@') != -1) { if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(email).Equals(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(constraint))) { return true; } } // on particular host else if (!(constraint[0].Equals('.'))) { if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(sub).Equals(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(constraint))) { return true; } } // address in sub domain else if (WithinDomain(sub, constraint)) { return true; } return false; } private bool WithinDomain(string testDomain, string domain) { string tempDomain = domain; if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(tempDomain, ".")) { tempDomain = tempDomain.Substring(1); } string[] domainParts = tempDomain.Split('.'); // Strings.split(tempDomain, '.'); string[] testDomainParts = testDomain.Split('.'); // Strings.split(testDomain, '.'); // must have at least one subdomain if (testDomainParts.Length <= domainParts.Length) return false; int d = testDomainParts.Length - domainParts.Length; for (int i = -1; i < domainParts.Length; i++) { if (i == -1) { if (testDomainParts[i + d].Length < 1) { return false; } } else if (!BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(testDomainParts[i + d], domainParts[i])) { return false; } } return true; } private void CheckPermittedDns(ISet permitted, string dns) //throws PkixNameConstraintValidatorException { if (null == permitted) return; foreach (string str in permitted) { // is sub domain or the same if (WithinDomain(dns, str) || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(dns, str)) return; } if (dns.Length == 0 && permitted.Count == 0) return; throw new PkixNameConstraintValidatorException("DNS is not from a permitted subtree."); } private void CheckExcludedDns(ISet excluded, string dns) //throws PkixNameConstraintValidatorException { foreach (string str in excluded) { // is sub domain or the same if (WithinDomain(dns, str) || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(dns, str)) throw new PkixNameConstraintValidatorException("DNS is from an excluded subtree."); } } /** * The common part of <code>email1</code> and <code>email2</code> is * added to the union <code>union</code>. If <code>email1</code> and * <code>email2</code> have nothing in common they are added both. * * @param email1 Email address constraint 1. * @param email2 Email address constraint 2. * @param union The union. */ private void UnionEmail(string email1, string email2, ISet union) { // email1 is a particular address if (email1.IndexOf('@') != -1) { string _sub = email1.Substring(email1.IndexOf('@') + 1); // both are a particular mailbox if (email2.IndexOf('@') != -1) { if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } // email2 specifies a domain else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { if (WithinDomain(_sub, email2)) { union.Add(email2); } else { union.Add(email1); union.Add(email2); } } // email2 specifies a particular host else { if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email2)) { union.Add(email2); } else { union.Add(email1); union.Add(email2); } } } // email1 specifies a domain else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email1, ".")) { if (email2.IndexOf('@') != -1) { string _sub = email2.Substring(email1.IndexOf('@') + 1); if (WithinDomain(_sub, email1)) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } // email2 specifies a domain else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { if (WithinDomain(email1, email2) || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { union.Add(email2); } else if (WithinDomain(email2, email1)) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } else { if (WithinDomain(email2, email1)) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } } // email specifies a host else { if (email2.IndexOf('@') != -1) { string _sub = email2.Substring(email1.IndexOf('@') + 1); if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email1)) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } // email2 specifies a domain else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { if (WithinDomain(email1, email2)) { union.Add(email2); } else { union.Add(email1); union.Add(email2); } } // email2 specifies a particular host else { if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } } } private void unionURI(string email1, string email2, ISet union) { // email1 is a particular address if (email1.IndexOf('@') != -1) { string _sub = email1.Substring(email1.IndexOf('@') + 1); // both are a particular mailbox if (email2.IndexOf('@') != -1) { if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } // email2 specifies a domain else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { if (WithinDomain(_sub, email2)) { union.Add(email2); } else { union.Add(email1); union.Add(email2); } } // email2 specifies a particular host else { if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email2)) { union.Add(email2); } else { union.Add(email1); union.Add(email2); } } } // email1 specifies a domain else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email1, ".")) { if (email2.IndexOf('@') != -1) { string _sub = email2.Substring(email1.IndexOf('@') + 1); if (WithinDomain(_sub, email1)) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } // email2 specifies a domain else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { if (WithinDomain(email1, email2) || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { union.Add(email2); } else if (WithinDomain(email2, email1)) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } else { if (WithinDomain(email2, email1)) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } } // email specifies a host else { if (email2.IndexOf('@') != -1) { string _sub = email2.Substring(email1.IndexOf('@') + 1); if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email1)) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } // email2 specifies a domain else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { if (WithinDomain(email1, email2)) { union.Add(email2); } else { union.Add(email1); union.Add(email2); } } // email2 specifies a particular host else { if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { union.Add(email1); } else { union.Add(email1); union.Add(email2); } } } } private ISet intersectDNS(ISet permitted, ISet dnss) { ISet intersect = new HashSet(); for (IEnumerator it = dnss.GetEnumerator(); it.MoveNext(); ) { string dns = ExtractNameAsString(((GeneralSubtree)it.Current) .Base); if (permitted == null) { if (dns != null) { intersect.Add(dns); } } else { IEnumerator _iter = permitted.GetEnumerator(); while (_iter.MoveNext()) { string _permitted = (string)_iter.Current; if (WithinDomain(_permitted, dns)) { intersect.Add(_permitted); } else if (WithinDomain(dns, _permitted)) { intersect.Add(dns); } } } } return intersect; } protected ISet unionDNS(ISet excluded, string dns) { if (excluded.IsEmpty) { if (dns == null) { return excluded; } excluded.Add(dns); return excluded; } else { ISet union = new HashSet(); IEnumerator _iter = excluded.GetEnumerator(); while (_iter.MoveNext()) { string _permitted = (string)_iter.Current; if (WithinDomain(_permitted, dns)) { union.Add(dns); } else if (WithinDomain(dns, _permitted)) { union.Add(_permitted); } else { union.Add(_permitted); union.Add(dns); } } return union; } } /** * The most restricting part from <code>email1</code> and * <code>email2</code> is added to the intersection <code>intersect</code>. * * @param email1 Email address constraint 1. * @param email2 Email address constraint 2. * @param intersect The intersection. */ private void intersectEmail(string email1, string email2, ISet intersect) { // email1 is a particular address if (email1.IndexOf('@') != -1) { string _sub = email1.Substring(email1.IndexOf('@') + 1); // both are a particular mailbox if (email2.IndexOf('@') != -1) { if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { intersect.Add(email1); } } // email2 specifies a domain else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { if (WithinDomain(_sub, email2)) { intersect.Add(email1); } } // email2 specifies a particular host else { if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email2)) { intersect.Add(email1); } } } // email specifies a domain else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email1, ".")) { if (email2.IndexOf('@') != -1) { string _sub = email2.Substring(email1.IndexOf('@') + 1); if (WithinDomain(_sub, email1)) { intersect.Add(email2); } } // email2 specifies a domain else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { if (WithinDomain(email1, email2) || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { intersect.Add(email1); } else if (WithinDomain(email2, email1)) { intersect.Add(email2); } } else { if (WithinDomain(email2, email1)) { intersect.Add(email2); } } } // email1 specifies a host else { if (email2.IndexOf('@') != -1) { string _sub = email2.Substring(email2.IndexOf('@') + 1); if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email1)) { intersect.Add(email2); } } // email2 specifies a domain else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { if (WithinDomain(email1, email2)) { intersect.Add(email1); } } // email2 specifies a particular host else { if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { intersect.Add(email1); } } } } private void checkExcludedURI(ISet excluded, string uri) // throws PkixNameConstraintValidatorException { if (excluded.IsEmpty) { return; } IEnumerator it = excluded.GetEnumerator(); while (it.MoveNext()) { string str = ((string)it.Current); if (IsUriConstrained(uri, str)) { throw new PkixNameConstraintValidatorException( "URI is from an excluded subtree."); } } } private ISet intersectURI(ISet permitted, ISet uris) { ISet intersect = new HashSet(); for (IEnumerator it = uris.GetEnumerator(); it.MoveNext(); ) { string uri = ExtractNameAsString(((GeneralSubtree)it.Current) .Base); if (permitted == null) { if (uri != null) { intersect.Add(uri); } } else { IEnumerator _iter = permitted.GetEnumerator(); while (_iter.MoveNext()) { string _permitted = (string)_iter.Current; intersectURI(_permitted, uri, intersect); } } } return intersect; } private ISet unionURI(ISet excluded, string uri) { if (excluded.IsEmpty) { if (uri == null) { return excluded; } excluded.Add(uri); return excluded; } else { ISet union = new HashSet(); IEnumerator _iter = excluded.GetEnumerator(); while (_iter.MoveNext()) { string _excluded = (string)_iter.Current; unionURI(_excluded, uri, union); } return union; } } private void intersectURI(string email1, string email2, ISet intersect) { // email1 is a particular address if (email1.IndexOf('@') != -1) { string _sub = email1.Substring(email1.IndexOf('@') + 1); // both are a particular mailbox if (email2.IndexOf('@') != -1) { if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { intersect.Add(email1); } } // email2 specifies a domain else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { if (WithinDomain(_sub, email2)) { intersect.Add(email1); } } // email2 specifies a particular host else { if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email2)) { intersect.Add(email1); } } } // email specifies a domain else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email1, ".")) { if (email2.IndexOf('@') != -1) { string _sub = email2.Substring(email1.IndexOf('@') + 1); if (WithinDomain(_sub, email1)) { intersect.Add(email2); } } // email2 specifies a domain else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { if (WithinDomain(email1, email2) || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { intersect.Add(email1); } else if (WithinDomain(email2, email1)) { intersect.Add(email2); } } else { if (WithinDomain(email2, email1)) { intersect.Add(email2); } } } // email1 specifies a host else { if (email2.IndexOf('@') != -1) { string _sub = email2.Substring(email2.IndexOf('@') + 1); if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email1)) { intersect.Add(email2); } } // email2 specifies a domain else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { if (WithinDomain(email1, email2)) { intersect.Add(email1); } } // email2 specifies a particular host else { if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { intersect.Add(email1); } } } } private void CheckPermittedURI(ISet permitted, string uri) // throws PkixNameConstraintValidatorException { if (permitted == null) { return; } IEnumerator it = permitted.GetEnumerator(); while (it.MoveNext()) { string str = ((string)it.Current); if (IsUriConstrained(uri, str)) { return; } } if (uri.Length == 0 && permitted.Count == 0) { return; } throw new PkixNameConstraintValidatorException( "URI is not from a permitted subtree."); } private bool IsUriConstrained(string uri, string constraint) { string host = ExtractHostFromURL(uri); // a host if (!BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(constraint, ".")) { if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(host, constraint)) { return true; } } // in sub domain or domain else if (WithinDomain(host, constraint)) { return true; } return false; } private static string ExtractHostFromURL(string url) { // see RFC 1738 // remove ':' after protocol, e.g. http: string sub = url.Substring(url.IndexOf(':') + 1); // extract host from Common Internet Scheme Syntax, e.g. http:// int idxOfSlashes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.IndexOf(sub, "//"); if (idxOfSlashes != -1) { sub = sub.Substring(idxOfSlashes + 2); } // first remove port, e.g. http://test.com:21 if (sub.LastIndexOf(':') != -1) { sub = sub.Substring(0, sub.LastIndexOf(':')); } // remove user and password, e.g. http://john:password@test.com sub = sub.Substring(sub.IndexOf(':') + 1); sub = sub.Substring(sub.IndexOf('@') + 1); // remove local parts, e.g. http://test.com/bla if (sub.IndexOf('/') != -1) { sub = sub.Substring(0, sub.IndexOf('/')); } return sub; } /** * Checks if the given GeneralName is in the permitted ISet. * * @param name The GeneralName * @throws PkixNameConstraintValidatorException * If the <code>name</code> */ public void checkPermitted(GeneralName name) // throws PkixNameConstraintValidatorException { switch (name.TagNo) { case 1: CheckPermittedEmail(permittedSubtreesEmail, ExtractNameAsString(name)); break; case 2: CheckPermittedDns(permittedSubtreesDNS, DerIA5String.GetInstance( name.Name).GetString()); break; case 4: CheckPermittedDN(Asn1Sequence.GetInstance(name.Name.ToAsn1Object())); break; case 6: CheckPermittedURI(permittedSubtreesURI, DerIA5String.GetInstance( name.Name).GetString()); break; case 7: byte[] ip = Asn1OctetString.GetInstance(name.Name).GetOctets(); CheckPermittedIP(permittedSubtreesIP, ip); break; } } /** * Check if the given GeneralName is contained in the excluded ISet. * * @param name The GeneralName. * @throws PkixNameConstraintValidatorException * If the <code>name</code> is * excluded. */ public void checkExcluded(GeneralName name) // throws PkixNameConstraintValidatorException { switch (name.TagNo) { case 1: CheckExcludedEmail(excludedSubtreesEmail, ExtractNameAsString(name)); break; case 2: CheckExcludedDns(excludedSubtreesDNS, DerIA5String.GetInstance( name.Name).GetString()); break; case 4: CheckExcludedDN(Asn1Sequence.GetInstance(name.Name.ToAsn1Object())); break; case 6: checkExcludedURI(excludedSubtreesURI, DerIA5String.GetInstance( name.Name).GetString()); break; case 7: byte[] ip = Asn1OctetString.GetInstance(name.Name).GetOctets(); CheckExcludedIP(excludedSubtreesIP, ip); break; } } /** * Updates the permitted ISet of these name constraints with the intersection * with the given subtree. * * @param permitted The permitted subtrees */ public void IntersectPermittedSubtree(Asn1Sequence permitted) { IDictionary subtreesMap = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); // group in ISets in a map ordered by tag no. for (IEnumerator e = permitted.GetEnumerator(); e.MoveNext(); ) { GeneralSubtree subtree = GeneralSubtree.GetInstance(e.Current); int tagNo = subtree.Base.TagNo; if (subtreesMap[tagNo] == null) { subtreesMap[tagNo] = new HashSet(); } ((ISet)subtreesMap[tagNo]).Add(subtree); } for (IEnumerator it = subtreesMap.GetEnumerator(); it.MoveNext(); ) { DictionaryEntry entry = (DictionaryEntry)it.Current; // go through all subtree groups switch ((int)entry.Key ) { case 1: permittedSubtreesEmail = IntersectEmail(permittedSubtreesEmail, (ISet)entry.Value); break; case 2: permittedSubtreesDNS = intersectDNS(permittedSubtreesDNS, (ISet)entry.Value); break; case 4: permittedSubtreesDN = IntersectDN(permittedSubtreesDN, (ISet)entry.Value); break; case 6: permittedSubtreesURI = intersectURI(permittedSubtreesURI, (ISet)entry.Value); break; case 7: permittedSubtreesIP = IntersectIP(permittedSubtreesIP, (ISet)entry.Value); break; } } } private string ExtractNameAsString(GeneralName name) { return DerIA5String.GetInstance(name.Name).GetString(); } public void IntersectEmptyPermittedSubtree(int nameType) { switch (nameType) { case 1: permittedSubtreesEmail = new HashSet(); break; case 2: permittedSubtreesDNS = new HashSet(); break; case 4: permittedSubtreesDN = new HashSet(); break; case 6: permittedSubtreesURI = new HashSet(); break; case 7: permittedSubtreesIP = new HashSet(); break; } } /** * Adds a subtree to the excluded ISet of these name constraints. * * @param subtree A subtree with an excluded GeneralName. */ public void AddExcludedSubtree(GeneralSubtree subtree) { GeneralName subTreeBase = subtree.Base; switch (subTreeBase.TagNo) { case 1: excludedSubtreesEmail = UnionEmail(excludedSubtreesEmail, ExtractNameAsString(subTreeBase)); break; case 2: excludedSubtreesDNS = unionDNS(excludedSubtreesDNS, ExtractNameAsString(subTreeBase)); break; case 4: excludedSubtreesDN = UnionDN(excludedSubtreesDN, (Asn1Sequence)subTreeBase.Name.ToAsn1Object()); break; case 6: excludedSubtreesURI = unionURI(excludedSubtreesURI, ExtractNameAsString(subTreeBase)); break; case 7: excludedSubtreesIP = UnionIP(excludedSubtreesIP, Asn1OctetString .GetInstance(subTreeBase.Name).GetOctets()); break; } } /** * Returns the maximum IP address. * * @param ip1 The first IP address. * @param ip2 The second IP address. * @return The maximum IP address. */ private static byte[] Max(byte[] ip1, byte[] ip2) { for (int i = 0; i < ip1.Length; i++) { if ((ip1[i] & 0xFFFF) > (ip2[i] & 0xFFFF)) { return ip1; } } return ip2; } /** * Returns the minimum IP address. * * @param ip1 The first IP address. * @param ip2 The second IP address. * @return The minimum IP address. */ private static byte[] Min(byte[] ip1, byte[] ip2) { for (int i = 0; i < ip1.Length; i++) { if ((ip1[i] & 0xFFFF) < (ip2[i] & 0xFFFF)) { return ip1; } } return ip2; } /** * Compares IP address <code>ip1</code> with <code>ip2</code>. If ip1 * is equal to ip2 0 is returned. If ip1 is bigger 1 is returned, -1 * otherwise. * * @param ip1 The first IP address. * @param ip2 The second IP address. * @return 0 if ip1 is equal to ip2, 1 if ip1 is bigger, -1 otherwise. */ private static int CompareTo(byte[] ip1, byte[] ip2) { if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Arrays.AreEqual(ip1, ip2)) { return 0; } if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Arrays.AreEqual(Max(ip1, ip2), ip1)) { return 1; } return -1; } /** * Returns the logical OR of the IP addresses <code>ip1</code> and * <code>ip2</code>. * * @param ip1 The first IP address. * @param ip2 The second IP address. * @return The OR of <code>ip1</code> and <code>ip2</code>. */ private static byte[] Or(byte[] ip1, byte[] ip2) { byte[] temp = new byte[ip1.Length]; for (int i = 0; i < ip1.Length; i++) { temp[i] = (byte)(ip1[i] | ip2[i]); } return temp; } [Obsolete("Use GetHashCode instead")] public int HashCode() { return GetHashCode(); } public override int GetHashCode() { return HashCollection(excludedSubtreesDN) + HashCollection(excludedSubtreesDNS) + HashCollection(excludedSubtreesEmail) + HashCollection(excludedSubtreesIP) + HashCollection(excludedSubtreesURI) + HashCollection(permittedSubtreesDN) + HashCollection(permittedSubtreesDNS) + HashCollection(permittedSubtreesEmail) + HashCollection(permittedSubtreesIP) + HashCollection(permittedSubtreesURI); } private int HashCollection(ICollection coll) { if (coll == null) { return 0; } int hash = 0; IEnumerator it1 = coll.GetEnumerator(); while (it1.MoveNext()) { Object o = it1.Current; if (o is byte[]) { hash += BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Arrays.GetHashCode((byte[])o); } else { hash += o.GetHashCode(); } } return hash; } public override bool Equals(Object o) { if (!(o is PkixNameConstraintValidator)) return false; PkixNameConstraintValidator constraintValidator = (PkixNameConstraintValidator)o; return CollectionsAreEqual(constraintValidator.excludedSubtreesDN, excludedSubtreesDN) && CollectionsAreEqual(constraintValidator.excludedSubtreesDNS, excludedSubtreesDNS) && CollectionsAreEqual(constraintValidator.excludedSubtreesEmail, excludedSubtreesEmail) && CollectionsAreEqual(constraintValidator.excludedSubtreesIP, excludedSubtreesIP) && CollectionsAreEqual(constraintValidator.excludedSubtreesURI, excludedSubtreesURI) && CollectionsAreEqual(constraintValidator.permittedSubtreesDN, permittedSubtreesDN) && CollectionsAreEqual(constraintValidator.permittedSubtreesDNS, permittedSubtreesDNS) && CollectionsAreEqual(constraintValidator.permittedSubtreesEmail, permittedSubtreesEmail) && CollectionsAreEqual(constraintValidator.permittedSubtreesIP, permittedSubtreesIP) && CollectionsAreEqual(constraintValidator.permittedSubtreesURI, permittedSubtreesURI); } private bool CollectionsAreEqual(ICollection coll1, ICollection coll2) { if (coll1 == coll2) { return true; } if (coll1 == null || coll2 == null) { return false; } if (coll1.Count != coll2.Count) { return false; } IEnumerator it1 = coll1.GetEnumerator(); while (it1.MoveNext()) { Object a = it1.Current; IEnumerator it2 = coll2.GetEnumerator(); bool found = false; while (it2.MoveNext()) { Object b = it2.Current; if (SpecialEquals(a, b)) { found = true; break; } } if (!found) { return false; } } return true; } private bool SpecialEquals(Object o1, Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } if ((o1 is byte[]) && (o2 is byte[])) { return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Arrays.AreEqual((byte[])o1, (byte[])o2); } else { return o1.Equals(o2); } } /** * Stringifies an IPv4 or v6 address with subnet mask. * * @param ip The IP with subnet mask. * @return The stringified IP address. */ private string StringifyIP(byte[] ip) { string temp = ""; for (int i = 0; i < ip.Length / 2; i++) { //temp += Integer.toString(ip[i] & 0x00FF) + "."; temp += (ip[i] & 0x00FF) + "."; } temp = temp.Substring(0, temp.Length - 1); temp += "/"; for (int i = ip.Length / 2; i < ip.Length; i++) { //temp += Integer.toString(ip[i] & 0x00FF) + "."; temp += (ip[i] & 0x00FF) + "."; } temp = temp.Substring(0, temp.Length - 1); return temp; } private string StringifyIPCollection(ISet ips) { string temp = ""; temp += "["; for (IEnumerator it = ips.GetEnumerator(); it.MoveNext(); ) { temp += StringifyIP((byte[])it.Current) + ","; } if (temp.Length > 1) { temp = temp.Substring(0, temp.Length - 1); } temp += "]"; return temp; } public override string ToString() { string temp = ""; temp += "permitted:\n"; if (permittedSubtreesDN != null) { temp += "DN:\n"; temp += permittedSubtreesDN.ToString() + "\n"; } if (permittedSubtreesDNS != null) { temp += "DNS:\n"; temp += permittedSubtreesDNS.ToString() + "\n"; } if (permittedSubtreesEmail != null) { temp += "Email:\n"; temp += permittedSubtreesEmail.ToString() + "\n"; } if (permittedSubtreesURI != null) { temp += "URI:\n"; temp += permittedSubtreesURI.ToString() + "\n"; } if (permittedSubtreesIP != null) { temp += "IP:\n"; temp += StringifyIPCollection(permittedSubtreesIP) + "\n"; } temp += "excluded:\n"; if (!(excludedSubtreesDN.IsEmpty)) { temp += "DN:\n"; temp += excludedSubtreesDN.ToString() + "\n"; } if (!excludedSubtreesDNS.IsEmpty) { temp += "DNS:\n"; temp += excludedSubtreesDNS.ToString() + "\n"; } if (!excludedSubtreesEmail.IsEmpty) { temp += "Email:\n"; temp += excludedSubtreesEmail.ToString() + "\n"; } if (!excludedSubtreesURI.IsEmpty) { temp += "URI:\n"; temp += excludedSubtreesURI.ToString() + "\n"; } if (!excludedSubtreesIP.IsEmpty) { temp += "IP:\n"; temp += StringifyIPCollection(excludedSubtreesIP) + "\n"; } return temp; } } } #pragma warning restore #endif
35.81701
202
0.442196
[ "MIT" ]
jakemoves/cohort-unity-client
Assets/Best HTTP (Pro)/BestHTTP/SecureProtocol/pkix/PkixNameConstraintValidator.cs
69,485
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using Renci.SshNet.Common; using Renci.SshNet.Tests.Common; using Renci.SshNet.Tests.Properties; using System; using System.Diagnostics; using System.Linq; namespace Renci.SshNet.Tests.Classes { /// <summary> /// Implementation of the SSH File Transfer Protocol (SFTP) over SSH. /// </summary> public partial class SftpClientTest : TestBase { [TestMethod] [TestCategory("Sftp")] [ExpectedException(typeof(SshConnectionException))] public void Test_Sftp_ListDirectory_Without_Connecting() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { var files = sftp.ListDirectory("."); foreach (var file in files) { Debug.WriteLine(file.FullName); } } } [TestMethod] [TestCategory("Sftp")] [TestCategory("integration")] [ExpectedException(typeof(SftpPermissionDeniedException))] public void Test_Sftp_ListDirectory_Permission_Denied() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); var files = sftp.ListDirectory("/root"); foreach (var file in files) { Debug.WriteLine(file.FullName); } sftp.Disconnect(); } } [TestMethod] [TestCategory("Sftp")] [TestCategory("integration")] [ExpectedException(typeof(SftpPathNotFoundException))] public void Test_Sftp_ListDirectory_Not_Exists() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); var files = sftp.ListDirectory("/asdfgh"); foreach (var file in files) { Debug.WriteLine(file.FullName); } sftp.Disconnect(); } } [TestMethod] [TestCategory("Sftp")] [TestCategory("integration")] public void Test_Sftp_ListDirectory_Current() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); var files = sftp.ListDirectory("."); Assert.IsTrue(files.Count() > 0); foreach (var file in files) { Debug.WriteLine(file.FullName); } sftp.Disconnect(); } } [TestMethod] [TestCategory("Sftp")] [TestCategory("integration")] public void Test_Sftp_ListDirectory_Empty() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); var files = sftp.ListDirectory(string.Empty); Assert.IsTrue(files.Count() > 0); foreach (var file in files) { Debug.WriteLine(file.FullName); } sftp.Disconnect(); } } [TestMethod] [TestCategory("Sftp")] [TestCategory("integration")] [Description("Test passing null to ListDirectory.")] [ExpectedException(typeof(ArgumentNullException))] public void Test_Sftp_ListDirectory_Null() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); var files = sftp.ListDirectory(null); Assert.IsTrue(files.Count() > 0); foreach (var file in files) { Debug.WriteLine(file.FullName); } sftp.Disconnect(); } } [TestMethod] [TestCategory("Sftp")] [TestCategory("integration")] public void Test_Sftp_ListDirectory_HugeDirectory() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); // Create 10000 directory items for (int i = 0; i < 10000; i++) { sftp.CreateDirectory(string.Format("test_{0}", i)); Debug.WriteLine("Created " + i); } var files = sftp.ListDirectory("."); // Ensure that directory has at least 10000 items Assert.IsTrue(files.Count() > 10000); sftp.Disconnect(); } RemoveAllFiles(); } [TestMethod] [TestCategory("Sftp")] [TestCategory("integration")] public void Test_Sftp_Change_Directory() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); Assert.AreEqual(sftp.WorkingDirectory, "/home/tester"); sftp.CreateDirectory("test1"); sftp.ChangeDirectory("test1"); Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1"); sftp.CreateDirectory("test1_1"); sftp.CreateDirectory("test1_2"); sftp.CreateDirectory("test1_3"); var files = sftp.ListDirectory("."); Assert.IsTrue(files.First().FullName.StartsWith(string.Format("{0}", sftp.WorkingDirectory))); sftp.ChangeDirectory("test1_1"); Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_1"); sftp.ChangeDirectory("../test1_2"); Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_2"); sftp.ChangeDirectory(".."); Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1"); sftp.ChangeDirectory(".."); Assert.AreEqual(sftp.WorkingDirectory, "/home/tester"); files = sftp.ListDirectory("test1/test1_1"); Assert.IsTrue(files.First().FullName.StartsWith(string.Format("{0}/test1/test1_1", sftp.WorkingDirectory))); sftp.ChangeDirectory("test1/test1_1"); Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_1"); sftp.ChangeDirectory("/home/tester/test1/test1_1"); Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_1"); sftp.ChangeDirectory("/home/tester/test1/test1_1/../test1_2"); Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_2"); sftp.ChangeDirectory("../../"); sftp.DeleteDirectory("test1/test1_1"); sftp.DeleteDirectory("test1/test1_2"); sftp.DeleteDirectory("test1/test1_3"); sftp.DeleteDirectory("test1"); sftp.Disconnect(); } RemoveAllFiles(); } [TestMethod] [TestCategory("Sftp")] [TestCategory("integration")] [Description("Test passing null to ChangeDirectory.")] [ExpectedException(typeof(ArgumentNullException))] public void Test_Sftp_ChangeDirectory_Null() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); sftp.ChangeDirectory(null); sftp.Disconnect(); } } [TestMethod] [TestCategory("Sftp")] [TestCategory("integration")] [Description("Test calling EndListDirectory method more then once.")] [ExpectedException(typeof(ArgumentException))] public void Test_Sftp_Call_EndListDirectory_Twice() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); var ar = sftp.BeginListDirectory("/", null, null); var result = sftp.EndListDirectory(ar); var result1 = sftp.EndListDirectory(ar); } } } }
31.639405
124
0.538127
[ "MIT" ]
Foreveryone-cz/SSH.NET-for-winsshfs
src/Renci.SshNet.Tests/Classes/SftpClientTest.ListDirectory.cs
8,513
C#
using System; namespace TorchSharp.JIT { public sealed class DynamicType : Type { internal DynamicType(IntPtr handle) : base(handle) { this.handle = new HType(handle, true); } } }
17.692308
58
0.582609
[ "MIT" ]
ganik/TorchSharp
TorchSharp/JIT/Type/DynamicType .cs
232
C#
using System.Collections.Generic; using System.Threading.Tasks; using SmartHome.DomainCore.Data.Models; namespace SmartHome.DomainCore.ServiceInterfaces.Role { public interface IGetRolesService { Task<IList<RoleModel>> GetAllRolesAsync(); Task<RoleModel> GetRoleByIdAsync(long roleId); Task<RoleModel> GetRoleByNameAsync(string name); Task<IList<RoleModel>> GetUserRolesAsync(long userId); } }
25.941176
62
0.741497
[ "MIT" ]
JanPalasek/smart-home-server
SmartHome.DomainCore/ServiceInterfaces/Role/IGetRolesService.cs
441
C#
using PagarMe.Models.Enums; using PagarMe.Utils; using Newtonsoft.Json; using Xunit; namespace PagarMe.Tests.Util { public class JsonSerializerUtilTest { [Fact] public void Should_Parse_Json_To_SnakeCase() { // Arrange JsonSerializerSettings settings = JsonSerializerUtil.SnakeCaseSettings; var obj = new JsonSerializerUtilTestClass() { Name = "test", Age = 18, CustomerType = CustomerTypeEnum.Individual }; // Act var jsonAsString = JsonConvert.SerializeObject(obj, settings); // Assert var expected = "{\n \"name\": \"test\",\n \"age\": 18,\n \"customer_type\": \"individual\"\n}"; Assert.Equal(expected.Replace("\r", ""), jsonAsString.Replace("\r", "")); } } public class JsonSerializerUtilTestClass { public string Email { get; set; } public string Name { get; set; } public int Age { get; set; } public CustomerTypeEnum CustomerType { get; set; } } }
26.738095
110
0.560997
[ "MIT" ]
GabrielDeveloper/pagarme-dotnet
PagarMe.Tests/Util/JsonSerializerUtilTest.cs
1,125
C#
using System; using System.Collections.Generic; using System.Text; namespace FakeRpc.Core.Discovery.Consul { public class ConsulServiceDiscoveryOptions { public string BaseUrl{ get; set; } public bool UseHttps { get; set; } = true; } }
20.461538
50
0.68797
[ "MIT" ]
Regularly-Archive/2021
src/FakeRPC/FakeRPC.Core/FakeRPC.Core/Discovery/Consul/ConsulServiceDiscoveryOptions.cs
268
C#
using System.Drawing; using System.Globalization; using System.Text; namespace ApiReviewDotNet.Data; public sealed class ApiReviewLabel { public ApiReviewLabel(string name, string color, string description) { Name = name; Color = color; Description = description; } public string Name { get; } public string Color { get; } public string Description { get; } public string GetStyle() { var color = ParseColor(Color); var labelR = color.R; var labelG = color.G; var labelB = color.B; var labelH = color.GetHue(); var labelS = color.GetSaturation() * 100; var labelL = color.GetBrightness() * 100; var sb = new StringBuilder(); sb.Append($"--label-r: {labelR};"); sb.Append($"--label-g: {labelG};"); sb.Append($"--label-b: {labelB};"); sb.Append($"--label-h: {labelH};"); sb.Append($"--label-s: {labelS};"); sb.Append($"--label-l: {labelL};"); return sb.ToString(); } private static Color ParseColor(string color) { if (!string.IsNullOrEmpty(color) && color.Length == 6 && int.TryParse(color.AsSpan(0, 2), NumberStyles.HexNumber, null, out var r) && int.TryParse(color.AsSpan(2, 2), NumberStyles.HexNumber, null, out var g) && int.TryParse(color.AsSpan(4, 2), NumberStyles.HexNumber, null, out var b)) { return System.Drawing.Color.FromArgb(r, g, b); } return System.Drawing.Color.Black; } }
30
88
0.56358
[ "MIT" ]
terrajobst/apireview.net
src/ApiReviewDotNet/Data/ApiReviewLabel.cs
1,622
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime; using System.Text; using System.Reflection.Runtime.General; using Internal.Runtime.Augments; using Internal.Runtime.CompilerServices; using Internal.Metadata.NativeFormat; using Internal.NativeFormat; using Internal.TypeSystem; using Internal.TypeSystem.NativeFormat; using Internal.TypeSystem.NoMetadata; namespace Internal.Runtime.TypeLoader { using DynamicGenericsRegistrationData = TypeLoaderEnvironment.DynamicGenericsRegistrationData; using GenericTypeEntry = TypeLoaderEnvironment.GenericTypeEntry; using TypeEntryToRegister = TypeLoaderEnvironment.TypeEntryToRegister; using GenericMethodEntry = TypeLoaderEnvironment.GenericMethodEntry; using HandleBasedGenericTypeLookup = TypeLoaderEnvironment.HandleBasedGenericTypeLookup; using DefTypeBasedGenericTypeLookup = TypeLoaderEnvironment.DefTypeBasedGenericTypeLookup; using HandleBasedGenericMethodLookup = TypeLoaderEnvironment.HandleBasedGenericMethodLookup; using MethodDescBasedGenericMethodLookup = TypeLoaderEnvironment.MethodDescBasedGenericMethodLookup; using ThunkKind = CallConverterThunk.ThunkKind; using VTableSlotMapper = TypeBuilderState.VTableSlotMapper; internal static class LowLevelListExtensions { public static void Expand<T>(this LowLevelList<T> list, int count) { if (list.Capacity < count) list.Capacity = count; while (list.Count < count) list.Add(default(T)); } public static bool HasSetBits(this LowLevelList<bool> list) { for (int index = 0; index < list.Count; index++) { if (list[index]) return true; } return false; } } [Flags] internal enum FieldLoadState { None = 0, Instance = 1, Statics = 2, } public static class TypeBuilderApi { public static void ResolveMultipleCells(GenericDictionaryCell [] cells, out IntPtr[] fixups) { TypeBuilder.ResolveMultipleCells(cells, out fixups); } } internal class TypeBuilder { public TypeBuilder() { TypeLoaderEnvironment.Instance.VerifyTypeLoaderLockHeld(); } private const int MinimumValueTypeSize = 0x1; /// <summary> /// The StaticClassConstructionContext for a type is encoded in the negative space /// of the NonGCStatic fields of a type. /// </summary> public static unsafe readonly int ClassConstructorOffset = -sizeof(System.Runtime.CompilerServices.StaticClassConstructionContext); private LowLevelList<TypeDesc> _typesThatNeedTypeHandles = new LowLevelList<TypeDesc>(); private LowLevelList<InstantiatedMethod> _methodsThatNeedDictionaries = new LowLevelList<InstantiatedMethod>(); private LowLevelList<TypeDesc> _typesThatNeedPreparation; private object _epoch = new object(); #if DEBUG private bool _finalTypeBuilding; #endif // Helper exception to abort type building if we do not find the generic type template internal class MissingTemplateException : Exception { } private static bool CheckAllHandlesValidForMethod(MethodDesc method) { if (!method.OwningType.RetrieveRuntimeTypeHandleIfPossible()) return false; for (int i = 0; i < method.Instantiation.Length; i++) if (!method.Instantiation[i].RetrieveRuntimeTypeHandleIfPossible()) return false; return true; } internal static bool RetrieveExactFunctionPointerIfPossible(MethodDesc method, out IntPtr result) { result = IntPtr.Zero; if (!method.IsNonSharableMethod || !CheckAllHandlesValidForMethod(method)) return false; RuntimeTypeHandle[] genMethodArgs = method.Instantiation.Length > 0 ? new RuntimeTypeHandle[method.Instantiation.Length] : Empty<RuntimeTypeHandle>.Array; for (int i = 0; i < method.Instantiation.Length; i++) genMethodArgs[i] = method.Instantiation[i].RuntimeTypeHandle; return TypeLoaderEnvironment.Instance.TryLookupExactMethodPointerForComponents(method.OwningType.RuntimeTypeHandle, method.NameAndSignature, genMethodArgs, out result); } internal static bool RetrieveMethodDictionaryIfPossible(InstantiatedMethod method) { if (method.RuntimeMethodDictionary != IntPtr.Zero) return true; bool allHandlesValid = CheckAllHandlesValidForMethod(method); TypeLoaderLogger.WriteLine("Looking for method dictionary for method " + method.ToString() + " ... " + (allHandlesValid ? "(All type arg handles valid)" : "")); IntPtr methodDictionary; if ((allHandlesValid && TypeLoaderEnvironment.Instance.TryLookupGenericMethodDictionaryForComponents(new HandleBasedGenericMethodLookup(method), out methodDictionary)) || (!allHandlesValid && TypeLoaderEnvironment.Instance.TryLookupGenericMethodDictionaryForComponents(new MethodDescBasedGenericMethodLookup(method), out methodDictionary))) { TypeLoaderLogger.WriteLine("Found DICT = " + methodDictionary.LowLevelToString() + " for method " + method.ToString()); method.AssociateWithRuntimeMethodDictionary(methodDictionary); return true; } return false; } /// <summary> /// Register the type for preparation. The preparation will be done once the current type is prepared. /// This is the prefered way to get a dependent type prepared because of it avoids issues with cycles and recursion. /// </summary> public void RegisterForPreparation(TypeDesc type) { TypeLoaderLogger.WriteLine("Register for preparation " + type.ToString() + " ..."); // If this type has type handle, do nothing and return if (type.RetrieveRuntimeTypeHandleIfPossible()) return; var state = type.GetOrCreateTypeBuilderState(); // If this type was already inspected, do nothing and return. if (state.NeedsTypeHandle) return; state.NeedsTypeHandle = true; if (type.IsCanonicalSubtype(CanonicalFormKind.Any)) return; if (_typesThatNeedPreparation == null) _typesThatNeedPreparation = new LowLevelList<TypeDesc>(); _typesThatNeedPreparation.Add(type); } /// <summary> /// Collects all dependencies that need to be created in order to create /// the method that was passed in. /// </summary> public void PrepareMethod(MethodDesc method) { TypeLoaderLogger.WriteLine("Preparing method " + method.ToString() + " ..."); RegisterForPreparation(method.OwningType); if (method.Instantiation.Length == 0) return; InstantiatedMethod genericMethod = (InstantiatedMethod)method; if (RetrieveMethodDictionaryIfPossible(genericMethod)) return; // If this method was already inspected, do nothing and return if (genericMethod.NeedsDictionary) return; genericMethod.NeedsDictionary = true; if (genericMethod.IsCanonicalMethod(CanonicalFormKind.Any)) return; _methodsThatNeedDictionaries.Add(genericMethod); foreach (var type in genericMethod.Instantiation) RegisterForPreparation(type); ParseNativeLayoutInfo(genericMethod); } private void InsertIntoNeedsTypeHandleList(TypeBuilderState state, TypeDesc type) { if ((type is DefType) || (type is ArrayType) || (type is PointerType) || (type is ByRefType)) { _typesThatNeedTypeHandles.Add(type); } } /// <summary> /// Collects all dependencies that need to be created in order to create /// the type that was passed in. /// </summary> internal void PrepareType(TypeDesc type) { TypeLoaderLogger.WriteLine("Preparing type " + type.ToString() + " ..."); TypeBuilderState state = type.GetTypeBuilderStateIfExist(); bool hasTypeHandle = type.RetrieveRuntimeTypeHandleIfPossible(); // If this type has type handle, do nothing and return unless we should prepare even in the presence of a type handle if (hasTypeHandle) return; if (state == null) state = type.GetOrCreateTypeBuilderState(); // If this type was already prepared, do nothing unless we are re-preparing it for the purpose of loading the field layout if (state.HasBeenPrepared) { return; } state.HasBeenPrepared = true; state.NeedsTypeHandle = true; if (!hasTypeHandle) { InsertIntoNeedsTypeHandleList(state, type); } bool noExtraPreparation = false; // Set this to true for types which don't need other types to be prepared. I.e GenericTypeDefinitions if (type is DefType) { DefType typeAsDefType = (DefType)type; if (typeAsDefType.HasInstantiation) { if (typeAsDefType.IsTypeDefinition) { noExtraPreparation = true; } else { // This call to ComputeTemplate will find the native layout info for the type, and the template // For metadata loaded types, a template will not exist, but we may find the NativeLayout describing the generic dictionary TypeDesc.ComputeTemplate(state, false); Debug.Assert(state.TemplateType == null || (state.TemplateType is DefType && !state.TemplateType.RuntimeTypeHandle.IsNull())); // Collect dependencies // We need the instantiation arguments to register a generic type foreach (var instArg in typeAsDefType.Instantiation) RegisterForPreparation(instArg); // We need the type definition to register a generic type if (type.GetTypeDefinition() is MetadataType) RegisterForPreparation(type.GetTypeDefinition()); ParseNativeLayoutInfo(state, type); } } if (!noExtraPreparation) state.PrepareStaticGCLayout(); } else if (type is ParameterizedType) { PrepareType(((ParameterizedType)type).ParameterType); if (type is ArrayType) { ArrayType typeAsArrayType = (ArrayType)type; if (typeAsArrayType.IsSzArray && !typeAsArrayType.ElementType.IsPointer) { TypeDesc.ComputeTemplate(state); Debug.Assert(state.TemplateType != null && state.TemplateType is ArrayType && !state.TemplateType.RuntimeTypeHandle.IsNull()); ParseNativeLayoutInfo(state, type); } else { Debug.Assert(typeAsArrayType.IsMdArray || typeAsArrayType.ElementType.IsPointer); } // Assert that non-valuetypes are considered to have pointer size Debug.Assert(typeAsArrayType.ParameterType.IsValueType || state.ComponentSize == IntPtr.Size); } } else { Debug.Assert(false); } // Need to prepare the base type first since it is used to compute interfaces if (!noExtraPreparation) { PrepareBaseTypeAndDictionaries(type); PrepareRuntimeInterfaces(type); TypeLoaderLogger.WriteLine("Layout for type " + type.ToString() + " complete." + " IsHFA = " + (state.IsHFA ? "true" : "false") + " Type size = " + (state.TypeSize.HasValue ? state.TypeSize.Value.LowLevelToString() : "UNDEF") + " Fields size = " + (state.UnalignedTypeSize.HasValue ? state.UnalignedTypeSize.Value.LowLevelToString() : "UNDEF") + " Type alignment = " + (state.FieldAlignment.HasValue ? state.FieldAlignment.Value.LowLevelToString() : "UNDEF")); #if FEATURE_UNIVERSAL_GENERICS if (state.TemplateType != null && state.TemplateType.IsCanonicalSubtype(CanonicalFormKind.Universal)) { state.VTableSlotsMapping = new VTableSlotMapper(state.TemplateType.RuntimeTypeHandle.GetNumVtableSlots()); ComputeVTableLayout(type, state.TemplateType, state); } #endif } } /// <summary> /// Recursively triggers preparation for a type's runtime interfaces /// </summary> private void PrepareRuntimeInterfaces(TypeDesc type) { // Prepare all the interfaces that might be used. (This can be a superset of the // interfaces explicitly in the NativeLayout.) foreach (DefType interfaceType in type.RuntimeInterfaces) { PrepareType(interfaceType); } } /// <summary> /// Triggers preparation for a type's base types /// </summary> private void PrepareBaseTypeAndDictionaries(TypeDesc type) { DefType baseType = type.BaseType; if (baseType == null) return; PrepareType(baseType); } private void ProcessTypesNeedingPreparation() { // Process the pending types while (_typesThatNeedPreparation != null) { var pendingTypes = _typesThatNeedPreparation; _typesThatNeedPreparation = null; for (int i = 0; i < pendingTypes.Count; i++) PrepareType(pendingTypes[i]); } } private static GenericDictionaryCell[] GetGenericMethodDictionaryCellsForMetadataBasedLoad(InstantiatedMethod method, InstantiatedMethod nonTemplateMethod) { #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING uint r2rNativeLayoutInfoToken; GenericDictionaryCell[] cells = null; NativeFormatModuleInfo r2rNativeLayoutModuleInfo; if ((new TemplateLocator()).TryGetMetadataNativeLayout(nonTemplateMethod, out r2rNativeLayoutModuleInfo, out r2rNativeLayoutInfoToken)) { // ReadyToRun dictionary parsing NativeReader readyToRunReader = TypeLoaderEnvironment.Instance.GetNativeLayoutInfoReader(r2rNativeLayoutModuleInfo.Handle); var readyToRunInfoParser = new NativeParser(readyToRunReader, r2rNativeLayoutInfoToken); // A null readyToRunInfoParser is a valid situation to end up in // This can happen if either we have exact code for a method, or if // we are going to use the universal generic implementation. // In both of those cases, we do not have any generic dictionary cells // to put into the dictionary if (!readyToRunInfoParser.IsNull) { NativeFormatMetadataUnit nativeMetadataUnit = method.Context.ResolveMetadataUnit(r2rNativeLayoutModuleInfo); FixupCellMetadataResolver resolver = new FixupCellMetadataResolver(nativeMetadataUnit, nonTemplateMethod); cells = GenericDictionaryCell.BuildDictionaryFromMetadataTokensAndContext(this, readyToRunInfoParser, nativeMetadataUnit, resolver); } } return cells; #else return null; #endif } internal void ParseNativeLayoutInfo(InstantiatedMethod method) { TypeLoaderLogger.WriteLine("Parsing NativeLayoutInfo for method " + method.ToString() + " ..."); Debug.Assert(method.Dictionary == null); InstantiatedMethod nonTemplateMethod = method; // Templates are always non-unboxing stubs if (method.UnboxingStub) { // Strip unboxing stub, note the first parameter which is false nonTemplateMethod = (InstantiatedMethod)method.Context.ResolveGenericMethodInstantiation(false, (DefType)method.OwningType, method.NameAndSignature, method.Instantiation, IntPtr.Zero, false); } uint nativeLayoutInfoToken; NativeFormatModuleInfo nativeLayoutModule; MethodDesc templateMethod = TemplateLocator.TryGetGenericMethodTemplate(nonTemplateMethod, out nativeLayoutModule, out nativeLayoutInfoToken); // If the templateMethod found in the static image is missing or universal, see if the R2R layout // can provide something more specific. if ((templateMethod == null) || templateMethod.IsCanonicalMethod(CanonicalFormKind.Universal)) { GenericDictionaryCell[] cells = GetGenericMethodDictionaryCellsForMetadataBasedLoad(method, nonTemplateMethod); if (cells != null) { method.SetGenericDictionary(new GenericMethodDictionary(cells)); return; } if (templateMethod == null) { #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING // In this case we were looking for the r2r template to create the dictionary, but // there isn't one. This implies that we don't need a Canon specific dictionary // so just generate something empty method.SetGenericDictionary(new GenericMethodDictionary(Array.Empty<GenericDictionaryCell>())); return; #else throw new TypeBuilder.MissingTemplateException(); #endif } } // Ensure that if this method is non-shareable from a normal canonical perspective, then // its template MUST be a universal canonical template method Debug.Assert(!method.IsNonSharableMethod || (method.IsNonSharableMethod && templateMethod.IsCanonicalMethod(CanonicalFormKind.Universal))); NativeReader nativeLayoutInfoReader = TypeLoaderEnvironment.GetNativeLayoutInfoReader(nativeLayoutModule.Handle); var methodInfoParser = new NativeParser(nativeLayoutInfoReader, nativeLayoutInfoToken); var context = new NativeLayoutInfoLoadContext { _typeSystemContext = method.Context, _typeArgumentHandles = method.OwningType.Instantiation, _methodArgumentHandles = method.Instantiation, _module = nativeLayoutModule }; BagElementKind kind; while ((kind = methodInfoParser.GetBagElementKind()) != BagElementKind.End) { switch (kind) { case BagElementKind.DictionaryLayout: TypeLoaderLogger.WriteLine("Found BagElementKind.DictionaryLayout"); method.SetGenericDictionary(new GenericMethodDictionary(GenericDictionaryCell.BuildDictionary(this, context, methodInfoParser.GetParserFromRelativeOffset()))); break; default: Debug.Fail("Unexpected BagElementKind for generic method with name " + method.NameAndSignature.Name + "! Only BagElementKind.DictionaryLayout should appear."); throw new BadImageFormatException(); } } if (method.Dictionary == null) method.SetGenericDictionary(new GenericMethodDictionary(Array.Empty<GenericDictionaryCell>())); } internal void ParseNativeLayoutInfo(TypeBuilderState state, TypeDesc type) { TypeLoaderLogger.WriteLine("Parsing NativeLayoutInfo for type " + type.ToString() + " ..."); bool isTemplateUniversalCanon = false; if (state.TemplateType != null) { isTemplateUniversalCanon = state.TemplateType.IsCanonicalSubtype(CanonicalFormKind.Universal); } // If we found the universal template, see if there is a ReadyToRun dictionary description available. // If so, use that, otherwise, run down the template type loader path with the universal template if ((state.TemplateType == null) || isTemplateUniversalCanon) { // ReadyToRun case - Native Layout is just the dictionary NativeParser readyToRunInfoParser = state.GetParserForReadyToRunNativeLayoutInfo(); GenericDictionaryCell[] cells = null; // A null readyToRunInfoParser is a valid situation to end up in // This can happen if either we have exact code for the method on a type, or if // we are going to use the universal generic implementation. // In both of those cases, we do not have any generic dictionary cells // to put into the dictionary if (!readyToRunInfoParser.IsNull) { #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING NativeFormatMetadataUnit nativeMetadataUnit = type.Context.ResolveMetadataUnit(state.R2RNativeLayoutInfo.Module); FixupCellMetadataResolver resolver = new FixupCellMetadataResolver(nativeMetadataUnit, type); cells = GenericDictionaryCell.BuildDictionaryFromMetadataTokensAndContext(this, readyToRunInfoParser, nativeMetadataUnit, resolver); #endif } state.Dictionary = cells != null ? new GenericTypeDictionary(cells) : null; if (state.TemplateType == null) return; } NativeParser typeInfoParser = state.GetParserForNativeLayoutInfo(); NativeLayoutInfoLoadContext context = state.NativeLayoutInfo.LoadContext; NativeParser baseTypeParser = new NativeParser(); int nonGcDataSize = 0; int gcDataSize = 0; int threadDataSize = 0; bool staticSizesMeaningful = (type is DefType) // Is type permitted to have static fields && !isTemplateUniversalCanon; // Non-universal templates always specify their statics sizes // if the size can be greater than 0 int baseTypeSize = 0; bool checkBaseTypeSize = false; BagElementKind kind; while ((kind = typeInfoParser.GetBagElementKind()) != BagElementKind.End) { switch (kind) { case BagElementKind.BaseType: TypeLoaderLogger.WriteLine("Found BagElementKind.BaseType"); Debug.Assert(baseTypeParser.IsNull); baseTypeParser = typeInfoParser.GetParserFromRelativeOffset(); break; case BagElementKind.BaseTypeSize: TypeLoaderLogger.WriteLine("Found BagElementKind.BaseTypeSize"); Debug.Assert(state.TemplateType.IsCanonicalSubtype(CanonicalFormKind.Universal)); baseTypeSize = checked((int)typeInfoParser.GetUnsigned()); break; case BagElementKind.ImplementedInterfaces: TypeLoaderLogger.WriteLine("Found BagElementKind.ImplementedInterfaces"); // Interface handling is done entirely in NativeLayoutInterfacesAlgorithm typeInfoParser.GetUnsigned(); break; case BagElementKind.TypeFlags: { TypeLoaderLogger.WriteLine("Found BagElementKind.TypeFlags"); Internal.NativeFormat.TypeFlags flags = (Internal.NativeFormat.TypeFlags)typeInfoParser.GetUnsigned(); Debug.Assert(state.HasStaticConstructor == ((flags & Internal.NativeFormat.TypeFlags.HasClassConstructor) != 0)); } break; case BagElementKind.ClassConstructorPointer: TypeLoaderLogger.WriteLine("Found BagElementKind.ClassConstructorPointer"); state.ClassConstructorPointer = context.GetGCStaticInfo(typeInfoParser.GetUnsigned()); break; case BagElementKind.NonGcStaticDataSize: TypeLoaderLogger.WriteLine("Found BagElementKind.NonGcStaticDataSize"); // Use checked typecast to int to ensure there aren't any overflows/truncations (size value used in allocation of memory later) nonGcDataSize = checked((int)typeInfoParser.GetUnsigned()); Debug.Assert(staticSizesMeaningful); break; case BagElementKind.GcStaticDataSize: TypeLoaderLogger.WriteLine("Found BagElementKind.GcStaticDataSize"); // Use checked typecast to int to ensure there aren't any overflows/truncations (size value used in allocation of memory later) gcDataSize = checked((int)typeInfoParser.GetUnsigned()); Debug.Assert(staticSizesMeaningful); break; case BagElementKind.ThreadStaticDataSize: TypeLoaderLogger.WriteLine("Found BagElementKind.ThreadStaticDataSize"); // Use checked typecast to int to ensure there aren't any overflows/truncations (size value used in allocation of memory later) threadDataSize = checked((int)typeInfoParser.GetUnsigned()); Debug.Assert(staticSizesMeaningful); break; case BagElementKind.GcStaticDesc: TypeLoaderLogger.WriteLine("Found BagElementKind.GcStaticDesc"); state.GcStaticDesc = context.GetGCStaticInfo(typeInfoParser.GetUnsigned()); break; case BagElementKind.ThreadStaticDesc: TypeLoaderLogger.WriteLine("Found BagElementKind.ThreadStaticDesc"); state.ThreadStaticDesc = context.GetGCStaticInfo(typeInfoParser.GetUnsigned()); break; case BagElementKind.GenericVarianceInfo: TypeLoaderLogger.WriteLine("Found BagElementKind.GenericVarianceInfo"); NativeParser varianceInfoParser = typeInfoParser.GetParserFromRelativeOffset(); state.GenericVarianceFlags = new GenericVariance[varianceInfoParser.GetSequenceCount()]; for (int i = 0; i < state.GenericVarianceFlags.Length; i++) state.GenericVarianceFlags[i] = checked((GenericVariance)varianceInfoParser.GetUnsigned()); break; case BagElementKind.FieldLayout: TypeLoaderLogger.WriteLine("Found BagElementKind.FieldLayout"); typeInfoParser.SkipInteger(); // Handled in type layout algorithm break; #if FEATURE_UNIVERSAL_GENERICS case BagElementKind.VTableMethodSignatures: TypeLoaderLogger.WriteLine("Found BagElementKind.VTableMethodSignatures"); ParseVTableMethodSignatures(state, context, typeInfoParser.GetParserFromRelativeOffset()); break; #endif case BagElementKind.SealedVTableEntries: TypeLoaderLogger.WriteLine("Found BagElementKind.SealedVTableEntries"); state.NumSealedVTableEntries = typeInfoParser.GetUnsigned(); break; case BagElementKind.DictionaryLayout: TypeLoaderLogger.WriteLine("Found BagElementKind.DictionaryLayout"); Debug.Assert(!isTemplateUniversalCanon, "Universal template nativelayout do not have DictionaryLayout"); Debug.Assert(state.Dictionary == null); if (!state.TemplateType.RetrieveRuntimeTypeHandleIfPossible()) { TypeLoaderLogger.WriteLine("ERROR: failed to get type handle for template type " + state.TemplateType.ToString()); throw new TypeBuilder.MissingTemplateException(); } state.Dictionary = new GenericTypeDictionary(GenericDictionaryCell.BuildDictionary(this, context, typeInfoParser.GetParserFromRelativeOffset())); break; default: TypeLoaderLogger.WriteLine("Found unknown BagElementKind: " + ((int)kind).LowLevelToString()); typeInfoParser.SkipInteger(); break; } } if (staticSizesMeaningful) { Debug.Assert((state.NonGcDataSize + (state.HasStaticConstructor ? TypeBuilder.ClassConstructorOffset : 0)) == nonGcDataSize); Debug.Assert(state.GcDataSize == gcDataSize); Debug.Assert(state.ThreadDataSize == threadDataSize); } #if GENERICS_FORCE_USG if (isTemplateUniversalCanon && type.CanShareNormalGenericCode()) { // Even in the GENERICS_FORCE_USG stress mode today, codegen will generate calls to normal-canonical target methods whenever possible. // Given that we use universal template types to build the dynamic EETypes, these dynamic types will end up with NULL dictionary // entries, causing the normal-canonical code sharing to fail. // To fix this problem, we will load the generic dictionary from the non-universal template type, and build a generic dictionary out of // it for the dynamic type, and store that dictionary pointer in the dynamic MethodTable's structure. TypeBuilderState tempState = new TypeBuilderState(); tempState.NativeLayoutInfo = new NativeLayoutInfo(); state.NonUniversalTemplateType = tempState.TemplateType = type.Context.TemplateLookup.TryGetNonUniversalTypeTemplate(type, ref tempState.NativeLayoutInfo); if (tempState.TemplateType != null) { Debug.Assert(!tempState.TemplateType.IsCanonicalSubtype(CanonicalFormKind.UniversalCanonLookup)); NativeParser nonUniversalTypeInfoParser = GetNativeLayoutInfoParser(type, ref tempState.NativeLayoutInfo); NativeParser dictionaryLayoutParser = nonUniversalTypeInfoParser.GetParserForBagElementKind(BagElementKind.DictionaryLayout); if (!dictionaryLayoutParser.IsNull) state.Dictionary = new GenericTypeDictionary(GenericDictionaryCell.BuildDictionary(this, context, dictionaryLayoutParser)); // Get the non-universal GCDesc pointers, so we can compare them the ones we will dynamically construct for the type // and verify they are equal (This is an easy and predictable way of validation for the GCDescs creation logic in the stress mode) GetNonUniversalGCDescPointers(type, state, tempState); } } #endif type.ParseBaseType(context, baseTypeParser); // Assert that parsed base type size matches the BaseTypeSize that we calculated. Debug.Assert(!checkBaseTypeSize || state.BaseTypeSize == baseTypeSize); } #if FEATURE_UNIVERSAL_GENERICS private void ParseVTableMethodSignatures(TypeBuilderState state, NativeLayoutInfoLoadContext nativeLayoutInfoLoadContext, NativeParser methodSignaturesParser) { TypeDesc type = state.TypeBeingBuilt; if (methodSignaturesParser.IsNull) return; // Processing vtable method signatures is only meaningful in the context of universal generics only Debug.Assert(state.TemplateType != null && state.TemplateType.IsCanonicalSubtype(CanonicalFormKind.Universal)); uint numSignatures = methodSignaturesParser.GetUnsigned(); state.VTableMethodSignatures = new TypeBuilderState.VTableLayoutInfo[numSignatures]; for (int i = 0; i < numSignatures; i++) { state.VTableMethodSignatures[i] = new TypeBuilderState.VTableLayoutInfo(); uint slot = methodSignaturesParser.GetUnsigned(); state.VTableMethodSignatures[i].VTableSlot = (slot >> 1); if ((slot & 1) == 1) { state.VTableMethodSignatures[i].IsSealedVTableSlot = true; state.NumSealedVTableMethodSignatures++; } NativeParser sigParser = methodSignaturesParser.GetParserFromRelativeOffset(); state.VTableMethodSignatures[i].MethodSignature = RuntimeSignature.CreateFromNativeLayoutSignature(nativeLayoutInfoLoadContext._module.Handle, sigParser.Offset); } } #endif private unsafe void ComputeVTableLayout(TypeDesc currentType, TypeDesc currentTemplateType, TypeBuilderState targetTypeState) { TypeDesc baseType = GetBaseTypeThatIsCorrectForMDArrays(currentType); TypeDesc baseTemplateType = GetBaseTypeUsingRuntimeTypeHandle(currentTemplateType); Debug.Assert((baseType == null && baseTemplateType == null) || (baseType != null && baseTemplateType != null)); // Compute the vtable layout for the current type starting with base types first if (baseType != null) ComputeVTableLayout(baseType, baseTemplateType, targetTypeState); currentTemplateType.RetrieveRuntimeTypeHandleIfPossible(); Debug.Assert(!currentTemplateType.RuntimeTypeHandle.IsNull()); Debug.Assert(baseTemplateType == null || !baseTemplateType.RuntimeTypeHandle.IsNull()); // The m_usNumVtableSlots field on EETypes includes the count of vtable slots of the base type, // so make sure we don't count that twice! int currentVtableIndex = baseTemplateType == null ? 0 : baseTemplateType.RuntimeTypeHandle.GetNumVtableSlots(); IntPtr dictionarySlotInVtable = IntPtr.Zero; if (currentType.IsGeneric()) { if (!currentType.CanShareNormalGenericCode() && currentTemplateType.IsCanonicalSubtype(CanonicalFormKind.Universal)) { // We are building a type that cannot share code with normal canonical types, so the type has to have // the same vtable layout as non-shared generics, meaning no dictionary pointer in the vtable. // We use universal canonical template types to build such types. Universal canonical types have 'NULL' // dictionary pointers in their vtables, so we'll start copying the vtable entries right after that // dictionary slot (dictionaries are accessed/used at runtime in a different way, not through the vtable // dictionary pointer for such types). currentVtableIndex++; } else if (currentType.CanShareNormalGenericCode()) { // In the case of a normal canonical type in their base class hierarchy, // we need to keep track of its dictionary slot in the vtable mapping, and try to // copy its value values directly from its template type vtable. // Two possible cases: // 1) The template type is a normal canonical type. In this case, the dictionary value // in the vtable slot of the template is NULL, but that's ok because this case is // correctly handled anyways by the FinishBaseTypeAndDictionaries() API. // 2) The template type is NOT a canonical type. In this case, the dictionary value // in the vtable slot of the template is not null, and we keep track of it in the // VTableSlotsMapping so we can copy it to the dynamic type after creation. // This corner case is not handled by FinishBaseTypeAndDictionaries(), so we track it // here. // Examples: // 1) Derived<T,U> : Base<U>, instantiated over [int,string] // 2) Derived<__Universal> : BaseClass, and BaseClass : BaseBaseClass<object> // 3) Derived<__Universal> : BaseClass<object> Debug.Assert(currentTemplateType != null && !currentTemplateType.RuntimeTypeHandle.IsNull()); IntPtr* pTemplateVtable = (IntPtr*)((byte*)(currentTemplateType.RuntimeTypeHandle.ToEETypePtr()) + sizeof(MethodTable)); dictionarySlotInVtable = pTemplateVtable[currentVtableIndex]; } } else if (currentType is ArrayType) { if (currentTemplateType.IsCanonicalSubtype(CanonicalFormKind.Universal)) { TypeDesc canonicalElementType = currentType.Context.ConvertToCanon(((ArrayType)currentType).ElementType, CanonicalFormKind.Specific); bool quickIsNotCanonical = canonicalElementType == ((ArrayType)currentType).ElementType; Debug.Assert(quickIsNotCanonical == !canonicalElementType.IsCanonicalSubtype(CanonicalFormKind.Any)); if (quickIsNotCanonical) { // We are building a type that cannot share code with normal canonical types, so the type has to have // the same vtable layout as non-shared generics, meaning no dictionary pointer in the vtable. // We use universal canonical template types to build such types. Universal canonical types have 'NULL' // dictionary pointers in their vtables, so we'll start copying the vtable entries right after that // dictionary slot (dictionaries are accessed/used at runtime in a different way, not through the vtable // dictionary pointer for such types). currentVtableIndex++; } } } // Map vtable entries from target type's template type int numVtableSlotsOnCurrentTemplateType = currentTemplateType.RuntimeTypeHandle.GetNumVtableSlots(); for (; currentVtableIndex < numVtableSlotsOnCurrentTemplateType; currentVtableIndex++) { targetTypeState.VTableSlotsMapping.AddMapping( currentVtableIndex, targetTypeState.VTableSlotsMapping.NumSlotMappings, dictionarySlotInVtable); // Reset dictionarySlotInVtable (only one dictionary slot in vtable per type) dictionarySlotInVtable = IntPtr.Zero; } // Sanity check: vtable of the dynamic type should be equal or smaller than the vtable of the template type Debug.Assert(targetTypeState.VTableSlotsMapping.NumSlotMappings <= numVtableSlotsOnCurrentTemplateType); } /// <summary> /// Wraps information about how a type is laid out into one package. Types may have been laid out by /// TypeBuilder (which means they have a gc bitfield), or they could be types that were laid out by NUTC /// (which means we only have a GCDesc for them). This struct wraps both of those possibilities into /// one package to be able to write that layout to another bitfield we are constructing. (This is for /// struct fields.) /// </summary> internal unsafe struct GCLayout { private LowLevelList<bool> _bitfield; private unsafe void* _gcdesc; private int _size; private bool _isReferenceTypeGCLayout; public static GCLayout None { get { return new GCLayout(); } } public static GCLayout SingleReference { get; } = new GCLayout(new LowLevelList<bool>(new bool[1] { true }), false); public bool IsNone { get { return _bitfield == null && _gcdesc == null; } } public GCLayout(LowLevelList<bool> bitfield, bool isReferenceTypeGCLayout) { Debug.Assert(bitfield != null); _bitfield = bitfield; _gcdesc = null; _size = 0; _isReferenceTypeGCLayout = isReferenceTypeGCLayout; } public GCLayout(RuntimeTypeHandle rtth) { MethodTable* MethodTable = rtth.ToEETypePtr(); Debug.Assert(MethodTable != null); _bitfield = null; _isReferenceTypeGCLayout = false; // This field is only used for the LowLevelList<bool> path _gcdesc = MethodTable->HasGCPointers ? (void**)MethodTable - 1 : null; _size = (int)MethodTable->BaseSize; } /// <summary> /// Writes this layout to the given bitfield. /// </summary> /// <param name="bitfield">The bitfield to write a layout to (may be null, at which /// point it will be created and assigned).</param> /// <param name="offset">The offset at which we need to write the bitfield.</param> public void WriteToBitfield(LowLevelList<bool> bitfield, int offset) { if (bitfield == null) throw new ArgumentNullException(nameof(bitfield)); if (IsNone) return; // Ensure exactly one of these two are set. Debug.Assert(_gcdesc != null ^ _bitfield != null); if (_bitfield != null) MergeBitfields(bitfield, offset); else WriteGCDescToBitfield(bitfield, offset); } private unsafe void WriteGCDescToBitfield(LowLevelList<bool> bitfield, int offset) { int startIndex = offset / IntPtr.Size; void** ptr = (void**)_gcdesc; Debug.Assert(_gcdesc != null); // Number of series int count = (int)*ptr-- - 1; Debug.Assert(count >= 0); // Ensure capacity for the values we are about to write int capacity = startIndex + _size / IntPtr.Size - 2; bitfield.Expand(capacity); while (count-- >= 0) { int offs = (int)*ptr-- / IntPtr.Size - 1; int len = ((int)*ptr-- + _size) / IntPtr.Size; Debug.Assert(len > 0); Debug.Assert(offs >= 0); for (int i = 0; i < len; i++) bitfield[startIndex + offs + i] = true; } } private void MergeBitfields(LowLevelList<bool> outputBitfield, int offset) { int startIndex = offset / IntPtr.Size; // These routines represent the GC layout after the MethodTable pointer // in an object, but the LowLevelList<bool> bitfield logically contains // the EETypepointer if it is describing a reference type. So, skip the // first value. int itemsToSkip = _isReferenceTypeGCLayout ? 1 : 0; // Assert that we only skip a non-reported pointer. Debug.Assert(itemsToSkip == 0 || _bitfield[0] == false); // Ensure capacity for the values we are about to write int capacity = startIndex + _bitfield.Count - itemsToSkip; outputBitfield.Expand(capacity); for (int i = itemsToSkip; i < _bitfield.Count; i++) { // We should never overwrite a TRUE value in the table. Debug.Assert(!outputBitfield[startIndex + i - itemsToSkip] || _bitfield[i]); outputBitfield[startIndex + i - itemsToSkip] = _bitfield[i]; } } } #if GENERICS_FORCE_USG private unsafe void GetNonUniversalGCDescPointers(TypeDesc type, TypeBuilderState state, TypeBuilderState tempNonUniversalState) { NativeParser nonUniversalTypeInfoParser = GetNativeLayoutInfoParser(type, ref tempNonUniversalState.NativeLayoutInfo); NativeLayoutInfoLoadContext context = tempNonUniversalState.NativeLayoutInfo.LoadContext; uint beginOffset = nonUniversalTypeInfoParser.Offset; uint? staticGCDescId = nonUniversalTypeInfoParser.GetUnsignedForBagElementKind(BagElementKind.GcStaticDesc); nonUniversalTypeInfoParser.Offset = beginOffset; uint? threadStaticGCDescId = nonUniversalTypeInfoParser.GetUnsignedForBagElementKind(BagElementKind.ThreadStaticDesc); if(staticGCDescId.HasValue) state.NonUniversalStaticGCDesc = context.GetStaticInfo(staticGCDescId.Value); if (threadStaticGCDescId.HasValue) state.NonUniversalThreadStaticGCDesc = context.GetStaticInfo(threadStaticGCDescId.Value); state.NonUniversalInstanceGCDescSize = RuntimeAugments.GetGCDescSize(tempNonUniversalState.TemplateType.RuntimeTypeHandle); if (state.NonUniversalInstanceGCDescSize > 0) state.NonUniversalInstanceGCDesc = new IntPtr(((byte*)tempNonUniversalState.TemplateType.RuntimeTypeHandle.ToIntPtr().ToPointer()) - 1); } #endif private unsafe void AllocateRuntimeType(TypeDesc type) { TypeBuilderState state = type.GetTypeBuilderState(); Debug.Assert(type is DefType || type is ArrayType || type is PointerType || type is ByRefType); if (state.ThreadDataSize != 0) state.ThreadStaticOffset = TypeLoaderEnvironment.Instance.GetNextThreadStaticsOffsetValue(); RuntimeTypeHandle rtt = EETypeCreator.CreateEEType(type, state); if (state.ThreadDataSize != 0) TypeLoaderEnvironment.Instance.RegisterDynamicThreadStaticsInfo(state.HalfBakedRuntimeTypeHandle, state.ThreadStaticOffset, state.ThreadDataSize); TypeLoaderLogger.WriteLine("Allocated new type " + type.ToString() + " with hashcode value = 0x" + type.GetHashCode().LowLevelToString() + " with MethodTable = " + rtt.ToIntPtr().LowLevelToString() + " of size " + rtt.ToEETypePtr()->BaseSize.LowLevelToString()); } private static void AllocateRuntimeMethodDictionary(InstantiatedMethod method) { Debug.Assert(method.RuntimeMethodDictionary == IntPtr.Zero && method.Dictionary != null); IntPtr rmd = method.Dictionary.Allocate(); method.AssociateWithRuntimeMethodDictionary(rmd); TypeLoaderLogger.WriteLine("Allocated new method dictionary for method " + method.ToString() + " @ " + rmd.LowLevelToString()); } private RuntimeTypeHandle[] GetGenericContextOfBaseType(DefType type, int vtableMethodSlot) { DefType baseType = type.BaseType; Debug.Assert(baseType == null || !GetRuntimeTypeHandle(baseType).IsNull()); Debug.Assert(vtableMethodSlot < GetRuntimeTypeHandle(type).GetNumVtableSlots()); int numBaseTypeVtableSlots = baseType == null ? 0 : GetRuntimeTypeHandle(baseType).GetNumVtableSlots(); if (vtableMethodSlot < numBaseTypeVtableSlots) return GetGenericContextOfBaseType(baseType, vtableMethodSlot); else return GetRuntimeTypeHandles(type.Instantiation); } #if FEATURE_UNIVERSAL_GENERICS private unsafe void FinishVTableCallingConverterThunks(TypeDesc type, TypeBuilderState state) { Debug.Assert(state.TemplateType.IsCanonicalSubtype(CanonicalFormKind.Universal)); if (state.VTableMethodSignatures == null || state.VTableMethodSignatures.Length == 0) return; int numVtableSlots = GetRuntimeTypeHandle(type).GetNumVtableSlots(); IntPtr* vtableCells = (IntPtr*)((byte*)GetRuntimeTypeHandle(type).ToIntPtr() + sizeof(MethodTable)); Debug.Assert((state.VTableMethodSignatures.Length - state.NumSealedVTableMethodSignatures) <= numVtableSlots); TypeDesc baseType = type.BaseType; int numBaseTypeVtableSlots = GetRuntimeTypeHandle(baseType).GetNumVtableSlots(); // Generic context RuntimeTypeHandle[] typeArgs = Empty<RuntimeTypeHandle>.Array; if (type is DefType) typeArgs = GetRuntimeTypeHandles(((DefType)type).Instantiation); else if (type is ArrayType) typeArgs = GetRuntimeTypeHandles(new Instantiation(new TypeDesc[] { ((ArrayType)type).ElementType })); for (int i = 0; i < state.VTableMethodSignatures.Length; i++) { RuntimeTypeHandle[] typeArgsToUse = typeArgs; int vtableSlotInDynamicType = -1; if (!state.VTableMethodSignatures[i].IsSealedVTableSlot) { vtableSlotInDynamicType = state.VTableSlotsMapping.GetVTableSlotInTargetType((int)state.VTableMethodSignatures[i].VTableSlot); Debug.Assert(vtableSlotInDynamicType != -1); if (vtableSlotInDynamicType < numBaseTypeVtableSlots) { // Vtable method from the vtable portion of a base type. Use generic context of the basetype defining the vtable slot. // We should never reach here for array types (the vtable entries of the System.Array basetype should never need a converter). Debug.Assert(type is DefType); typeArgsToUse = GetGenericContextOfBaseType((DefType)type, vtableSlotInDynamicType); } } IntPtr originalFunctionPointerFromVTable = state.VTableMethodSignatures[i].IsSealedVTableSlot ? ((IntPtr*)state.HalfBakedSealedVTable)[state.VTableMethodSignatures[i].VTableSlot] : vtableCells[vtableSlotInDynamicType]; IntPtr thunkPtr = CallConverterThunk.MakeThunk( ThunkKind.StandardToGeneric, originalFunctionPointerFromVTable, state.VTableMethodSignatures[i].MethodSignature, IntPtr.Zero, // No instantiating arg for non-generic instance methods typeArgsToUse, Empty<RuntimeTypeHandle>.Array); // No GVMs in vtables, no no method args if (state.VTableMethodSignatures[i].IsSealedVTableSlot) { // Patch the sealed vtable entry to point to the calling converter thunk Debug.Assert(state.VTableMethodSignatures[i].VTableSlot < state.NumSealedVTableEntries && state.HalfBakedSealedVTable != IntPtr.Zero); ((IntPtr*)state.HalfBakedSealedVTable)[state.VTableMethodSignatures[i].VTableSlot] = thunkPtr; } else { // Patch the vtable entry to point to the calling converter thunk Debug.Assert(vtableSlotInDynamicType < numVtableSlots && vtableCells != null); vtableCells[vtableSlotInDynamicType] = thunkPtr; } } } #endif // // Returns either the registered type handle or half-baked type handle. This method should be only called // during final phase of type building. // #pragma warning disable CA1822 public RuntimeTypeHandle GetRuntimeTypeHandle(TypeDesc type) { #if DEBUG Debug.Assert(_finalTypeBuilding); #endif var rtth = type.RuntimeTypeHandle; if (!rtth.IsNull()) return rtth; rtth = type.GetTypeBuilderState().HalfBakedRuntimeTypeHandle; Debug.Assert(!rtth.IsNull()); return rtth; } #pragma warning restore CA1822 public RuntimeTypeHandle[] GetRuntimeTypeHandles(Instantiation types) { if (types.Length == 0) return Array.Empty<RuntimeTypeHandle>(); RuntimeTypeHandle[] result = new RuntimeTypeHandle[types.Length]; for (int i = 0; i < types.Length; i++) result[i] = GetRuntimeTypeHandle(types[i]); return result; } public static DefType GetBaseTypeUsingRuntimeTypeHandle(TypeDesc type) { type.RetrieveRuntimeTypeHandleIfPossible(); unsafe { RuntimeTypeHandle thBaseTypeTemplate = type.RuntimeTypeHandle.ToEETypePtr()->BaseType->ToRuntimeTypeHandle(); if (thBaseTypeTemplate.IsNull()) return null; return (DefType)type.Context.ResolveRuntimeTypeHandle(thBaseTypeTemplate); } } public static DefType GetBaseTypeThatIsCorrectForMDArrays(TypeDesc type) { if (type.BaseType == type.Context.GetWellKnownType(WellKnownType.Array)) { // Use the type from the template, the metadata we have will be inaccurate for multidimensional // arrays, as we hide the MDArray infrastructure from the metadata. TypeDesc template = type.ComputeTemplate(false); return GetBaseTypeUsingRuntimeTypeHandle(template ?? type); } return type.BaseType; } private void FinishInterfaces(TypeDesc type, TypeBuilderState state) { DefType[] interfaces = state.RuntimeInterfaces; if (interfaces != null) { for (int i = 0; i < interfaces.Length; i++) { state.HalfBakedRuntimeTypeHandle.SetInterface(i, GetRuntimeTypeHandle(interfaces[i])); } } } private unsafe void FinishTypeDictionary(TypeDesc type, TypeBuilderState state) { if (state.Dictionary != null) { // First, update the dictionary slot in the type's vtable to point to the created dictionary when applicable Debug.Assert(state.HalfBakedDictionary != IntPtr.Zero); int dictionarySlot = EETypeCreator.GetDictionarySlotInVTable(type); if (dictionarySlot >= 0) { state.HalfBakedRuntimeTypeHandle.SetDictionary(dictionarySlot, state.HalfBakedDictionary); } else { // Dictionary shouldn't be in the vtable of the type Debug.Assert(!type.CanShareNormalGenericCode()); } TypeLoaderLogger.WriteLine("Setting dictionary entries for type " + type.ToString() + " @ " + state.HalfBakedDictionary.LowLevelToString()); state.Dictionary.Finish(this); } } private unsafe void FinishMethodDictionary(InstantiatedMethod method) { Debug.Assert(method.Dictionary != null); TypeLoaderLogger.WriteLine("Setting dictionary entries for method " + method.ToString() + " @ " + method.RuntimeMethodDictionary.LowLevelToString()); method.Dictionary.Finish(this); } private unsafe void FinishClassConstructor(TypeDesc type, TypeBuilderState state) { if (!state.HasStaticConstructor) return; IntPtr canonicalClassConstructorFunctionPointer = IntPtr.Zero; // Pointer to canonical static method to serve as cctor IntPtr exactClassConstructorFunctionPointer = IntPtr.Zero; // Exact pointer. Takes priority over canonical pointer if (state.TemplateType == null) { if (!type.HasInstantiation) { // Non-Generic ReadyToRun types in their current state already have their static field region setup // with the class constructor initialized. return; } else { // For generic types, we need to do the metadata lookup and then resolve to a function pointer. MethodDesc staticConstructor = type.GetStaticConstructor(); IntPtr staticCctor; IntPtr unused1; TypeLoaderEnvironment.MethodAddressType addressType; if (!TypeLoaderEnvironment.TryGetMethodAddressFromMethodDesc(staticConstructor, out staticCctor, out unused1, out addressType)) { Environment.FailFast("Unable to find class constructor method address for type:" + type.ToString()); } Debug.Assert(unused1 == IntPtr.Zero); switch (addressType) { case TypeLoaderEnvironment.MethodAddressType.Exact: // If we have an exact match, put it in the slot directly // and return as we don't want to make this into a fat function pointer exactClassConstructorFunctionPointer = staticCctor; break; case TypeLoaderEnvironment.MethodAddressType.Canonical: case TypeLoaderEnvironment.MethodAddressType.UniversalCanonical: // If we have a canonical method, setup for generating a fat function pointer canonicalClassConstructorFunctionPointer = staticCctor; break; default: Environment.FailFast("Invalid MethodAddressType during ClassConstructor discovery"); return; } } } else if (state.ClassConstructorPointer.HasValue) { canonicalClassConstructorFunctionPointer = state.ClassConstructorPointer.Value; } else { // Lookup the non-GC static data for the template type, and use the class constructor context offset to locate the class constructor's // fat pointer within the non-GC static data. IntPtr templateTypeStaticData = TypeLoaderEnvironment.Instance.TryGetNonGcStaticFieldData(GetRuntimeTypeHandle(state.TemplateType)); Debug.Assert(templateTypeStaticData != IntPtr.Zero); IntPtr* templateTypeClassConstructorSlotPointer = (IntPtr*)((byte*)templateTypeStaticData + ClassConstructorOffset); IntPtr templateTypeClassConstructorFatFunctionPointer = templateTypeClassConstructorFatFunctionPointer = *templateTypeClassConstructorSlotPointer; // Crack the fat function pointer into the raw class constructor method pointer and the generic type dictionary. Debug.Assert(FunctionPointerOps.IsGenericMethodPointer(templateTypeClassConstructorFatFunctionPointer)); GenericMethodDescriptor* templateTypeGenericMethodDescriptor = FunctionPointerOps.ConvertToGenericDescriptor(templateTypeClassConstructorFatFunctionPointer); Debug.Assert(templateTypeGenericMethodDescriptor != null); canonicalClassConstructorFunctionPointer = templateTypeGenericMethodDescriptor->MethodFunctionPointer; } IntPtr generatedTypeStaticData = GetRuntimeTypeHandle(type).ToEETypePtr()->DynamicNonGcStaticsData; IntPtr* generatedTypeClassConstructorSlotPointer = (IntPtr*)((byte*)generatedTypeStaticData + ClassConstructorOffset); if (exactClassConstructorFunctionPointer != IntPtr.Zero) { // We have an exact pointer, not a canonical match // Just set the pointer and return. No need for a fat pointer *generatedTypeClassConstructorSlotPointer = exactClassConstructorFunctionPointer; return; } // If we reach here, classConstructorFunctionPointer points at a canonical method, that needs to be converted into // a fat function pointer so that the calli in the ClassConstructorRunner will work properly Debug.Assert(canonicalClassConstructorFunctionPointer != IntPtr.Zero); // Use the template type's class constructor method pointer and this type's generic type dictionary to generate a new fat pointer, // and save that fat pointer back to this type's class constructor context offset within the non-GC static data. IntPtr instantiationArgument = GetRuntimeTypeHandle(type).ToIntPtr(); IntPtr generatedTypeClassConstructorFatFunctionPointer = FunctionPointerOps.GetGenericMethodFunctionPointer(canonicalClassConstructorFunctionPointer, instantiationArgument); *generatedTypeClassConstructorSlotPointer = generatedTypeClassConstructorFatFunctionPointer; } private void CopyDictionaryFromTypeToAppropriateSlotInDerivedType(TypeDesc baseType, TypeBuilderState derivedTypeState) { var baseTypeState = baseType.GetOrCreateTypeBuilderState(); if (baseTypeState.HasDictionaryInVTable) { RuntimeTypeHandle baseTypeHandle = GetRuntimeTypeHandle(baseType); // If the basetype is currently being created by the TypeBuilder, we need to get its dictionary pointer from the // TypeBuilder state (at this point, the dictionary has not yet been set on the baseTypeHandle). If // the basetype is not a dynamic type, or has previously been dynamically allocated in the past, the TypeBuilder // state will have a null dictionary pointer, in which case we need to read it directly from the basetype's vtable IntPtr dictionaryEntry = baseTypeState.HalfBakedDictionary; if (dictionaryEntry == IntPtr.Zero) dictionaryEntry = baseTypeHandle.GetDictionary(); Debug.Assert(dictionaryEntry != IntPtr.Zero); // Compute the vtable slot for the dictionary entry to set int dictionarySlot = EETypeCreator.GetDictionarySlotInVTable(baseType); Debug.Assert(dictionarySlot >= 0); derivedTypeState.HalfBakedRuntimeTypeHandle.SetDictionary(dictionarySlot, dictionaryEntry); TypeLoaderLogger.WriteLine("Setting basetype " + baseType.ToString() + " dictionary on type " + derivedTypeState.TypeBeingBuilt.ToString()); } } private void FinishBaseTypeAndDictionaries(TypeDesc type, TypeBuilderState state) { DefType baseType = GetBaseTypeThatIsCorrectForMDArrays(type); state.HalfBakedRuntimeTypeHandle.SetBaseType(baseType == null ? default(RuntimeTypeHandle) : GetRuntimeTypeHandle(baseType)); if (baseType == null) return; // Update every dictionary in type hierarchy with copy from base type while (baseType != null) { CopyDictionaryFromTypeToAppropriateSlotInDerivedType(baseType, state); baseType = baseType.BaseType; } } private void FinishRuntimeType(TypeDesc type) { TypeLoaderLogger.WriteLine("Finishing type " + type.ToString() + " ..."); var state = type.GetTypeBuilderState(); if (type is DefType) { DefType typeAsDefType = (DefType)type; if (type.HasInstantiation) { // Type definitions don't need any further finishing once created by the EETypeCreator if (type.IsTypeDefinition) return; state.HalfBakedRuntimeTypeHandle.SetGenericDefinition(GetRuntimeTypeHandle(typeAsDefType.GetTypeDefinition())); Instantiation instantiation = typeAsDefType.Instantiation; state.HalfBakedRuntimeTypeHandle.SetGenericArity((uint)instantiation.Length); for (int argIndex = 0; argIndex < instantiation.Length; argIndex++) { state.HalfBakedRuntimeTypeHandle.SetGenericArgument(argIndex, GetRuntimeTypeHandle(instantiation[argIndex])); if (state.GenericVarianceFlags != null) { Debug.Assert(state.GenericVarianceFlags.Length == instantiation.Length); state.HalfBakedRuntimeTypeHandle.SetGenericVariance(argIndex, state.GenericVarianceFlags[argIndex]); } } } FinishBaseTypeAndDictionaries(type, state); FinishInterfaces(type, state); FinishTypeDictionary(type, state); FinishClassConstructor(type, state); #if FEATURE_UNIVERSAL_GENERICS // For types that were allocated from universal canonical templates, patch their vtables with // pointers to calling convention conversion thunks if (state.TemplateType != null && state.TemplateType.IsCanonicalSubtype(CanonicalFormKind.Universal)) FinishVTableCallingConverterThunks(type, state); #endif } else if (type is ParameterizedType) { if (type is ArrayType) { ArrayType typeAsSzArrayType = (ArrayType)type; state.HalfBakedRuntimeTypeHandle.SetRelatedParameterType(GetRuntimeTypeHandle(typeAsSzArrayType.ElementType)); state.HalfBakedRuntimeTypeHandle.SetComponentSize(state.ComponentSize.Value); FinishInterfaces(type, state); if (typeAsSzArrayType.IsSzArray && !typeAsSzArrayType.ElementType.IsPointer) { FinishTypeDictionary(type, state); #if FEATURE_UNIVERSAL_GENERICS // For types that were allocated from universal canonical templates, patch their vtables with // pointers to calling convention conversion thunks if (state.TemplateType != null && state.TemplateType.IsCanonicalSubtype(CanonicalFormKind.Universal)) FinishVTableCallingConverterThunks(type, state); #endif } } else if (type is PointerType) { state.HalfBakedRuntimeTypeHandle.SetRelatedParameterType(GetRuntimeTypeHandle(((PointerType)type).ParameterType)); // Nothing else to do for pointer types } else if (type is ByRefType) { state.HalfBakedRuntimeTypeHandle.SetRelatedParameterType(GetRuntimeTypeHandle(((ByRefType)type).ParameterType)); // We used a pointer type for the template because they're similar enough. Adjust this to be a ByRef. unsafe { Debug.Assert(state.HalfBakedRuntimeTypeHandle.ToEETypePtr()->ParameterizedTypeShape == ParameterizedTypeShapeConstants.Pointer); state.HalfBakedRuntimeTypeHandle.SetParameterizedTypeShape(ParameterizedTypeShapeConstants.ByRef); Debug.Assert(state.HalfBakedRuntimeTypeHandle.ToEETypePtr()->ElementType == EETypeElementType.Pointer); state.HalfBakedRuntimeTypeHandle.ToEETypePtr()->Flags = EETypeBuilderHelpers.ComputeFlags(type); Debug.Assert(state.HalfBakedRuntimeTypeHandle.ToEETypePtr()->ElementType == EETypeElementType.ByRef); } } } else { Debug.Assert(false); } } private IEnumerable<TypeEntryToRegister> TypesToRegister() { for (int i = 0; i < _typesThatNeedTypeHandles.Count; i++) { DefType typeAsDefType = _typesThatNeedTypeHandles[i] as DefType; if (typeAsDefType == null) continue; if (typeAsDefType.HasInstantiation && !typeAsDefType.IsTypeDefinition) { yield return new TypeEntryToRegister { GenericTypeEntry = new GenericTypeEntry { _genericTypeDefinitionHandle = GetRuntimeTypeHandle(typeAsDefType.GetTypeDefinition()), _genericTypeArgumentHandles = GetRuntimeTypeHandles(typeAsDefType.Instantiation), _instantiatedTypeHandle = typeAsDefType.GetTypeBuilderState().HalfBakedRuntimeTypeHandle } }; } else { yield return new TypeEntryToRegister { MetadataDefinitionType = (MetadataType)typeAsDefType }; } } } private IEnumerable<GenericMethodEntry> MethodsToRegister() { for (int i = 0; i < _methodsThatNeedDictionaries.Count; i++) { InstantiatedMethod method = _methodsThatNeedDictionaries[i]; yield return new GenericMethodEntry { _declaringTypeHandle = GetRuntimeTypeHandle(method.OwningType), _genericMethodArgumentHandles = GetRuntimeTypeHandles(method.Instantiation), _methodNameAndSignature = method.NameAndSignature, _methodDictionary = method.RuntimeMethodDictionary }; } } private void RegisterGenericTypesAndMethods() { int typesToRegisterCount = 0; for (int i = 0; i < _typesThatNeedTypeHandles.Count; i++) { if (_typesThatNeedTypeHandles[i] is DefType) typesToRegisterCount++; } DynamicGenericsRegistrationData registrationData = new DynamicGenericsRegistrationData { TypesToRegisterCount = typesToRegisterCount, TypesToRegister = (typesToRegisterCount != 0) ? TypesToRegister() : null, MethodsToRegisterCount = _methodsThatNeedDictionaries.Count, MethodsToRegister = (_methodsThatNeedDictionaries.Count != 0) ? MethodsToRegister() : null, }; TypeLoaderEnvironment.Instance.RegisterDynamicGenericTypesAndMethods(registrationData); } /// <summary> /// Publish generic type / method information to the data buffer read by the debugger. This supports /// debugging dynamically created types / methods /// </summary> private void RegisterDebugDataForTypesAndMethods() { for (int i = 0; i < _typesThatNeedTypeHandles.Count; i++) { DefType typeAsDefType; if ((typeAsDefType = _typesThatNeedTypeHandles[i] as DefType) != null) { SerializedDebugData.RegisterDebugDataForType(this, typeAsDefType, typeAsDefType.GetTypeBuilderState()); } } for (int i = 0; i < _methodsThatNeedDictionaries.Count; i++) { SerializedDebugData.RegisterDebugDataForMethod(this, _methodsThatNeedDictionaries[i]); } } private void FinishTypeAndMethodBuilding() { // Once we start allocating EETypes and dictionaries, the only accepted failure is OOM. // TODO: Error handling - on retry, restart where we failed last time? The current implementation is leaking on OOM. #if DEBUG _finalTypeBuilding = true; #endif // At this point we know all types that need EETypes. Allocate all EETypes so that we can start building // their contents. for (int i = 0; i < _typesThatNeedTypeHandles.Count; i++) { AllocateRuntimeType(_typesThatNeedTypeHandles[i]); } for (int i = 0; i < _methodsThatNeedDictionaries.Count; i++) { AllocateRuntimeMethodDictionary(_methodsThatNeedDictionaries[i]); } // Do not add more type phases here. Instead, read the required information from the TypeDesc or TypeBuilderState. // Fill in content of all EETypes for (int i = 0; i < _typesThatNeedTypeHandles.Count; i++) { FinishRuntimeType(_typesThatNeedTypeHandles[i]); } for (int i = 0; i < _methodsThatNeedDictionaries.Count; i++) { FinishMethodDictionary(_methodsThatNeedDictionaries[i]); } RegisterDebugDataForTypesAndMethods(); int newArrayTypesCount = 0; int newPointerTypesCount = 0; int newByRefTypesCount = 0; int[] mdArrayNewTypesCount = null; for (int i = 0; i < _typesThatNeedTypeHandles.Count; i++) { ParameterizedType typeAsParameterizedType = _typesThatNeedTypeHandles[i] as ParameterizedType; if (typeAsParameterizedType == null) continue; if (typeAsParameterizedType.IsSzArray) newArrayTypesCount++; else if (typeAsParameterizedType.IsPointer) newPointerTypesCount++; else if (typeAsParameterizedType.IsByRef) newByRefTypesCount++; else if (typeAsParameterizedType.IsMdArray) { if (mdArrayNewTypesCount == null) mdArrayNewTypesCount = new int[MDArray.MaxRank + 1]; mdArrayNewTypesCount[((ArrayType)typeAsParameterizedType).Rank]++; } } // Reserve space in array/pointer cache's so that the actual adding can be fault-free. var szArrayCache = TypeSystemContext.GetArrayTypesCache(false, -1); szArrayCache.Reserve(szArrayCache.Count + newArrayTypesCount); // if (mdArrayNewTypesCount != null) { for (int i = 0; i < mdArrayNewTypesCount.Length; i++) { if (mdArrayNewTypesCount[i] == 0) continue; var mdArrayCache = TypeSystemContext.GetArrayTypesCache(true, i); mdArrayCache.Reserve(mdArrayCache.Count + mdArrayNewTypesCount[i]); } } TypeSystemContext.PointerTypesCache.Reserve(TypeSystemContext.PointerTypesCache.Count + newPointerTypesCount); TypeSystemContext.ByRefTypesCache.Reserve(TypeSystemContext.ByRefTypesCache.Count + newByRefTypesCount); // Finally, register all generic types and methods atomically with the runtime RegisterGenericTypesAndMethods(); for (int i = 0; i < _typesThatNeedTypeHandles.Count; i++) { _typesThatNeedTypeHandles[i].SetRuntimeTypeHandleUnsafe(_typesThatNeedTypeHandles[i].GetTypeBuilderState().HalfBakedRuntimeTypeHandle); TypeLoaderLogger.WriteLine("Successfully Registered type " + _typesThatNeedTypeHandles[i].ToString() + "."); } // Save all constructed array and pointer types to the types cache for (int i = 0; i < _typesThatNeedTypeHandles.Count; i++) { ParameterizedType typeAsParameterizedType = _typesThatNeedTypeHandles[i] as ParameterizedType; if (typeAsParameterizedType == null) continue; Debug.Assert(!typeAsParameterizedType.RuntimeTypeHandle.IsNull()); Debug.Assert(!typeAsParameterizedType.ParameterType.RuntimeTypeHandle.IsNull()); if (typeAsParameterizedType.IsMdArray) TypeSystemContext.GetArrayTypesCache(true, ((ArrayType)typeAsParameterizedType).Rank).AddOrGetExisting(typeAsParameterizedType.RuntimeTypeHandle); else if (typeAsParameterizedType.IsSzArray) TypeSystemContext.GetArrayTypesCache(false, -1).AddOrGetExisting(typeAsParameterizedType.RuntimeTypeHandle); else if (typeAsParameterizedType.IsByRef) { unsafe { Debug.Assert(typeAsParameterizedType.RuntimeTypeHandle.ToEETypePtr()->IsByRefType); } TypeSystemContext.ByRefTypesCache.AddOrGetExisting(typeAsParameterizedType.RuntimeTypeHandle); } else { Debug.Assert(typeAsParameterizedType is PointerType); unsafe { Debug.Assert(typeAsParameterizedType.RuntimeTypeHandle.ToEETypePtr()->IsPointerType); } TypeSystemContext.PointerTypesCache.AddOrGetExisting(typeAsParameterizedType.RuntimeTypeHandle); } } } internal void BuildType(TypeDesc type) { TypeLoaderLogger.WriteLine("Dynamically allocating new type for " + type.ToString()); // Construct a new type along with all the dependencies that are needed to create interface lists, // generic dictionaries, etc. // Start by collecting all dependencies we need to create in order to create this type. PrepareType(type); // Process the pending types ProcessTypesNeedingPreparation(); FinishTypeAndMethodBuilding(); } internal static bool TryComputeFieldOffset(DefType declaringType, uint fieldOrdinal, out int fieldOffset) { TypeLoaderLogger.WriteLine("Computing offset of field #" + fieldOrdinal.LowLevelToString() + " on type " + declaringType.ToString()); // Get the computed field offset result LayoutInt layoutFieldOffset = declaringType.GetFieldByNativeLayoutOrdinal(fieldOrdinal).Offset; if (layoutFieldOffset.IsIndeterminate) { fieldOffset = 0; return false; } fieldOffset = layoutFieldOffset.AsInt; return true; } private void BuildMethod(InstantiatedMethod method) { TypeLoaderLogger.WriteLine("Dynamically allocating new method instantiation for " + method.ToString()); // Start by collecting all dependencies we need to create in order to create this method. PrepareMethod(method); // Process the pending types ProcessTypesNeedingPreparation(); FinishTypeAndMethodBuilding(); } private static DefType GetExactDeclaringType(DefType srcDefType, DefType dstDefType) { while (srcDefType != null) { if (srcDefType.HasSameTypeDefinition(dstDefType)) return srcDefType; srcDefType = srcDefType.BaseType; } Debug.Assert(false); return null; } // // This method is used by the lazy generic lookup. It resolves the signature of the runtime artifact in the given instantiation context. // private unsafe IntPtr BuildGenericLookupTarget(TypeSystemContext typeSystemContext, IntPtr context, IntPtr signature, out IntPtr auxResult) { TypeLoaderLogger.WriteLine("BuildGenericLookupTarget for " + context.LowLevelToString() + "/" + signature.LowLevelToString()); TypeManagerHandle typeManager; NativeReader reader; uint offset; // The first is a pointer that points to the TypeManager indirection cell. // The second is the offset into the native layout info blob in that TypeManager, where the native signature is encoded. IntPtr** lazySignature = (IntPtr**)signature.ToPointer(); typeManager = new TypeManagerHandle(lazySignature[0][0]); offset = checked((uint)new IntPtr(lazySignature[1]).ToInt32()); reader = TypeLoaderEnvironment.GetNativeLayoutInfoReader(typeManager); NativeParser parser = new NativeParser(reader, offset); GenericContextKind contextKind = (GenericContextKind)parser.GetUnsigned(); NativeFormatModuleInfo moduleInfo = ModuleList.Instance.GetModuleInfoByHandle(typeManager); NativeLayoutInfoLoadContext nlilContext = new NativeLayoutInfoLoadContext(); nlilContext._module = moduleInfo; nlilContext._typeSystemContext = typeSystemContext; #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING NativeFormatMetadataUnit metadataUnit = null; if (moduleInfo.ModuleType == ModuleType.ReadyToRun) metadataUnit = typeSystemContext.ResolveMetadataUnit(moduleInfo); #endif if ((contextKind & GenericContextKind.FromMethodHiddenArg) != 0) { RuntimeTypeHandle declaringTypeHandle; MethodNameAndSignature nameAndSignature; RuntimeTypeHandle[] genericMethodArgHandles; bool success = TypeLoaderEnvironment.Instance.TryGetGenericMethodComponents(context, out declaringTypeHandle, out nameAndSignature, out genericMethodArgHandles); Debug.Assert(success); if (RuntimeAugments.IsGenericType(declaringTypeHandle)) { DefType declaringType = (DefType)typeSystemContext.ResolveRuntimeTypeHandle(declaringTypeHandle); nlilContext._typeArgumentHandles = declaringType.Instantiation; } nlilContext._methodArgumentHandles = typeSystemContext.ResolveRuntimeTypeHandles(genericMethodArgHandles); } else { TypeDesc typeContext = typeSystemContext.ResolveRuntimeTypeHandle(RuntimeAugments.CreateRuntimeTypeHandle(context)); if (typeContext is DefType) { nlilContext._typeArgumentHandles = ((DefType)typeContext).Instantiation; } else if (typeContext is ArrayType) { nlilContext._typeArgumentHandles = new Instantiation(new TypeDesc[] { ((ArrayType)typeContext).ElementType }); } else { Debug.Assert(false); } if ((contextKind & GenericContextKind.HasDeclaringType) != 0) { // No need to deal with arrays - arrays can't have declaring type TypeDesc declaringType; if (moduleInfo.ModuleType == ModuleType.Eager) { declaringType = nlilContext.GetType(ref parser); } else { Debug.Assert(moduleInfo.ModuleType == ModuleType.ReadyToRun); #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING uint typeToken = parser.GetUnsigned(); declaringType = metadataUnit.GetType(((int)typeToken).AsHandle()); #else Environment.FailFast("Ready to Run module type?"); declaringType = null; #endif } DefType actualContext = GetExactDeclaringType((DefType)typeContext, (DefType)declaringType); nlilContext._typeArgumentHandles = actualContext.Instantiation; } } if ((contextKind & GenericContextKind.NeedsUSGContext) != 0) { IntPtr genericDictionary; auxResult = IntPtr.Zero; // There is a cache in place so that this function doesn't get called much, but we still need a registration store, // so we don't leak allocated contexts if (TypeLoaderEnvironment.Instance.TryLookupConstructedLazyDictionaryForContext(context, signature, out genericDictionary)) { return genericDictionary; } GenericTypeDictionary ucgDict; if (moduleInfo.ModuleType == ModuleType.Eager) { ucgDict = new GenericTypeDictionary(GenericDictionaryCell.BuildDictionary(this, nlilContext, parser)); } else { #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING Debug.Assert(moduleInfo.ModuleType == ModuleType.ReadyToRun); FixupCellMetadataResolver metadataResolver = new FixupCellMetadataResolver(metadataUnit, nlilContext); ucgDict = new GenericTypeDictionary(GenericDictionaryCell.BuildDictionaryFromMetadataTokensAndContext(this, parser, metadataUnit, metadataResolver)); #else Environment.FailFast("Ready to Run module type?"); ucgDict = null; #endif } genericDictionary = ucgDict.Allocate(); // Process the pending types ProcessTypesNeedingPreparation(); FinishTypeAndMethodBuilding(); ucgDict.Finish(this); TypeLoaderEnvironment.Instance.RegisterConstructedLazyDictionaryForContext(context, signature, genericDictionary); return genericDictionary; } else { GenericDictionaryCell cell; if (moduleInfo.ModuleType == ModuleType.Eager) { cell = GenericDictionaryCell.ParseAndCreateCell( nlilContext, ref parser); } else { Debug.Assert(moduleInfo.ModuleType == ModuleType.ReadyToRun); #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING MetadataFixupKind fixupKind = (MetadataFixupKind)parser.GetUInt8(); Internal.Metadata.NativeFormat.Handle token = parser.GetUnsigned().AsHandle(); Internal.Metadata.NativeFormat.Handle token2 = default(Internal.Metadata.NativeFormat.Handle); switch (fixupKind) { case MetadataFixupKind.GenericConstrainedMethod: case MetadataFixupKind.NonGenericConstrainedMethod: case MetadataFixupKind.NonGenericDirectConstrainedMethod: token2 = parser.GetUnsigned().AsHandle(); break; } FixupCellMetadataResolver resolver = new FixupCellMetadataResolver(metadataUnit, nlilContext); cell = GenericDictionaryCell.CreateCellFromFixupKindAndToken(fixupKind, resolver, token, token2); #else Environment.FailFast("Ready to Run module type?"); cell = null; #endif } cell.Prepare(this); // Process the pending types ProcessTypesNeedingPreparation(); FinishTypeAndMethodBuilding(); IntPtr dictionaryCell = cell.CreateLazyLookupCell(this, out auxResult); return dictionaryCell; } } // // This method is used to build the floating portion of a generic dictionary. // private unsafe IntPtr BuildFloatingDictionary(TypeSystemContext typeSystemContext, IntPtr context, bool isTypeContext, IntPtr fixedDictionary, out bool isNewlyAllocatedDictionary) { isNewlyAllocatedDictionary = true; NativeParser nativeLayoutParser; NativeLayoutInfoLoadContext nlilContext; if (isTypeContext) { TypeDesc typeContext = typeSystemContext.ResolveRuntimeTypeHandle(*(RuntimeTypeHandle*)&context); TypeLoaderLogger.WriteLine("Building floating dictionary layout for type " + typeContext.ToString() + "..."); // We should only perform updates to floating dictionaries for types that share normal canonical code Debug.Assert(typeContext.CanShareNormalGenericCode()); // Computing the template will throw if no template is found. typeContext.ComputeTemplate(); TypeBuilderState state = typeContext.GetOrCreateTypeBuilderState(); nativeLayoutParser = state.GetParserForNativeLayoutInfo(); nlilContext = state.NativeLayoutInfo.LoadContext; } else { RuntimeTypeHandle declaringTypeHandle; MethodNameAndSignature nameAndSignature; RuntimeTypeHandle[] genericMethodArgHandles; bool success = TypeLoaderEnvironment.Instance.TryGetGenericMethodComponents(context, out declaringTypeHandle, out nameAndSignature, out genericMethodArgHandles); Debug.Assert(success); DefType declaringType = (DefType)typeSystemContext.ResolveRuntimeTypeHandle(declaringTypeHandle); InstantiatedMethod methodContext = (InstantiatedMethod)typeSystemContext.ResolveGenericMethodInstantiation( false, declaringType, nameAndSignature, typeSystemContext.ResolveRuntimeTypeHandles(genericMethodArgHandles), IntPtr.Zero, false); TypeLoaderLogger.WriteLine("Building floating dictionary layout for method " + methodContext.ToString() + "..."); // We should only perform updates to floating dictionaries for gemeric methods that share normal canonical code Debug.Assert(!methodContext.IsNonSharableMethod); uint nativeLayoutInfoToken; NativeFormatModuleInfo nativeLayoutModule; MethodDesc templateMethod = TemplateLocator.TryGetGenericMethodTemplate(methodContext, out nativeLayoutModule, out nativeLayoutInfoToken); if (templateMethod == null) throw new TypeBuilder.MissingTemplateException(); NativeReader nativeLayoutInfoReader = TypeLoaderEnvironment.GetNativeLayoutInfoReader(nativeLayoutModule.Handle); nativeLayoutParser = new NativeParser(nativeLayoutInfoReader, nativeLayoutInfoToken); nlilContext = new NativeLayoutInfoLoadContext { _typeSystemContext = methodContext.Context, _typeArgumentHandles = methodContext.OwningType.Instantiation, _methodArgumentHandles = methodContext.Instantiation, _module = nativeLayoutModule }; } NativeParser dictionaryLayoutParser = nativeLayoutParser.GetParserForBagElementKind(BagElementKind.DictionaryLayout); if (dictionaryLayoutParser.IsNull) return IntPtr.Zero; int floatingVersionCellIndex, floatingVersionInLayout; GenericDictionaryCell[] floatingCells = GenericDictionaryCell.BuildFloatingDictionary(this, nlilContext, dictionaryLayoutParser, out floatingVersionCellIndex, out floatingVersionInLayout); if (floatingCells == null) return IntPtr.Zero; // If the floating section is already constructed, then return. This means we are beaten by another thread. if (*((IntPtr*)fixedDictionary) != IntPtr.Zero) { isNewlyAllocatedDictionary = false; return *((IntPtr*)fixedDictionary); } GenericTypeDictionary floatingDict = new GenericTypeDictionary(floatingCells); IntPtr result = floatingDict.Allocate(); ProcessTypesNeedingPreparation(); FinishTypeAndMethodBuilding(); floatingDict.Finish(this); return result; } public static bool TryBuildGenericType(RuntimeTypeHandle genericTypeDefinitionHandle, RuntimeTypeHandle[] genericTypeArgumentHandles, out RuntimeTypeHandle runtimeTypeHandle) { Debug.Assert(!genericTypeDefinitionHandle.IsNull() && genericTypeArgumentHandles != null && genericTypeArgumentHandles.Length > 0); try { TypeSystemContext context = TypeSystemContextFactory.Create(); DefType genericDef = (DefType)context.ResolveRuntimeTypeHandle(genericTypeDefinitionHandle); Instantiation genericArgs = context.ResolveRuntimeTypeHandles(genericTypeArgumentHandles); DefType typeBeingLoaded = context.ResolveGenericInstantiation(genericDef, genericArgs); new TypeBuilder().BuildType(typeBeingLoaded); runtimeTypeHandle = typeBeingLoaded.RuntimeTypeHandle; Debug.Assert(!runtimeTypeHandle.IsNull()); // Recycle the context only if we succesfully built the type. The state may be partially initialized otherwise. TypeSystemContextFactory.Recycle(context); return true; } catch (MissingTemplateException) { runtimeTypeHandle = default(RuntimeTypeHandle); return false; } } public static bool TryBuildArrayType(RuntimeTypeHandle elementTypeHandle, bool isMdArray, int rank, out RuntimeTypeHandle arrayTypeHandle) { try { TypeSystemContext context = TypeSystemContextFactory.Create(); TypeDesc elementType = context.ResolveRuntimeTypeHandle(elementTypeHandle); ArrayType arrayType = (ArrayType)context.GetArrayType(elementType, !isMdArray ? -1 : rank); new TypeBuilder().BuildType(arrayType); arrayTypeHandle = arrayType.RuntimeTypeHandle; Debug.Assert(!arrayTypeHandle.IsNull()); // Recycle the context only if we succesfully built the type. The state may be partially initialized otherwise. TypeSystemContextFactory.Recycle(context); return true; } catch (MissingTemplateException) { arrayTypeHandle = default(RuntimeTypeHandle); return false; } } public static bool TryBuildPointerType(RuntimeTypeHandle pointeeTypeHandle, out RuntimeTypeHandle pointerTypeHandle) { if (!TypeSystemContext.PointerTypesCache.TryGetValue(pointeeTypeHandle, out pointerTypeHandle)) { TypeSystemContext context = TypeSystemContextFactory.Create(); TypeDesc pointerType = context.GetPointerType(context.ResolveRuntimeTypeHandle(pointeeTypeHandle)); pointerTypeHandle = EETypeCreator.CreatePointerEEType((uint)pointerType.GetHashCode(), pointeeTypeHandle, pointerType); unsafe { Debug.Assert(pointerTypeHandle.ToEETypePtr()->IsPointerType); } TypeSystemContext.PointerTypesCache.AddOrGetExisting(pointerTypeHandle); // Recycle the context only if we succesfully built the type. The state may be partially initialized otherwise. TypeSystemContextFactory.Recycle(context); } return true; } public static bool TryBuildByRefType(RuntimeTypeHandle pointeeTypeHandle, out RuntimeTypeHandle byRefTypeHandle) { if (!TypeSystemContext.ByRefTypesCache.TryGetValue(pointeeTypeHandle, out byRefTypeHandle)) { TypeSystemContext context = TypeSystemContextFactory.Create(); TypeDesc byRefType = context.GetByRefType(context.ResolveRuntimeTypeHandle(pointeeTypeHandle)); byRefTypeHandle = EETypeCreator.CreateByRefEEType((uint)byRefType.GetHashCode(), pointeeTypeHandle, byRefType); unsafe { Debug.Assert(byRefTypeHandle.ToEETypePtr()->IsByRefType); } TypeSystemContext.ByRefTypesCache.AddOrGetExisting(byRefTypeHandle); // Recycle the context only if we succesfully built the type. The state may be partially initialized otherwise. TypeSystemContextFactory.Recycle(context); } return true; } public static bool TryBuildGenericMethod(RuntimeTypeHandle declaringTypeHandle, RuntimeTypeHandle[] genericMethodArgHandles, MethodNameAndSignature methodNameAndSignature, out IntPtr methodDictionary) { TypeSystemContext context = TypeSystemContextFactory.Create(); DefType declaringType = (DefType)context.ResolveRuntimeTypeHandle(declaringTypeHandle); InstantiatedMethod methodBeingLoaded = (InstantiatedMethod)context.ResolveGenericMethodInstantiation(false, declaringType, methodNameAndSignature, context.ResolveRuntimeTypeHandles(genericMethodArgHandles), IntPtr.Zero, false); bool success = TryBuildGenericMethod(methodBeingLoaded, out methodDictionary); // Recycle the context only if we succesfully built the method. The state may be partially initialized otherwise. if (success) TypeSystemContextFactory.Recycle(context); return success; } internal static bool TryBuildGenericMethod(InstantiatedMethod methodBeingLoaded, out IntPtr methodDictionary) { try { new TypeBuilder().BuildMethod(methodBeingLoaded); methodDictionary = methodBeingLoaded.RuntimeMethodDictionary; Debug.Assert(methodDictionary != IntPtr.Zero); return true; } catch (MissingTemplateException) { methodDictionary = IntPtr.Zero; return false; } } private void ResolveSingleCell_Worker(GenericDictionaryCell cell, out IntPtr fixupResolution) { cell.Prepare(this); // Process the pending types ProcessTypesNeedingPreparation(); FinishTypeAndMethodBuilding(); // At this stage the pointer we need is accessible via a call to Create on the prepared cell fixupResolution = cell.Create(this); } private void ResolveMultipleCells_Worker(GenericDictionaryCell[] cells, out IntPtr[] fixups) { foreach (var cell in cells) { cell.Prepare(this); } // Process the pending types ProcessTypesNeedingPreparation(); FinishTypeAndMethodBuilding(); // At this stage the pointer we need is accessible via a call to Create on the prepared cell fixups = new IntPtr[cells.Length]; for (int i = 0; i < fixups.Length; i++) fixups[i] = cells[i].Create(this); } #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING private void ResolveSingleMetadataFixup(NativeFormatMetadataUnit module, Handle token, MetadataFixupKind fixupKind, out IntPtr fixupResolution) { FixupCellMetadataResolver metadata = new FixupCellMetadataResolver(module); // Allocate a cell object to represent the fixup, and prepare it GenericDictionaryCell cell = GenericDictionaryCell.CreateCellFromFixupKindAndToken(fixupKind, metadata, token, default(Handle)); ResolveSingleCell_Worker(cell, out fixupResolution); } public static bool TryResolveSingleMetadataFixup(NativeFormatModuleInfo module, int metadataToken, MetadataFixupKind fixupKind, out IntPtr fixupResolution) { TypeSystemContext context = TypeSystemContextFactory.Create(); NativeFormatMetadataUnit metadataUnit = context.ResolveMetadataUnit(module); new TypeBuilder().ResolveSingleMetadataFixup(metadataUnit, metadataToken.AsHandle(), fixupKind, out fixupResolution); TypeSystemContextFactory.Recycle(context); return true; } public static void ResolveSingleTypeDefinition(QTypeDefinition qTypeDefinition, out IntPtr typeHandle) { TypeSystemContext context = TypeSystemContextFactory.Create(); TypeDesc type = context.GetTypeDescFromQHandle(qTypeDefinition); GenericDictionaryCell cell = GenericDictionaryCell.CreateTypeHandleCell(type); new TypeBuilder().ResolveSingleCell_Worker(cell, out typeHandle); TypeSystemContextFactory.Recycle(context); } #endif internal static void ResolveSingleCell(GenericDictionaryCell cell, out IntPtr fixupResolution) { new TypeBuilder().ResolveSingleCell_Worker(cell, out fixupResolution); } public static void ResolveMultipleCells(GenericDictionaryCell [] cells, out IntPtr[] fixups) { new TypeBuilder().ResolveMultipleCells_Worker(cells, out fixups); } public static IntPtr BuildGenericLookupTarget(IntPtr typeContext, IntPtr signature, out IntPtr auxResult) { try { TypeSystemContext context = TypeSystemContextFactory.Create(); IntPtr ret = new TypeBuilder().BuildGenericLookupTarget(context, typeContext, signature, out auxResult); TypeSystemContextFactory.Recycle(context); return ret; } catch (MissingTemplateException e) { // This should not ever happen. The static compiler should ensure that the templates are always // available for types and methods referenced by lazy dictionary lookups Environment.FailFast("MissingTemplateException thrown during lazy generic lookup", e); auxResult = IntPtr.Zero; return IntPtr.Zero; } } public static bool TryGetFieldOffset(RuntimeTypeHandle declaringTypeHandle, uint fieldOrdinal, out int fieldOffset) { try { TypeSystemContext context = TypeSystemContextFactory.Create(); DefType declaringType = (DefType)context.ResolveRuntimeTypeHandle(declaringTypeHandle); Debug.Assert(declaringType.HasInstantiation); bool success = TypeBuilder.TryComputeFieldOffset(declaringType, fieldOrdinal, out fieldOffset); TypeSystemContextFactory.Recycle(context); return success; } catch (MissingTemplateException) { fieldOffset = int.MinValue; return false; } } internal static bool TryGetDelegateInvokeMethodSignature(RuntimeTypeHandle delegateTypeHandle, out RuntimeSignature signature) { signature = default(RuntimeSignature); bool success = false; TypeSystemContext context = TypeSystemContextFactory.Create(); DefType delegateType = (DefType)context.ResolveRuntimeTypeHandle(delegateTypeHandle); Debug.Assert(delegateType.HasInstantiation); NativeLayoutInfo universalLayoutInfo; NativeParser parser = delegateType.GetOrCreateTypeBuilderState().GetParserForUniversalNativeLayoutInfo(out _, out universalLayoutInfo); if (!parser.IsNull) { NativeParser sigParser = parser.GetParserForBagElementKind(BagElementKind.DelegateInvokeSignature); if (!sigParser.IsNull) { signature = RuntimeSignature.CreateFromNativeLayoutSignature(universalLayoutInfo.Module.Handle, sigParser.Offset); success = true; } } TypeSystemContextFactory.Recycle(context); return success; } // // This method is used to build the floating portion of a generic dictionary. // internal static IntPtr TryBuildFloatingDictionary(IntPtr context, bool isTypeContext, IntPtr fixedDictionary, out bool isNewlyAllocatedDictionary) { isNewlyAllocatedDictionary = true; try { TypeSystemContext typeSystemContext = TypeSystemContextFactory.Create(); IntPtr ret = new TypeBuilder().BuildFloatingDictionary(typeSystemContext, context, isTypeContext, fixedDictionary, out isNewlyAllocatedDictionary); TypeSystemContextFactory.Recycle(typeSystemContext); return ret; } catch (MissingTemplateException e) { // This should not ever happen. The static compiler should ensure that the templates are always // available for types and methods that have floating dictionaries Environment.FailFast("MissingTemplateException thrown during dictionary update", e); return IntPtr.Zero; } } } }
47.710689
274
0.615792
[ "MIT" ]
AlexanderSemenyak/runtime
src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilder.cs
108,017
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.261 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace OutlookAutoRules.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
39.592593
151
0.582788
[ "MIT" ]
dcorns/OutlookAutoRules
OutlookAutoRules/Properties/Settings.Designer.cs
1,071
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace NetOffice.OfficeApi.Tools.Dialogs { /// <summary> /// Shows error information to the user /// </summary> public partial class ErrorDialog : ToolsDialog { #region Embeded Definitions /// <summary> /// Encapsulate an exception to show them as easy /// </summary> private class ErrorDescription { #region Fields private Exception _exception; #endregion #region Ctor /// <summary> /// Creates an instance of the class /// </summary> /// <param name="exception">top level exception to display</param> internal ErrorDescription(Exception exception) { _exception = exception; Message = null != exception ? exception.Message : String.Empty; Type = null != exception ? exception.GetType().Name : String.Empty; Source = null != exception && null != exception.TargetSite ? exception.TargetSite.ToString() : String.Empty; } #endregion #region Properties /// <summary> /// Exception Message /// </summary> public string Message { get; private set; } /// <summary> /// Type of Exception /// </summary> public string Type { get; private set; } /// <summary> /// Source/Scope from the Exception /// </summary> public string Source { get; private set; } #endregion #region Methods /// <summary> /// Create enumerator for given exception and all inner exception /// </summary> /// <param name="exception">last exception in stack</param> /// <returns>enumerator to iterate the errors</returns> internal static IEnumerable<ErrorDescription> CreateList(Exception exception) { List<ErrorDescription> list = new List<ErrorDescription>(); while (null != exception) { ErrorDescription error = new ErrorDescription(exception); list.Add(error); exception = exception.InnerException; } return list; } #endregion #region Overrides /// <summary> /// Returns a System.String that represents the instance /// </summary> /// <returns>System.String</returns> public override string ToString() { return null != _exception ? _exception.ToString() : base.ToString(); } #endregion } #endregion #region Fields private const int _minimumWidth = 540; private const int _smallHeight = 210; private const int _extendedHeight = 500; private const string _errorMessageTemplate = "%ErrorMessage"; #endregion #region Ctor /// <summary> /// Creates an instance of the class /// </summary> public ErrorDialog() { InitializeComponent(); } /// <summary> /// Creates an instance of the class /// </summary> /// <param name="exception">thrown exception to display</param> /// <param name="errorMessage">friendly error message to explain what happen</param> /// <param name="allowDetails">allow user to see exception details</param> public ErrorDialog(Exception exception, string errorMessage, bool allowDetails) { InitializeComponent(); buttonShowDetails.Visible = allowDetails; Height = _smallHeight; labelErrorMessage.Text = _errorMessageTemplate; dataGridViewErrors.AutoGenerateColumns = false; if (!String.IsNullOrEmpty(errorMessage)) labelErrorMessage.Text = errorMessage; dataGridViewErrors.DataSource = ErrorDescription.CreateList(exception); Height = _smallHeight; } #endregion #region Overrides /// <summary> /// <see cref="ToolsDialog.DoLocalization"/> /// </summary> /// <param name="localization">localized values</param> protected internal override void DoLocalization(DialogLocalization localization) { Text = localization["Title", Text]; labelErrorHeader.Text = localization["ErrorHeader", labelErrorHeader.Text]; if (labelErrorMessage.Text.Equals(_errorMessageTemplate, StringComparison.InvariantCultureIgnoreCase)) labelErrorMessage.Text = localization["ErrorMessage", ""]; colMessage.HeaderText = localization["Message", colMessage.HeaderText]; colType.HeaderText = localization["Type", colType.HeaderText]; colSource.HeaderText = localization["Source", colSource.HeaderText]; buttonShowDetails.Text = localization["buttonShowDetails", buttonShowDetails.Text]; buttonClose.Text = localization["buttonClose", buttonClose.Text]; buttonClipboardCopy.Text = localization["buttonClipboardCopy", buttonClipboardCopy.Text]; } /// <summary> /// <see cref="ToolsDialog.DoLayout"/> /// </summary> /// <param name="layout">layout settings</param> protected internal override void DoLayout(DialogLayoutSettings layout) { dataGridViewErrors.BackgroundColor = layout.BackHeaderColor; dataGridViewErrors.ColumnHeadersDefaultCellStyle.BackColor = layout.BackColor; dataGridViewErrors.ColumnHeadersDefaultCellStyle.ForeColor = layout.ForeAlternateColor; base.DoLayout(layout); } #endregion #region Methods private void ShowSingleException(ErrorDescription error) { MessageBox.Show(this, error.ToString(), Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } private void CopyErrorInfoToClipboard(IEnumerable<ErrorDescription> errors) { StringBuilder builder = new StringBuilder(); foreach (ErrorDescription item in errors) builder.AppendLine(String.Format("{0};{1};{2}{4}{3}{4}", item.Type, item.Source, item.Message, item.ToString(), Environment.NewLine)); Clipboard.SetData(DataFormats.Text, builder.ToString()); } #endregion #region Trigger private void dataGridViewErrors_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { try { if (dataGridViewErrors.SelectedCells.Count == 0) return; ErrorDescription selectedItem = dataGridViewErrors.Rows[dataGridViewErrors.SelectedCells[0].RowIndex].DataBoundItem as ErrorDescription; if (null != selectedItem) ShowSingleException(selectedItem); } catch (Exception exception) { ShowSingleException(exception); } } private void buttonShowDetails_Click(object sender, EventArgs e) { try { buttonShowDetails.Enabled = false; FormBorderStyle = FormBorderStyle.Sizable; Height = _extendedHeight; MinimumSize = new System.Drawing.Size(_minimumWidth, _extendedHeight); buttonShowDetails.Enabled = false; dataGridViewErrors.Visible = true; buttonClipboardCopy.Visible = true; } catch (Exception exception) { ShowSingleException(exception); } } private void buttonClipboardCopy_Click(object sender, EventArgs e) { try { IEnumerable<ErrorDescription> list = dataGridViewErrors.DataSource as IEnumerable<ErrorDescription>; if (null == list) return; CopyErrorInfoToClipboard(list); } catch (Exception exception) { ShowSingleException(exception); } } private void buttonClose_Click(object sender, EventArgs e) { try { Close(); } catch (Exception exception) { ShowSingleException(exception); } } #endregion } }
33.737643
152
0.569593
[ "MIT" ]
DominikPalo/NetOffice
Source/Office/Tools/Dialogs/ErrorDialog.cs
8,875
C#
/**** * Created by: Coleton Wheeler * Date Created: April 24, 2022 * * Last Edited by: * Last Edited: * * Description: AI Logic Handling ****/ using System.Collections; using System.Collections.Generic; using UnityEngine; public class AIScript : MonoBehaviour { public float delayBeforePlay = 2f; public int playerNumber; private float timeSinceTurn = 0f; private GameManager gm; private int numBundleCards = 0; private int numAnimalCards = 0; void Awake() { gm = GameManager.GM; } // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (gm.playerTurn == playerNumber) { timeSinceTurn += Time.deltaTime; if (timeSinceTurn > delayBeforePlay) { int random = Random.Range(0, 100); UpdateInventoryStats(); if (random > 80 && numBundleCards < 3) { Debug.Log("Player " + playerNumber + " took a bundle card " + Time.time); numBundleCards++; //SCRIPT TO TAKE A BUNDLE CARD ONCE IMPLEMENTED } else if (numAnimalCards < 7) { Debug.Log("Player " + playerNumber + " took an animal card " + Time.time); int randomIndex = Random.Range(0, gm.board.GetComponent<DrawArea>().CurrentBoardCards.Length); GameObject currentCard = gm.board.GetComponent<DrawArea>().CurrentBoardCards[randomIndex]; currentCard.GetComponent<HoverScript>().TakeCard(this.gameObject); numAnimalCards++; if (numAnimalCards == 7) { gm.NextTurn(); return; } int randomIndex2 = randomIndex; while ((randomIndex2 = Random.Range(0, 8)) == randomIndex) { } currentCard = gm.board.GetComponent<DrawArea>().CurrentBoardCards[randomIndex2]; currentCard.GetComponent<HoverScript>().TakeCard(this.gameObject); } else { Debug.Log("Player " + playerNumber + " discarded an animal card " + Time.time); transform.GetComponent<Inventory>().RemoveCard(Random.Range(0, 7)); } gm.NextTurn(); } } else { timeSinceTurn = 0f; } } void UpdateInventoryStats() { numAnimalCards = 0; numBundleCards = 0; foreach (GameObject bundle in transform.GetComponent<Inventory>().bundleInvtory) { if (bundle != null) { numBundleCards++; } } foreach (GameObject card in transform.GetComponent<Inventory>().cardInventory) { if (card != null) { numAnimalCards++; } } } }
27.128205
114
0.501575
[ "MIT" ]
Doggitoz/Rename
Oppozootion Unity/Assets/Scripts/AIScript.cs
3,174
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Logic.Models { using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using System.Linq; /// <summary> /// The workflow trigger history. /// </summary> [Rest.Serialization.JsonTransformation] public partial class WorkflowTriggerHistory : SubResource { /// <summary> /// Initializes a new instance of the WorkflowTriggerHistory class. /// </summary> public WorkflowTriggerHistory() { CustomInit(); } /// <summary> /// Initializes a new instance of the WorkflowTriggerHistory class. /// </summary> /// <param name="id">The resource id.</param> /// <param name="startTime">Gets the start time.</param> /// <param name="endTime">Gets the end time.</param> /// <param name="status">Gets the status. Possible values include: /// 'NotSpecified', 'Paused', 'Running', 'Waiting', 'Succeeded', /// 'Skipped', 'Suspended', 'Cancelled', 'Failed', 'Faulted', /// 'TimedOut', 'Aborted', 'Ignored'</param> /// <param name="code">Gets the code.</param> /// <param name="error">Gets the error.</param> /// <param name="trackingId">Gets the tracking id.</param> /// <param name="correlation">The run correlation.</param> /// <param name="inputsLink">Gets the link to input parameters.</param> /// <param name="outputsLink">Gets the link to output /// parameters.</param> /// <param name="fired">Gets a value indicating whether trigger was /// fired.</param> /// <param name="run">Gets the reference to workflow run.</param> /// <param name="name">Gets the workflow trigger history name.</param> /// <param name="type">Gets the workflow trigger history type.</param> public WorkflowTriggerHistory(string id = default(string), System.DateTime? startTime = default(System.DateTime?), System.DateTime? endTime = default(System.DateTime?), string status = default(string), string code = default(string), object error = default(object), string trackingId = default(string), Correlation correlation = default(Correlation), ContentLink inputsLink = default(ContentLink), ContentLink outputsLink = default(ContentLink), bool? fired = default(bool?), ResourceReference run = default(ResourceReference), string name = default(string), string type = default(string)) : base(id) { StartTime = startTime; EndTime = endTime; Status = status; Code = code; Error = error; TrackingId = trackingId; Correlation = correlation; InputsLink = inputsLink; OutputsLink = outputsLink; Fired = fired; Run = run; Name = name; Type = type; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets the start time. /// </summary> [JsonProperty(PropertyName = "properties.startTime")] public System.DateTime? StartTime { get; private set; } /// <summary> /// Gets the end time. /// </summary> [JsonProperty(PropertyName = "properties.endTime")] public System.DateTime? EndTime { get; private set; } /// <summary> /// Gets the status. Possible values include: 'NotSpecified', 'Paused', /// 'Running', 'Waiting', 'Succeeded', 'Skipped', 'Suspended', /// 'Cancelled', 'Failed', 'Faulted', 'TimedOut', 'Aborted', 'Ignored' /// </summary> [JsonProperty(PropertyName = "properties.status")] public string Status { get; private set; } /// <summary> /// Gets the code. /// </summary> [JsonProperty(PropertyName = "properties.code")] public string Code { get; private set; } /// <summary> /// Gets the error. /// </summary> [JsonProperty(PropertyName = "properties.error")] public object Error { get; private set; } /// <summary> /// Gets the tracking id. /// </summary> [JsonProperty(PropertyName = "properties.trackingId")] public string TrackingId { get; private set; } /// <summary> /// Gets or sets the run correlation. /// </summary> [JsonProperty(PropertyName = "properties.correlation")] public Correlation Correlation { get; set; } /// <summary> /// Gets the link to input parameters. /// </summary> [JsonProperty(PropertyName = "properties.inputsLink")] public ContentLink InputsLink { get; private set; } /// <summary> /// Gets the link to output parameters. /// </summary> [JsonProperty(PropertyName = "properties.outputsLink")] public ContentLink OutputsLink { get; private set; } /// <summary> /// Gets a value indicating whether trigger was fired. /// </summary> [JsonProperty(PropertyName = "properties.fired")] public bool? Fired { get; private set; } /// <summary> /// Gets the reference to workflow run. /// </summary> [JsonProperty(PropertyName = "properties.run")] public ResourceReference Run { get; private set; } /// <summary> /// Gets the workflow trigger history name. /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; private set; } /// <summary> /// Gets the workflow trigger history type. /// </summary> [JsonProperty(PropertyName = "type")] public string Type { get; private set; } } }
39.325
596
0.593611
[ "MIT" ]
0xced/azure-sdk-for-net
src/SDKs/Logic/Management.Logic/Generated/Models/WorkflowTriggerHistory.cs
6,292
C#
using System; using System.Collections.Generic; using ISAAR.MSolve.Numerical.LinearAlgebra.Interfaces; using ISAAR.MSolve.Numerical.LinearAlgebra; using ISAAR.MSolve.FEM.Interfaces; using ISAAR.MSolve.FEM.Entities; namespace ISAAR.MSolve.FEM.Elements { public class ConcentratedMass3D : IStructuralFiniteElement { private static readonly DOFType[] nodalDOFTypes = new DOFType[] { DOFType.X, DOFType.Y, DOFType.Z }; private static readonly DOFType[][] dofs = new DOFType[][] { nodalDOFTypes }; private readonly double massCoefficient; private IFiniteElementDOFEnumerator dofEnumerator = new GenericDOFEnumerator(); public int ID { get { return 998; } } public ElementDimensions ElementDimensions { get { return ElementDimensions.ThreeD; } } public IFiniteElementDOFEnumerator DOFEnumerator { get { return dofEnumerator; } set { dofEnumerator = value; } } public IList<IList<DOFType>> GetElementDOFTypes(Element element) { if (element == null) return dofs; var d = new List<IList<DOFType>>(); foreach (var node in element.Nodes) { var nodeDofs = new List<DOFType>(); nodeDofs.AddRange(nodalDOFTypes); d.Add(nodeDofs); } return d; } public bool MaterialModified { get { return false; } } public ConcentratedMass3D(double massCoefficient) { this.massCoefficient = massCoefficient; } public ConcentratedMass3D(double massCoefficient, IFiniteElementDOFEnumerator dofEnumerator) : this(massCoefficient) { this.dofEnumerator = dofEnumerator; } public IMatrix2D MassMatrix(Element element) { return new SymmetricMatrix2D(new double[] { massCoefficient, 0, 0, massCoefficient, 0, massCoefficient }); } public IMatrix2D StiffnessMatrix(Element element) { return new SymmetricMatrix2D(new double[6]); } public IMatrix2D DampingMatrix(Element element) { return new SymmetricMatrix2D(new double[6]); } public void ResetMaterialModified() { } public Tuple<double[], double[]> CalculateStresses(Element element, double[] localDisplacements, double[] localdDisplacements) { return new Tuple<double[], double[]>(new double[6], new double[6]); } public double[] CalculateForcesForLogging(Element element, double[] localDisplacements) { return CalculateForces(element, localDisplacements, new double[localDisplacements.Length]); } public double[] CalculateForces(Element element, double[] localDisplacements, double[] localdDisplacements) { return new double[6]; } public double[] CalculateAccelerationForces(Element element, IList<MassAccelerationLoad> loads) { Vector accelerations = new Vector(3); IMatrix2D massMatrix = MassMatrix(element); foreach (MassAccelerationLoad load in loads) { int index = 0; foreach (DOFType[] nodalDOFTypes in dofs) foreach (DOFType dofType in nodalDOFTypes) { if (dofType == load.DOF) accelerations[index] += load.Amount; index++; } } double[] forces = new double[3]; massMatrix.Multiply(accelerations, forces); return forces; } public void ClearMaterialState() { } public void SaveMaterialState() { } public void ClearMaterialStresses() { } } }
30.270677
134
0.578987
[ "Apache-2.0" ]
odyred/RandomVariable_MonteCarlo
ISAAR.MSolve.FEM/Elements/ConcentratedMass3D.cs
4,028
C#
using System; using NUnit.Framework; namespace TaxCalculator.Tests { [Ignore("Not yet implemented")] class TaxCalculatorAfterFirstYearTest { private static readonly DateTime FirstOfApril2017 = new DateTime(2017, 4, 1); private TaxCalculator _taxCalculator; [SetUp] public void BeforeEach() { _taxCalculator = new DummyTaxCalculator(); } [Test] public void WhenVehicleUsesPetrol() { Vehicle vehicle = new Vehicle(206, FuelType.Petrol, FirstOfApril2017, 20000); int tax = _taxCalculator.CalculateTax(vehicle); Assert.AreEqual(140, tax); } [Test] public void WhenVehicleIsElectric() { Vehicle vehicle = new Vehicle(206, FuelType.Electric, FirstOfApril2017, 20000); int tax = _taxCalculator.CalculateTax(vehicle); Assert.AreEqual(0, tax); } [Test] public void WhenVehicleUsesAlternativeFuel() { Vehicle vehicle = new Vehicle(206, FuelType.AlternativeFuel, FirstOfApril2017, 20000); int tax = _taxCalculator.CalculateTax(vehicle); Assert.AreEqual(130, tax); } } }
28.953488
98
0.608835
[ "Apache-2.0" ]
4ndrewHarri5/tax_calculator
exercises/dotnet/TaxCalculator.Tests/TaxCalculatorAfterFirstYearTest.cs
1,247
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Discord.WebSocket; using NadekoBot.Services; using NadekoBot.Services.Database.Models; using Newtonsoft.Json; using NLog; namespace NadekoBot.Modules.Utility.Services { public class ConverterService : INService { public List<ConvertUnit> Units { get; } = new List<ConvertUnit>(); private readonly Logger _log; private readonly Timer _currencyUpdater; private readonly TimeSpan _updateInterval = new TimeSpan(12, 0, 0); private readonly DbService _db; private readonly ConvertUnit[] fileData; public ConverterService(DiscordSocketClient client, DbService db) { _log = LogManager.GetCurrentClassLogger(); _db = db; if (client.ShardId == 0) { try { fileData = JsonConvert.DeserializeObject<List<MeasurementUnit>>( File.ReadAllText("data/units.json")) .Select(u => new ConvertUnit() { Modifier = u.Modifier, UnitType = u.UnitType, InternalTrigger = string.Join("|", u.Triggers) }).ToArray(); using (var uow = _db.UnitOfWork) { if (uow.ConverterUnits.Empty()) { uow.ConverterUnits.AddRange(fileData); Units = uow.ConverterUnits.GetAll().ToList(); uow.Complete(); } } } catch (Exception ex) { _log.Warn("Could not load units: " + ex.Message); } } _currencyUpdater = new Timer(async (shouldLoad) => await UpdateCurrency((bool)shouldLoad), client.ShardId == 0, TimeSpan.FromSeconds(1), _updateInterval); } private async Task<Rates> GetCurrencyRates() { using (var http = new HttpClient()) { var res = await http.GetStringAsync("http://api.fixer.io/latest").ConfigureAwait(false); return JsonConvert.DeserializeObject<Rates>(res); } } private async Task UpdateCurrency(bool shouldLoad) { try { var unitTypeString = "currency"; if (shouldLoad) { var currencyRates = await GetCurrencyRates(); var baseType = new ConvertUnit() { Triggers = new[] { currencyRates.Base }, Modifier = decimal.One, UnitType = unitTypeString }; var range = currencyRates.ConversionRates.Select(u => new ConvertUnit() { InternalTrigger = u.Key, Modifier = u.Value, UnitType = unitTypeString }).ToArray(); var toRemove = Units.Where(u => u.UnitType == unitTypeString); using (var uow = _db.UnitOfWork) { if(toRemove.Any()) uow.ConverterUnits.RemoveRange(toRemove.ToArray()); uow.ConverterUnits.Add(baseType); uow.ConverterUnits.AddRange(range); await uow.CompleteAsync().ConfigureAwait(false); } Units.RemoveAll(u => u.UnitType == unitTypeString); Units.Add(baseType); Units.AddRange(range); Units.AddRange(fileData); } else { using (var uow = _db.UnitOfWork) { Units.RemoveAll(u => u.UnitType == unitTypeString); Units.AddRange(uow.ConverterUnits.GetAll().ToArray()); } } } catch { _log.Warn("Failed updating currency. Ignore this."); } } } public class MeasurementUnit { public List<string> Triggers { get; set; } public string UnitType { get; set; } public decimal Modifier { get; set; } } public class Rates { public string Base { get; set; } public DateTime Date { get; set; } [JsonProperty("rates")] public Dictionary<string, decimal> ConversionRates { get; set; } } }
34.887324
104
0.472749
[ "MIT" ]
2UNIEK/tunes-of-turmoil-radio-bot
src/NadekoBot/Modules/Utility/Services/ConverterService.cs
4,956
C#
using System; using System.Globalization; using System.IO; using System.Threading.Tasks; namespace ContributionsRate { internal class Io { protected readonly int Contributions; public Io(int contributions) { Contributions = contributions; } public int GetContributions() { return Contributions; } } internal class Rates : Io { public Rates(int contributions) : base(contributions) { } public double GetAnnualContributionsRate() { var result = Convert.ToDouble(Contributions) / Convert.ToDouble(DateTime.Now.DayOfYear); return result; } public double PredictNumberOfAnnualContributions() { var result = GetAnnualContributionsRate() * 365; return result; } } internal static class Program { private static void Main(string[] args) { var rates = new Rates(3456); Console.WriteLine(rates.GetAnnualContributionsRate()); Console.WriteLine(rates.PredictNumberOfAnnualContributions()); } } }
22.090909
100
0.577778
[ "MIT" ]
CiganOliviu/contributions-rate
ContributionsRate/ContributionsRate/Program.cs
1,217
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EconomySim.Models { public class PriceModel { public int Iteration { get; set; } public double Price { get; set; } } }
18.333333
42
0.683636
[ "MIT" ]
matthewpaul-us/bazaarBot2
EconomySim/EconomySim/Models/PriceModel.cs
277
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. namespace mshtml { using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [ComImport, Guid("3050F33A-98B5-11CF-BB82-00AA00BDCE0B"), TypeLibType((short)0x1040)] public interface IHTMLStyle5 { [DispId(-2147412899)] string msInterpolationMode {[param: In, MarshalAs(UnmanagedType.BStr)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), TypeLibFunc((short)20), DispId(-2147412899)] set;[return: MarshalAs(UnmanagedType.BStr)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147412899), TypeLibFunc((short)20)] get; } [DispId(-2147412898)] object maxHeight {[param: In, MarshalAs(UnmanagedType.Struct)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147412898), TypeLibFunc((short)20)] set;[return: MarshalAs(UnmanagedType.Struct)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), TypeLibFunc((short)20), DispId(-2147412898)] get; } [DispId(-2147412897)] object minWidth {[param: In, MarshalAs(UnmanagedType.Struct)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147412897), TypeLibFunc((short)20)] set;[return: MarshalAs(UnmanagedType.Struct)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), TypeLibFunc((short)20), DispId(-2147412897)] get; } [DispId(-2147412896)] object maxWidth {[param: In, MarshalAs(UnmanagedType.Struct)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147412896), TypeLibFunc((short)20)] set;[return: MarshalAs(UnmanagedType.Struct)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), TypeLibFunc((short)20), DispId(-2147412896)] get; } } }
86.291667
391
0.764848
[ "MIT" ]
BobinYang/OpenLiveWriter
src/managed/OpenLiveWriter.Interop.Mshtml/mshtml/IHTMLStyle5.cs
2,073
C#
namespace SIS.Demo { using WebServer.Results; using HTTP.Enums; using HTTP.Responses.Contracts; public class HomeController { public IHttpResponse Index() { string content = "<h1>Hello, World</h1>"; return new HtmlResult(content, HttpResponseStatusCode.Ok); } } }
19.941176
70
0.60177
[ "MIT" ]
MiroslavKisov/Software-University
CSharp Web/SIS/SIS.Demo/HomeController.cs
341
C#
namespace HACC.Enumerations; public enum RuneDataType { Rune = 0, Attribute = 1, DirtyFlag = 2, }
13.75
28
0.654545
[ "MIT" ]
Blazor-Console/HACC.Development
src/HACC/Enumerations/RuneDataType.cs
110
C#
using System; using System.Maui.CustomAttributes; using System.Diagnostics; using System.Maui.Internals; namespace System.Maui.Controls.Issues { [Preserve (AllMembers = true)] [Issue (IssueTracker.Github, 2987, "When setting the minimum and maximum date for a date picker, only allow valid dates to be seen/selected from the DatePicker dialog", PlatformAffected.Android)] public class Issue2987 : TestContentPage { public AbsoluteLayout layout; protected override void Init () { var datePicker = new DatePicker { AutomationId = "datePicker" }; datePicker.MinimumDate = new DateTime (2015, 1, 1); datePicker.MaximumDate = new DateTime (2015, 6, 1); datePicker.Date = DateTime.Now; datePicker.Format = "MMM dd, yyyy"; datePicker.DateSelected += (object sender, DateChangedEventArgs e) => { Debug.WriteLine ("Date changed"); }; Padding = Device.RuntimePlatform == Device.iOS ? new Thickness(10, 20, 10, 5) : new Thickness(10, 0, 10, 5); layout = new AbsoluteLayout { VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand }; AbsoluteLayout.SetLayoutFlags (datePicker, AbsoluteLayoutFlags.None); AbsoluteLayout.SetLayoutBounds (datePicker, new Rectangle (0f, 0f, 300f, 50f)); layout.Children.Add (datePicker); Content = layout; } } }
32.780488
196
0.732143
[ "MIT" ]
AswinPG/maui
System.Maui.Controls.Issues/System.Maui.Controls.Issues.Shared/Issue2987.cs
1,344
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics.ContractsLight; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using BuildXL.Engine.Cache.Fingerprints; using BuildXL.Pips; using BuildXL.Pips.Artifacts; using BuildXL.Pips.Operations; using BuildXL.Scheduler.Filter; using BuildXL.Tracing; using BuildXL.Utilities; using BuildXL.Utilities.Configuration; using BuildXL.Utilities.Collections; using BuildXL.Utilities.Instrumentation.Common; namespace BuildXL.Scheduler.Graph { /// <summary> /// Defines graph of pips and allows adding Pips with validation. /// </summary> public sealed partial class PipGraph : PipGraphBase, IQueryablePipDependencyGraph { /// <summary> /// Envelope for graph serialization /// </summary> public static readonly FileEnvelope FileEnvelopeGraph = new FileEnvelope(name: "PipGraph", version: 0); /// <summary> /// Envelope for graph id serialization /// </summary> public static readonly FileEnvelope FileEnvelopeGraphId = new FileEnvelope(name: "PipGraphId", version: 0); #region State /// <summary> /// Mapping from include directory artifacts to the <see cref="SealDirectory" /> pips nodes that indicate their completion. /// </summary> /// <remarks> /// Pips which depend on an include directory artifact in its final, immutable state should have a dependency edge /// to the corresponding <see cref="SealDirectory" /> node. /// </remarks> private readonly ConcurrentBigMap<DirectoryArtifact, NodeId> m_sealedDirectoryNodes; /// <summary> /// Relation representing Service PipId -> Service Client PipId. /// </summary> private readonly ConcurrentBigMap<PipId, ConcurrentBigSet<PipId>> m_servicePipClients; /// <summary> /// Unique identifier for a graph, established at creation time. This ID is durable under serialization and deserialization. /// </summary> [Pure] public Guid GraphId { get; } /// <summary> /// Gets the fingerprint used for looking up performance data. /// This is calculated by taking the first N process semistable hashes after sorting. /// This provides a stable fingerprint because it is unlikely that modifications to this pip graph /// will change those semistable hashes. Further, it is unlikely that pip graphs of different codebases /// will share these values. /// </summary> public ContentFingerprint SemistableFingerprint { get; } /// <summary> /// Gets the range of node IDs valid in the current graph. /// </summary> [Pure] public NodeRange NodeRange => DataflowGraph.NodeRange; /// <summary> /// The maximum index of serialized absolute paths. /// </summary> public readonly int MaxAbsolutePathIndex; #endregion State #region Constructor private PipGraph( SerializedState serializedState, DirectedGraph directedGraph, PipTable pipTable, PipExecutionContext context, SemanticPathExpander semanticPathExpander) : base( pipTable: pipTable, context: context, semanticPathExpander: semanticPathExpander, dataflowGraph: directedGraph, values: serializedState.Values, specFiles: serializedState.SpecFiles, modules: serializedState.Modules, pipProducers: serializedState.PipProducers, outputDirectoryProducers: serializedState.OpaqueDirectoryProducers, outputDirectoryRoots: serializedState.OutputDirectoryRoots, compositeOutputDirectoryProducers: serializedState.CompositeOutputDirectoryProducers, sourceSealedDirectoryRoots: serializedState.SourceSealedDirectoryRoots, temporaryPaths: serializedState.TemporaryPaths, rewritingPips: serializedState.RewritingPips, rewrittenPips: serializedState.RewrittenPips, latestWriteCountsByPath: serializedState.LatestWriteCountsByPath, apiServerMoniker: serializedState.ApiServerMoniker, pipStaticFingerprints: serializedState.PipStaticFingerprints) { Contract.Requires(pipTable != null); Contract.Requires(context != null); Contract.Requires(semanticPathExpander != null); Debugging.NodeIdDebugView.DebugPipGraph = this; Debugging.NodeIdDebugView.DebugContext = context; // Serialized State GraphId = serializedState.GraphId; Contract.Assume(GraphId != default(Guid), "Not convincingly unique."); m_sealedDirectoryNodes = serializedState.SealDirectoryNodes; m_servicePipClients = serializedState.ServicePipClients; MaxAbsolutePathIndex = serializedState.MaxAbsolutePath; SemistableFingerprint = serializedState.SemistableProcessFingerprint; } #endregion Constructor #region Dependency-based queries (IQueryablePipDependencyGraph) /// <summary> /// Performs a reachability check between <paramref name="from" /> and <paramref name="to" /> on <see cref="PipGraphBase.DataflowGraph" />. /// </summary> /// <remarks> /// TODO: This will not return correct results w.r.t. meta-pips, e.g. spec file pips. Need to get meta-pips ordered correctly (i.e., add them topologically). /// Mis-ordering is ignored for now to unblock dependency violation analysis for real pips. /// </remarks> internal bool IsReachableFrom(NodeId from, NodeId to) { if (from == PipId.DummyHashSourceFilePipId.ToNodeId() || to == PipId.DummyHashSourceFilePipId.ToNodeId()) { return false; } // TODO: skipOutOfOrderNodes has to be used until meta-pips are ordered correctly. return DataflowGraph.IsReachableFrom(from, to, skipOutOfOrderNodes: true); } /// <inheritdoc /> Pip IQueryablePipDependencyGraph.HydratePip(PipId pipId, PipQueryContext queryContext) { return PipTable.HydratePip(pipId, queryContext); } private NodeId TryFindContainingExclusiveOpaqueOutputDirectory(AbsolutePath filePath) { AbsolutePath path = filePath.GetParent(Context.PathTable); while (path.IsValid) { NodeId nodeId; if (OutputDirectoryProducers.TryGetValue(DirectoryArtifact.CreateWithZeroPartialSealId(path), out nodeId)) { return nodeId; } path = path.GetParent(Context.PathTable); } return NodeId.Invalid; } /// <inheritdoc/> public DirectoryArtifact TryGetSealSourceAncestor(AbsolutePath path) { // Walk the parent directories of the path to find if it is under a sealedSourceDirectory. foreach (var current in Context.PathTable.EnumerateHierarchyBottomUp(path.Value, HierarchicalNameTable.NameFlags.Sealed)) { var currentDirectory = new AbsolutePath(current); if (SourceSealedDirectoryRoots.TryGetValue(currentDirectory, out var directoryArtifact)) { return directoryArtifact; } } return DirectoryArtifact.Invalid; } /// <inheritdoc/> public bool TryGetTempDirectoryAncestor(AbsolutePath path, out Pip pip, out AbsolutePath temPath) { // Walk the parent directories of the path to find if it is under a temp directory. foreach (var current in Context.PathTable.EnumerateHierarchyBottomUp(path.Value)) { var currentDirectory = new AbsolutePath(current); if (TemporaryPaths.TryGetValue(currentDirectory, out var pipId)) { pip = PipTable.HydratePip(pipId, PipQueryContext.PipGraphRetrieveAllPips); temPath = currentDirectory; return true; } } pip = null; temPath = AbsolutePath.Invalid; return false; } /// <inheritdoc /> public Pip GetSealedDirectoryPip(DirectoryArtifact directoryArtifact, PipQueryContext queryContext) { var nodeId = GetSealedDirectoryNode(directoryArtifact); var pip = PipTable.HydratePip(nodeId.ToPipId(), queryContext); return pip; } /// <inheritdoc /> public PipId? TryFindProducerPipId(AbsolutePath producedPath, VersionDisposition versionDisposition, DependencyOrderingFilter? maybeOrderingFilter) { Contract.Assume(producedPath.IsValid); // First check if the file is witin any opaque output directory. If it is, attribute the production to that pip. NodeId opaqueDirectoryProducer = TryFindContainingExclusiveOpaqueOutputDirectory(producedPath); PipId matchedPipId; if (!maybeOrderingFilter.HasValue) { // No filter: We are looking for the earliest or latest producer of the path. if (opaqueDirectoryProducer.IsValid) { matchedPipId = opaqueDirectoryProducer.ToPipId(); } else if (versionDisposition == VersionDisposition.Latest) { FileArtifact artifact = TryGetLatestFileArtifactForPath(producedPath); if (!artifact.IsValid) { return null; } matchedPipId = PipProducers[artifact].ToPipId(); } else { Contract.Assert(versionDisposition == VersionDisposition.Earliest); NodeId producerNode = TryGetOriginalProducerForPath(producedPath); if (!producerNode.IsValid) { return null; } matchedPipId = producerNode.ToPipId(); } } else { // Filter: We need to find an artifact relative to other pips. DependencyOrderingFilter orderingFilter = maybeOrderingFilter.Value; Contract.Assert(orderingFilter.Reference != null); NodeId originalProducerNode = opaqueDirectoryProducer; switch (orderingFilter.Filter) { case DependencyOrderingFilterType.PossiblyPrecedingInWallTime: { // Here we need to find a producer for this path 'possibly preceding' the reference in some actual execution order. // The found artifact's producer is either definitely preceding (reference reachable from producer) or concurrent (neither reachable from the other). // Equivalently, the disallowed condition is that the producer is reachable from the reference - i.e., the reference occurs earlier in all execution orders. // // Before the reachability check, we need to pick the right artifact (producer) for the path (there may be multiple in the event of rewrites): // - If the artifact is written once (or source), this is trivial. // - If the artifact is rewritten multiple times, we have the property that any producer P_i (producing version i) is reachable from P_(i-1), down to the first version - // rewrites are serialized in order of version. So, we check reachability from the reference to the *lowest* version, which determines reachability to *all* versions. // // Examples: // R -> P_1 -> P_2 (find none; lowest reachable) // P_1 -> R -> P_2 (find P_1 since not reachable from R) // P_1 R -> P_2 (same as prior, but this time P_1 is concurrent with R). // \______/ // TODO: This approach is not specific to the 'latest or earliest possible' criterion - 'version dispositon'; consider // P_1 -> P_2 -> R should report P_2, not P_1 // Consider a fancier IsReachableFrom(from, {set of to}) which returns the 'to' node found first (fewest hops). if (!originalProducerNode.IsValid) { originalProducerNode = TryGetOriginalProducerForPath(producedPath); } if (!originalProducerNode.IsValid) { return null; } var referenceNode = orderingFilter.Reference.PipId.ToNodeId(); if (IsReachableFrom(referenceNode, originalProducerNode)) { // Reference must execute before any version produced, so no match. return null; } matchedPipId = originalProducerNode.ToPipId(); } break; case DependencyOrderingFilterType.Concurrent: { // We want to find a pip that is neither ordered before nor after the reference. This means that there is not a path between // them when traversing edges either direction. // Before each reachability check, we need to pick a suitable producer for the path (there may be multiple in the event of rewrites). // Note that in general, we have to check concurrency with each version. // As a tricky case, consider the following with and without P_2: // P_1 -> R -> P_3 // \__>P_2>__/ // R is concurrent with P_2 if it is present. But without P_2, it is well-ordered between P_1 and P_3 (so concurrent with no P_*) FileArtifact latestArtifact = TryGetLatestFileArtifactForPath(producedPath); var referenceNode = orderingFilter.Reference.PipId.ToNodeId(); if (!latestArtifact.IsValid) { // Check for an opaque directory producer if (opaqueDirectoryProducer.IsValid && !IsReachableFrom(referenceNode, opaqueDirectoryProducer) && !IsReachableFrom(opaqueDirectoryProducer, referenceNode)) { matchedPipId = opaqueDirectoryProducer.ToPipId(); } else { return null; } } else { matchedPipId = PipId.Invalid; for (int rewriteCount = latestArtifact.RewriteCount; rewriteCount >= 0; rewriteCount--) { var thisArtifact = new FileArtifact(producedPath, rewriteCount); NodeId producerNodeId; if (!PipProducers.TryGetValue(thisArtifact, out producerNodeId)) { Contract.Assume( rewriteCount == 0, "Rewrite counts are dense down to zero, unless source rewrites are disallowed (then zero might be missing)."); break; } if (!IsReachableFrom(referenceNode, producerNodeId) && !IsReachableFrom(producerNodeId, referenceNode)) { // TODO: Should respect version disposition rather than disingenuously returning the latest. matchedPipId = producerNodeId.ToPipId(); break; } } } } break; case DependencyOrderingFilterType.OrderedBefore: { // We want to find a pip that is ordered before the reference. This means that there is a path from a producer of thepath to the reference. // Since the earliest producer of a path is ordered before any later producers (higher write counts), we can try to find a path from there. if (!originalProducerNode.IsValid) { originalProducerNode = TryGetOriginalProducerForPath(producedPath); } if (!originalProducerNode.IsValid) { return null; } var referenceNode = orderingFilter.Reference.PipId.ToNodeId(); if (!IsReachableFrom(originalProducerNode, referenceNode)) { // No path from the original producer to the reference, so original producer is not ordered before the reference. return null; } matchedPipId = originalProducerNode.ToPipId(); } break; default: throw Contract.AssertFailure("Unhandled DependencyOrderingFilterType (not yet supported by Scheduler)."); } } if (!matchedPipId.IsValid) { return null; } return matchedPipId; } /// <inheritdoc /> bool IQueryablePipDependencyGraph.IsReachableFrom(PipId from, PipId to) { return IsReachableFrom(from.ToNodeId(), to.ToNodeId()); } /// <inheritdoc /> public Pip TryFindProducer(AbsolutePath producedPath, VersionDisposition versionDisposition, DependencyOrderingFilter? maybeOrderingFilter) { PipId? matchedPipId = TryFindProducerPipId(producedPath, versionDisposition, maybeOrderingFilter); if (!matchedPipId.HasValue) { return null; } if (matchedPipId.Value == PipId.DummyHashSourceFilePipId) { return new HashSourceFile(FileArtifact.CreateSourceFile(producedPath)); } return PipTable.HydratePip(matchedPipId.Value, PipQueryContext.PipGraphTryFindProducer); } /// <summary> /// For a given service PipId (<paramref name="servicePipId"/>), looks up all its clients, hydrates and returns them. /// </summary> public IEnumerable<Pip> GetServicePipClients(PipId servicePipId) { ConcurrentBigSet<PipId> clients; if (!m_servicePipClients.TryGetValue(servicePipId, out clients)) { return CollectionUtilities.EmptyArray<Pip>(); } var result = new Pip[clients.Count]; for (int i = 0; i < clients.Count; i++) { result[i] = PipTable.HydratePip(clients[i], PipQueryContext.PipGraphAddServicePipDependency); } return result; } #endregion #region Queries /// <summary> /// Retrieves all pips /// </summary> public IEnumerable<Pip> RetrieveAllPips() { PipId[] pipIds = PipTable.Keys.ToArray(); return HydratePips(pipIds, PipQueryContext.PipGraphRetrieveAllPips); } /// <summary> /// Retrieves all pips of a particular pip type /// </summary> public IEnumerable<Pip> RetrievePipsOfType(PipType pipType) { var pipIds = new List<PipId>(); foreach (PipId pipId in PipTable.Keys) { if (PipTable.GetPipType(pipId) == pipType) { pipIds.Add(pipId); } } return HydratePips(pipIds, PipQueryContext.PipGraphRetrievePipsOfType); } /// <summary> /// Retrieves all pips of a particular pip type /// </summary> public IEnumerable<PipReference> RetrievePipReferencesOfType(PipType pipType) { var pipIds = new List<PipId>(); foreach (PipId pipId in PipTable.Keys) { if (PipTable.GetPipType(pipId) == pipType) { pipIds.Add(pipId); } } return AsPipReferences(pipIds, PipQueryContext.PipGraphRetrievePipsOfType); } /// <summary> /// Returns the PipReferences for the given PipIds /// </summary> public IEnumerable<PipReference> AsPipReferences(IEnumerable<PipId> pipIds, PipQueryContext context) { // no locking needed here foreach (PipId pipId in pipIds) { yield return new PipReference(PipTable, pipId, context); } } /// <summary> /// Checks if a number is a valid numeric representation of a pip /// </summary> [Pure] public bool CanGetPipFromUInt32(uint value) { var nodeId = new NodeId(value); return DataflowGraph.ContainsNode(nodeId); } /// <summary> /// Turns a previously obtained numeric representation of a pip back into the pip /// </summary> public Pip GetPipFromUInt32(uint value) { Contract.Requires(CanGetPipFromUInt32(value)); return PipTable.HydratePip(new PipId(value), PipQueryContext.PipGraphGetPipFromUInt32); } /// <summary> /// Hydrites a pip from a <see cref="PipId"/> /// </summary> public Pip GetPipFromPipId(PipId pipId) { return PipTable.HydratePip(pipId, PipQueryContext.PipGraphGetPipFromUInt32); } /// <summary> /// Gets a numeric representation of a pip id /// </summary> public static uint GetUInt32FromPip(Pip pip) { Contract.Requires(pip != null); return pip.PipId.Value; } /// <summary> /// Gets the producing pips for the given file artifact /// </summary> /// <param name="filePath">The produced file paht</param> /// <returns>List of pips that produce/rewrite the given file, or an empty list if file is not produced</returns> public IEnumerable<Pip> GetProducingPips(AbsolutePath filePath) { List<FileArtifact> files = (from k in PipProducers.Keys where k.Path == filePath select k).ToList(); List<NodeId> nodeIds = PipProducers.Where(kvp => files.Contains(kvp.Key)).Select(kvp => kvp.Value).ToList(); return HydratePips(nodeIds, PipQueryContext.PipGraphGetProducingPips); } private static bool IsInput(AbsolutePath path, FileArtifact artifact, bool isInput) { return path == artifact.Path && (isInput || artifact.RewriteCount > 1); } private static bool IsInput(AbsolutePath path, IEnumerable<FileArtifact> artifacts, bool isInput) { foreach (FileArtifact artifact in artifacts) { if (IsInput(path, artifact, isInput)) { return true; } } return false; } private static bool IsInput(AbsolutePath path, Pip pip) { switch (pip.PipType) { case PipType.CopyFile: var copyFile = (CopyFile)pip; return IsInput(path, copyFile.Source, isInput: true) || IsInput(path, copyFile.Destination, isInput: false); case PipType.WriteFile: var writeFile = (WriteFile)pip; return IsInput(path, writeFile.Destination, isInput: false); case PipType.Process: var process = (Process)pip; return IsInput(path, process.Dependencies, isInput: true) || IsInput(path, process.GetOutputs(), isInput: false); case PipType.SealDirectory: var sealDirectory = (SealDirectory)pip; return IsInput(path, sealDirectory.Contents, isInput: true); default: return false; } } /// <summary> /// Returns pips consuming given directory artifact. /// </summary> public IEnumerable<Pip> GetConsumingPips(DirectoryArtifact dir) { var producer = GetProducer(dir); var potentialConsumers = HydratePips( DataflowGraph.GetOutgoingEdges(producer.ToNodeId()).Cast<Edge>().Select(edge => edge.OtherNode), PipQueryContext.PipGraphGetConsumingPips); return potentialConsumers .Where(pip => (pip is Process proc && proc.DirectoryDependencies.Contains(dir)) || (pip is SealDirectory sd && sd.Directory == dir)); } /// <summary> /// Get the list of pips that consume a given file artifact /// </summary> /// <param name="filePath">The consumed file path</param> /// <returns>List of pips that consume the given file, or an empty list if file is not consumed</returns> public IEnumerable<Pip> GetConsumingPips(AbsolutePath filePath) { var potentialConsumers = new HashSet<NodeId>(); var artifact = FileArtifact.CreateSourceFile(filePath); while (true) { NodeId producer; if (PipProducers.TryGetValue(artifact, out producer)) { foreach (Edge edge in DataflowGraph.GetOutgoingEdges(producer)) { potentialConsumers.Add(edge.OtherNode); } } else if (!artifact.IsSourceFile) { // No producer was found. Stop looking for more producers if this wasn't a source file, since there // will always be a continuous chain of producers of later rewritten versions of the file break; } // Look for a producer of the next rewritten version if a producer was found for this version or // the file was a source file (rewrite version 0) artifact = artifact.CreateNextWrittenVersion(); } return HydratePips(potentialConsumers, PipQueryContext.PipGraphGetConsumingPips) .Where(pip => IsInput(filePath, pip)); } /// <summary> /// Gets the list of pips generated by a spec file /// </summary> /// <param name="specPath">The spec file path</param> /// <returns>List of pips generated by the specified spec file</returns> public IEnumerable<Pip> GetPipsPerSpecFile(AbsolutePath specPath) { return (from p in PipTable.Keys.Select(pipId => PipTable.HydratePip(pipId, PipQueryContext.PipGraphGetPipsPerSpecFile)) where p.Provenance != null && p.Provenance.Token.Path == specPath select p).ToList(); } /// <summary> /// Retrieves the producing node for the original file artifact for the given path (the one with the lowest version) /// If there is no such artifact (the path has not been used as an input or output), <see cref="NodeId.Invalid" /> is /// returned. /// </summary> /// <remarks> /// The graph lock need not be held when calling this method. /// Internal for use in change-based scheduling, in which we need to map changed file paths back to ndoes. /// </remarks> internal NodeId TryGetOriginalProducerForPath(string pathStr) { Contract.Requires(pathStr != null); AbsolutePath path; return !AbsolutePath.TryGet(Context.PathTable, pathStr, out path) ? NodeId.Invalid : TryGetOriginalProducerForPath(path); } /// <summary> /// Checks to see if a path is part of the build or not /// </summary> /// <returns>true if the path is a known input or output file</returns> public bool IsPathInBuild(AbsolutePath path) { Contract.Requires(path.IsValid); if (TryGetOriginalProducerForPath(path).IsValid) { return true; } return false; } /// <summary> /// Gets all directories containing outputs. /// </summary> /// <returns>Set of all directories that contain outputs.</returns> public HashSet<AbsolutePath> AllDirectoriesContainingOutputs() { var outputFileDirectories = PipProducers.Keys.Select(f => f.Path.GetParent(Context.PathTable)).ToReadOnlySet(); var outputDirectories = new HashSet<AbsolutePath>(OutputDirectoryProducers.Keys.Select(d => d.Path)); outputDirectories.UnionWith(outputFileDirectories); return outputDirectories; } /// <summary> /// Attempts to find the highest-versioned file artifact for a path that precedes the specified pip in graph order. /// The returned file artifact (if not invalid) is possibly generated causally before the specified pip, /// but to be sure requires a graph reachability check between the two. /// </summary> /// <remarks> /// The graph lock must not be held. /// </remarks> internal FileArtifact TryGetFileArtifactPrecedingPip(PipId readingPipId, AbsolutePath path) { FileArtifact latestArtifact = TryGetLatestFileArtifactForPath(path); if (!latestArtifact.IsValid) { return FileArtifact.Invalid; } var readingNodeId = readingPipId.ToNodeId(); // m_pipProducers[latestArtifact] must exist. If latestArtifact has a write count > 0, then // the path at versions [1, latestArtifact.RewriteCount] must exist, and *possibly* also at version 0 // (source) as well (depends if rewriting sources is allowed). // We want to find the producer with the highest node ID such that it is strictly less than readingNodeId. for (int rewriteCount = latestArtifact.RewriteCount; rewriteCount >= 1; rewriteCount--) { var thisArtifact = new FileArtifact(path, rewriteCount); NodeId producerNodeId = PipProducers[thisArtifact]; if (producerNodeId.Value < readingNodeId.Value) { return thisArtifact; } } { NodeId producerNodeId; var sourceArtifact = new FileArtifact(path, rewriteCount: 0); if (PipProducers.TryGetValue(sourceArtifact, out producerNodeId) && producerNodeId.Value < readingNodeId.Value) { return sourceArtifact; } } return FileArtifact.Invalid; } internal Pip GetProducingPip(FileArtifact fileArtifact) { Contract.Requires(fileArtifact.IsValid); Contract.Ensures(Contract.Result<Pip>() != null); NodeId producerNodeId; bool getProducerNodeId = PipProducers.TryGetValue(fileArtifact, out producerNodeId); Contract.Assume(getProducerNodeId, "Every file artifact added into the scheduler has a producer."); Pip pip = PipTable.HydratePip(producerNodeId.ToPipId(), PipQueryContext.PipGraphGetProducingPip); Contract.Assert(pip != null, "There should be a one-to-one correspondence between node id and pip"); return pip; } /// <inheritdoc /> public override NodeId GetSealedDirectoryNode(DirectoryArtifact directoryArtifact) { bool success = m_sealedDirectoryNodes.TryGetValue(directoryArtifact, out var nodeId); if (!success) { Contract.Assert(false, $"Directory artifact (path: '{directoryArtifact.Path.ToString(Context.PathTable)}', PartialSealId: '{directoryArtifact.PartialSealId}', IsSharedOpaque: '{directoryArtifact.IsSharedOpaque}') should be present."); } return nodeId; } internal bool TryGetValuePip(FullSymbol fullSymbol, QualifierId qualifierId, AbsolutePath specFile, out PipId pipId) { NodeId nodeId; if (!Values.TryGetValue((fullSymbol, qualifierId, specFile), out nodeId)) { pipId = PipId.Invalid; return false; } pipId = nodeId.ToPipId(); return true; } /// <summary> /// Checks if a pip rewrites its input. /// </summary> public bool IsRewritingPip(PipId pipId) { return RewritingPips.Contains(pipId); } /// <summary> /// Checks if a pip has one of its outputs rewritten. /// </summary> public bool IsRewrittenPip(PipId pipId) { return RewrittenPips.Contains(pipId); } /// <summary> /// Gets all known files for the build /// </summary> public IEnumerable<FileArtifact> AllFiles => PipProducers.Keys; /// <summary> /// Gets all known seal directories for the build /// </summary> public IEnumerable<DirectoryArtifact> AllSealDirectories => m_sealedDirectoryNodes.Keys; /// <summary> /// Gets all files and their corresponding producers. /// </summary> public IEnumerable<KeyValuePair<FileArtifact, PipId>> AllFilesAndProducers => PipProducers.Select(kvp => new KeyValuePair<FileArtifact, PipId>(kvp.Key, kvp.Value.ToPipId())); /// <summary> /// Gets all seal directories and their producers /// </summary> public IEnumerable<KeyValuePair<DirectoryArtifact, PipId>> AllSealDirectoriesAndProducers => m_sealedDirectoryNodes.Select(kvp => new KeyValuePair<DirectoryArtifact, PipId>(kvp.Key, kvp.Value.ToPipId())); /// <summary> /// Gets all output directories and their corresponding producers. /// </summary> public IEnumerable<KeyValuePair<DirectoryArtifact, PipId>> AllOutputDirectoriesAndProducers => OutputDirectoryProducers.Select(kvp => new KeyValuePair<DirectoryArtifact, PipId>(kvp.Key, kvp.Value.ToPipId())); /// <summary> /// Gets the number of known files for the build /// </summary> public int FileCount => PipProducers.Count; /// <summary> /// Gets the number of declared content (file or sealed directories or service pips) for the build /// </summary> public int ContentCount => FileCount + m_sealedDirectoryNodes.Count + m_servicePipClients.Count; /// <summary> /// Gets the number of declared content (file or sealed directories) for the build /// </summary> internal int ArtifactContentCount => FileCount + m_sealedDirectoryNodes.Count; /// <summary> /// Gets the associated file or directory for the given content index. <paramref name="contentIndex"/> should be in the range [0, <see cref="ArtifactContentCount"/>) /// </summary> internal FileOrDirectoryArtifact GetArtifactContent(int contentIndex) { if (contentIndex < FileCount) { return PipProducers.BackingSet[contentIndex].Key; } contentIndex -= FileCount; if (contentIndex < m_sealedDirectoryNodes.Count) { return m_sealedDirectoryNodes.BackingSet[contentIndex].Key; } throw Contract.AssertFailure("Out of range: contentIndex >= ArtifactContentCount"); } /// <summary> /// Gets an unique index less than <see cref="ContentCount"/> representing the content (or null if the content is not declared) /// </summary> internal int? GetContentIndex(in FileOrDirectoryArtifact artifact) { if (artifact.IsFile) { var result = PipProducers.TryGet(artifact.FileArtifact); return result.IsFound ? (int?)result.Index : null; } else { var result = m_sealedDirectoryNodes.TryGet(artifact.DirectoryArtifact); return result.IsFound ? (int?)(result.Index + FileCount) : null; } } /// <summary> /// Gets a unique index less than <see cref="ContentCount"/> representing the input content of the service (or null if the service is not declared) /// </summary> internal int? GetServiceContentIndex(PipId servicePipId) { var result = m_servicePipClients.TryGet(servicePipId); return result.IsFound ? (int?)(result.Index + FileCount + m_sealedDirectoryNodes.Count) : null; } /// <summary> /// Gets seal directories by kind. /// </summary> internal IEnumerable<SealDirectory> GetSealDirectoriesByKind(PipQueryContext queryContext, Func<SealDirectoryKind, bool> kindPredicate) { return m_sealedDirectoryNodes.Values.Select( sealDirectoryNode => (SealDirectory)PipTable.HydratePip(sealDirectoryNode.ToPipId(), queryContext)) .Where(sealDirectory => kindPredicate(sealDirectory.Kind)); } /// <summary> /// Gets seal directories by kind. /// </summary> /// <remarks>This method is used for testing.</remarks> public IEnumerable<SealDirectory> GetSealDirectoriesByKind(Func<SealDirectoryKind, bool> kindPredicate) => GetSealDirectoriesByKind(PipQueryContext.PipGraphGetSealDirectoryByKind, kindPredicate); /// <summary> /// Gets the producer for the statically defined file or directory /// </summary> public PipId TryGetProducer(in FileOrDirectoryArtifact fileOrDirectory) { NodeId producer; if (fileOrDirectory.IsFile) { PipProducers.TryGetValue(fileOrDirectory.FileArtifact, out producer); } else if (!OutputDirectoryProducers.TryGetValue(fileOrDirectory.DirectoryArtifact, out producer)) { m_sealedDirectoryNodes.TryGetValue(fileOrDirectory.DirectoryArtifact, out producer); } return producer.IsValid ? producer.ToPipId() : PipId.Invalid; } /// <summary> /// Gets the producer for the statically defined file or directory /// </summary> public PipId GetProducer(in FileOrDirectoryArtifact fileOrDirectory) { var producer = TryGetProducer(fileOrDirectory); Contract.Assert(producer.IsValid); return producer; } /// <summary> /// Tries to get pip fingerprints. /// </summary> public bool TryGetPipFingerprint(in PipId pipId, out ContentFingerprint fingerprint) => PipStaticFingerprints.TryGetFingerprint(pipId, out fingerprint); /// <summary> /// Tries to get pip from fingerprints. /// </summary> public bool TryGetPipFromFingerprint(in ContentFingerprint fingerprint, out PipId pipId) => PipStaticFingerprints.TryGetPip(fingerprint, out pipId); /// <summary> /// Gets all pip static fingerprints. /// </summary> public IEnumerable<KeyValuePair<PipId, ContentFingerprint>> AllPipStaticFingerprints => PipStaticFingerprints.PipStaticFingerprints; /// <summary> /// Checks if artifact must remain writable. /// </summary> public bool MustArtifactRemainWritable(in FileOrDirectoryArtifact artifact) { Contract.Requires(artifact.IsValid); PipId pipId = TryGetProducer(artifact); Contract.Assert(pipId.IsValid); return PipTable.GetMutable(pipId).MustOutputsRemainWritable(); } /// <summary> /// Checks if artifact is an output that should be preserved. /// </summary> public bool IsPreservedOutputArtifact(in FileOrDirectoryArtifact artifact, int sandBoxPreserveOutputTrustLevel) { Contract.Requires(artifact.IsValid); if (artifact.IsFile && artifact.FileArtifact.IsSourceFile) { // Shortcut, source file is not preserved. return false; } PipId pipId = TryGetProducer(artifact); Contract.Assert(pipId.IsValid); MutablePipState mutablePipState = PipTable.GetMutable(pipId); if (!mutablePipState.IsPreservedOutputsPip()) { return false; } if (mutablePipState.GetProcessPreserveOutputsTrustLevel() < sandBoxPreserveOutputTrustLevel) { return false; } if (!mutablePipState.HasPreserveOutputWhitelist()) { // If whitelist is not given, we preserve all outputs of the given pip. // This is shortcut to avoid hydrating pip in order to get the whitelist. return true; } Process process = PipTable.HydratePip(pipId, PipQueryContext.PreserveOutput) as Process; return PipArtifacts.IsPreservedOutputByPip(process, artifact.Path, Context.PathTable, sandBoxPreserveOutputTrustLevel); } #endregion Queries #region Helpers /// <summary> /// Checks if a given pip has existed in the schedule. /// </summary> internal static bool PipExists(Pip pip) { Contract.Requires(pip != null, "Argument pip cannot be null"); return pip.PipId.IsValid; } #endregion Helpers #region Filtering /// <summary> /// Applies the filter to each node in the build graph. /// </summary> internal bool FilterNodesToBuild(LoggingContext loggingContext, RootFilter filter, out RangedNodeSet filteredIn) { Contract.Ensures(Contract.ValueAtReturn(out filteredIn) != null); var matchingNodes = new RangedNodeSet(); // We would use NodeRange here but that (due to other usages) acquires the global exclusive lock, which is not recursive. // The caller to this method should already be holding it. matchingNodes.ClearAndSetRange(DataflowGraph.NodeRange); using (PerformanceMeasurement.Start( loggingContext, Statistics.ApplyingFilterToPips, BuildXL.Scheduler.Tracing.Logger.Log.StartFilterApplyTraversal, BuildXL.Scheduler.Tracing.Logger.Log.EndFilterApplyTraversal)) { Contract.Assert( !filter.IsEmpty, "Builds with an empty filter should not actually perform filtering. Instead their pips should be added to the schedule with an initial state of Waiting. " + "Or in the case of a cached graph, all pips should be scheduled without going through the overhead of filtering."); var outputs = FilterOutputs(filter); int addAttempts = 0; // The outputs set contains all file artifacts that passed the filter. This means that we may // have multiple file artifacts per path (due to rewrites), which is not desirable - we want to approximate the // 'set of artifacts which must be materialized' and for each path we would only like to materialize // the latest filter-passing version. So, we determine the max write count for any filter-passing path. // TODO: This could be cheaper by having filter implementations operate on a (path -> max write count) mapping, // which would correspond nicely to the structure by which filters are applied and aggregated. var maxWriteCounts = new Dictionary<AbsolutePath, int>(); // There might be multiple file artifacts per path but if we get the one that has the highest max write count, we can include the others as well due to its dependencies. var fileArtifacts = new Dictionary<AbsolutePath, FileArtifact>(); // There might be many seal directories per path so we should include all. var directoryArtifacts = new MultiValueDictionary<AbsolutePath, DirectoryArtifact>(); foreach (FileOrDirectoryArtifact outputFileOrDirectory in outputs) { if (outputFileOrDirectory.IsFile) { var output = outputFileOrDirectory.FileArtifact; int writeCount = output.RewriteCount; int existingMaxWriteCount; if (maxWriteCounts.TryGetValue(output.Path, out existingMaxWriteCount)) { if (writeCount <= existingMaxWriteCount) { continue; } } maxWriteCounts[output.Path] = writeCount; fileArtifacts[output.Path] = outputFileOrDirectory.FileArtifact; } else { Contract.Assert(outputFileOrDirectory.IsDirectory); directoryArtifacts.Add(outputFileOrDirectory.DirectoryArtifact.Path, outputFileOrDirectory.DirectoryArtifact); } } // Map the output files to which pips actually need to run. This is a temporary step until the // scheduler operates on outputs directly. // TODO: This means we can't represent the fact that some but not all outputs of a node are filter-passing. // In the case of a process with some rewritten outputs and some final filter-passing outputs, we are // not be able to guarantee a path is materialized only once (when replaying fully from cache), which is // problematic for reaching an incremental scheduling fixpoint. This can be fixed by materializing on a per-file // rather than per-pip basis. var outputPaths = outputs.Select(a => a.Path).Distinct().ToArray(); Parallel.ForEach( outputPaths, path => { NodeId node; FileArtifact fileArtifact; if (fileArtifacts.TryGetValue(path, out fileArtifact)) { if (PipProducers.TryGetValue(fileArtifact, out node)) { matchingNodes.AddAtomic(node); Interlocked.Increment(ref addAttempts); } else { Contract.Assert(false, "Filtering matched file output that is not registered as being produced by any pip."); } return; } IReadOnlyList<DirectoryArtifact> directoryList; if (directoryArtifacts.TryGetValue(path, out directoryList)) { foreach (var directoryArtifact in directoryList) { if (OutputDirectoryProducers.TryGetValue(directoryArtifact, out node) || m_sealedDirectoryNodes.TryGetValue(directoryArtifact, out node)) { matchingNodes.AddAtomic(node); Interlocked.Increment(ref addAttempts); } else { Contract.Assert(false, "Filtering matched directory output that is not registered as being produced by any pip."); } } } else { Contract.Assert(false, "The path must exist in either fileArtifacts or directoryArtifacts"); } }); filteredIn = matchingNodes; if (addAttempts == 0) { Contract.Assume(outputs.Count == 0); BuildXL.Scheduler.Tracing.Logger.Log.NoPipsMatchedFilter(loggingContext, filter.FilterExpression); return false; } } return true; } private sealed class PipFilterContext : IPipFilterContext { private readonly PipGraph m_graph; /// <summary> /// Cache for <see cref="PipFilter"/> <code>FilterOutputs</code> method. /// </summary> /// <remarks> /// Instead of caching the resulting outputs inside each pip filter instance itself, the cache is placed here /// so that pip filters are reusable for different <see cref="IPipFilterContext"/>s. /// </remarks> private readonly Dictionary<PipFilter, IReadOnlySet<FileOrDirectoryArtifact>> m_cachedOutputs = new Dictionary<PipFilter, IReadOnlySet<FileOrDirectoryArtifact>>(new CachedOutputKeyComparer()); public PipFilterContext(PipGraph graph) { m_graph = graph; } public PathTable PathTable => m_graph.Context.PathTable; public IList<PipId> AllPips => m_graph.PipTable.StableKeys; public Pip HydratePip(PipId pipId) { Contract.Requires(pipId.IsValid); return m_graph.PipTable.HydratePip(pipId, PipQueryContext.PipGraphFilterNodes); } public PipType GetPipType(PipId pipId) { Contract.Requires(pipId.IsValid); return m_graph.PipTable.GetPipType(pipId); } public long GetSemiStableHash(PipId pipId) { Contract.Requires(pipId.IsValid); return m_graph.PipTable.GetPipSemiStableHash(pipId); } public IEnumerable<PipId> GetDependencies(PipId pipId) { Contract.Requires(pipId.IsValid); return m_graph.DataflowGraph.GetIncomingEdges(pipId.ToNodeId()).Select(edge => edge.OtherNode.ToPipId()); } public IEnumerable<PipId> GetDependents(PipId pipId) { Contract.Requires(pipId.IsValid); return m_graph.DataflowGraph.GetOutgoingEdges(pipId.ToNodeId()).Select(edge => edge.OtherNode.ToPipId()); } public PipId GetProducer(in FileOrDirectoryArtifact fileOrDirectory) { Contract.Requires(fileOrDirectory.IsValid); return m_graph.GetProducer(fileOrDirectory); } public bool TryGetCachedOutputs(PipFilter pipFilter, out IReadOnlySet<FileOrDirectoryArtifact> outputs) { return m_cachedOutputs.TryGetValue(pipFilter, out outputs); } public void CacheOutputs(PipFilter pipFilter, IReadOnlySet<FileOrDirectoryArtifact> outputs) { m_cachedOutputs[pipFilter] = outputs; } private class CachedOutputKeyComparer : IEqualityComparer<PipFilter> { public bool Equals(PipFilter x, PipFilter y) { return ReferenceEquals(x, y); } public int GetHashCode(PipFilter obj) { // For filter-output cache key, we use the pointer value of the object // for the following reason: // (1) Caching is beneficial if the pip filter is canonicalized, i.e., reduced to a unique instance. // (2) Computing such a pointer value is cheap. // (3) Computing the hash code of pip filter using GetHashCode is more expensive than just getting // the pointer value, because the calculation of GetHashCode "traverses" the tree/graph structure // of the pip filter. return RuntimeHelpers.GetHashCode(obj); } } } /// <summary> /// Gets filtered outputs appropriate for a clean operation /// </summary> internal IReadOnlyList<FileOrDirectoryArtifact> FilterOutputsForClean(RootFilter filter) { var outputs = FilterOutputs(filter); List<FileOrDirectoryArtifact> outputsForDeletion = new List<FileOrDirectoryArtifact>(outputs.Count); foreach (var output in outputs) { if (output.IsDirectory) { // Only for output directories can the full directory be deleted if (OutputDirectoryProducers.ContainsKey(output.DirectoryArtifact)) { outputsForDeletion.Add(output); } else { // Otherwise, delete the individual output files foreach (var file in ListSealedDirectoryContents(output.DirectoryArtifact)) { if (file.IsOutputFile) { outputsForDeletion.Add(file); } } } } else if (output.FileArtifact.IsOutputFile) { // Only output files can be cleaned outputsForDeletion.Add(output.FileArtifact); } } return outputsForDeletion; } internal IReadOnlySet<FileOrDirectoryArtifact> FilterOutputs(RootFilter filter, bool canonicalizeFilter = true) { Contract.Requires(filter != null); if (filter.IsEmpty) { var outputs = new ReadOnlyHashSet<FileOrDirectoryArtifact>(PipProducers.Keys.Select(FileOrDirectoryArtifact.Create)); outputs.UnionWith(OutputDirectoryProducers.Keys.Select(FileOrDirectoryArtifact.Create)); return outputs; } var context = new PipFilterContext(this); var pipFilter = filter.PipFilter; return pipFilter.FilterOutputs(context); } #endregion Filtering } }
44.984698
251
0.552887
[ "MIT" ]
breidikl/BuildXL
Public/Src/Engine/Scheduler/Graph/PipGraph.cs
58,795
C#
using System; using GoRogue.MapGeneration.Generators; using GoRogue.MapViews; using GrimDank.MObjects; using System.Diagnostics; using GoRogue; namespace GrimDank { /// <summary> /// The main class. /// </summary> static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { using (var game = new GrimDank()) game.Run(); } } }
19.538462
53
0.557087
[ "MIT" ]
TimyJ/GrimDank
GrimDank/Program.cs
510
C#
// 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.Tracing; namespace System.Net { //TODO: If localization resources are not found, logging does not work. Issue #5126. [EventSource(Name = "Microsoft-System-Net-HttpListener", LocalizationResources = "FxResources.System.Net.HttpListener.SR")] internal sealed partial class NetEventSource { } }
36.133333
127
0.752768
[ "MIT" ]
2E0PGS/corefx
src/System.Net.HttpListener/src/System/Net/NetEventSource.HttpListener.cs
542
C#
using System.Linq; using System.Threading.Tasks; using System.Web.Mvc; using JoinRpg.Domain; using JoinRpg.Web.Models; namespace JoinRpg.Web.Controllers { public class UserController : Common.ControllerBase { [HttpGet] public async Task<ActionResult> Details(int userId) { var user = await UserManager.FindByIdAsync(userId); var currentUser = User.Identity.IsAuthenticated ? await GetCurrentUserAsync() : null; var accessReason = (AccessReason) user.GetProfileAccess(currentUser); var userProfileViewModel = new UserProfileViewModel() { DisplayName = user.GetDisplayName(), ThisUserProjects = user.ProjectAcls, UserId = user.UserId, Details = new UserProfileDetailsViewModel(user, accessReason), HasAdminAccess = currentUser?.Auth?.IsAdmin ?? false, IsAdmin = user.Auth?.IsAdmin ?? false, }; if (currentUser != null) { userProfileViewModel.CanGrantAccessProjects = currentUser.GetProjects(acl => acl.CanGrantRights); userProfileViewModel.Claims = new ClaimListViewModel(currentUser.UserId, user.Claims.Where(claim => claim.HasAccess(currentUser.UserId, ExtraAccessReason.Player)).ToArray(), null, showCount: false, showUserColumn: false); } return View(userProfileViewModel); } public UserController(ApplicationUserManager userManager) : base(userManager) { } [HttpGet,Authorize] public ActionResult Me() { return RedirectToAction("Details", new {UserId = CurrentUserId}); } } }
31.314815
113
0.651094
[ "MIT" ]
FulcrumVlsM/joinrpg-net
Joinrpg/Controllers/UserController.cs
1,691
C#
using Native.Sdk.Cqp.Enum; using Native.Sdk.Cqp.Expand; using Native.Sdk.Cqp.Interface; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime; using System.Text; using System.Threading.Tasks; namespace Native.Sdk.Cqp.Model { /// <summary> /// 描述 QQ消息 的类 /// </summary> public class QQMessage : IToSendString { #region --字段-- private List<CQCode> _cqCodes = null; #endregion #region --属性-- /// <summary> /// 获取当前实例用于获取信息的 <see cref="Native.Sdk.Cqp.CQApi"/> 实例对象 /// </summary> public CQApi CQApi { get; private set; } /// <summary> /// 获取当前实例的消息ID /// </summary> public int Id { get; private set; } /// <summary> /// 获取一个值, 指示当前消息是否发送成功. /// </summary> public bool IsSuccess { get { return this.Id >= 0; } } /// <summary> /// 获取当前实例的原始消息 /// </summary> public string Text { get; private set; } /// <summary> /// 获取一个值, 指示当前消息是否为正则消息 /// </summary> public bool IsRegexMessage { get; private set; } /// <summary> /// 获取当前实例解析出的正则消息键值对 /// </summary> [Obsolete ("该属性已过时, 请使用 RegexResult")] public Dictionary<string, string> RegexKeyValuePairs { get { return this.RegexResult; } } /// <summary> /// 获取当前实例解析出的正则消息结果 /// </summary> public Dictionary<string, string> RegexResult { get; private set; } /// <summary> /// 获取当前消息的所有 [CQ:...] 的对象集合 /// </summary> public List<CQCode> CQCodes { get { if (this.IsRegexMessage) { return null; } if (this._cqCodes == null) { _cqCodes = CQCode.Parse (this.Text); } return this._cqCodes; } } /// <summary> /// 获取一个值, 指示该实例是否属于纯图片消息 /// </summary> public bool IsImageMessage { get { return this.CQCodes.All (CQCode.EqualIsImageCQCode); } } /// <summary> /// 获取一个值, 指示该实例是否属于语音消息 /// </summary> public bool IsRecordMessage { get { return this.CQCodes.All (CQCode.EqualIsRecordCQCode); } } #endregion #region --构造函数-- /// <summary> /// 初始化 <see cref="QQMessage"/> 类的新实例 /// </summary> /// <param name="api">用于获取信息的实例</param> /// <param name="id">消息ID</param> /// <param name="msg">消息内容</param> public QQMessage (CQApi api, int id, string msg) : this (api, id, msg, false) { } /// <summary> /// 初始化 <see cref="QQMessage"/> 类的新实例 /// </summary> /// <param name="api">用于获取信息的实例</param> /// <param name="id">消息ID</param> /// <param name="msg">消息内容</param> /// <param name="isRegex">是否正则</param> public QQMessage (CQApi api, int id, string msg, bool isRegex) { if (api == null) { throw new ArgumentNullException ("api"); } if (msg == null) { throw new ArgumentNullException ("msg"); } this.CQApi = api; this.Id = id; this.Text = msg; this.IsRegexMessage = isRegex; this.RegexResult = null; #region --正则事件解析-- if (isRegex) { // 进行正则事件消息解析 this.RegexResult = ParseRegexMessage (msg); } #endregion } #endregion #region --公开方法-- /// <summary> /// 撤回消息 /// </summary> /// <returns>撤回成功返回 <code>true</code>, 失败返回 <code>false</code></returns> public bool RemoveMessage () { return this.CQApi.RemoveMessage (this.Id); } /// <summary> /// 接收消息中的语音 (消息含有CQ码 "record" 的消息) /// </summary> /// <param name="format">所需的目标语音的音频格式</param> /// <returns>返回语音文件位于本地服务器的绝对路径</returns> public string ReceiveRecord (CQAudioFormat format) { if (!this.IsRegexMessage) { CQCode record = (from code in this.CQCodes where code.Function == CQFunction.Record select code).First (); return this.CQApi.ReceiveRecord (record.Items["file"], format); } else { #if DEBUG throw new MethodAccessException ("无法在正则事件中调用 ToSendString, 因为正则事件获取的消息无法用于发送"); #else return null; #endif } } /// <summary> /// 接收消息中指定的图片 (消息含有CQ码 "image" 的消息) /// </summary> /// <param name="index">要接收的图片索引, 该索引从 0 开始</param> /// <returns>返回图片文件位于本地服务器的绝对路径</returns> public string ReceiveImage (int index) { return this.ReceiveAllImage ()[index]; } /// <summary> /// 接收消息中的所有图片 (消息含有CQ码 "image" 的消息) /// </summary> /// <returns>返回图片文件位于本地服务器的绝对路径数组</returns> public string[] ReceiveAllImage () { if (!this.IsRegexMessage) { IEnumerable<CQCode> codes = from code in this.CQCodes where code.Function == CQFunction.Image select code; List<string> list = new List<string> (codes.Count ()); foreach (CQCode code in codes) { list.Add (code.Items["file"]); } return list.ToArray (); } else { #if DEBUG throw new MethodAccessException ("无法在正则事件中调用 ToSendString, 因为正则事件获取的消息无法用于发送"); #else return null; #endif } } /// <summary> /// 返回用于发送的字符串 /// </summary> /// <returns>用于发送的字符串</returns> public string ToSendString () { if (!this.IsRegexMessage) { return this.Text; } #if DEBUG throw new MethodAccessException ("无法在正则事件中调用 ToSendString, 因为正则事件获取的消息无法用于发送"); #else return string.Empty; #endif } /// <summary> /// 确定指定的对象是否等于当前对象 /// </summary> /// <param name="obj">要与当前对象进行比较的对象</param> /// <returns>如果指定的对象等于当前对象,则为 <code>true</code>,否则为 <code>false</code></returns> public override bool Equals (object obj) { QQMessage msg = obj as QQMessage; if (msg != null) { return string.Compare (this.Text, msg.Text) == 0; } return base.Equals (obj); } /// <summary> /// 返回该字符串的哈希代码 /// </summary> /// <returns> 32 位有符号整数哈希代码</returns> public override int GetHashCode () { return this.Text.GetHashCode () & base.GetHashCode (); } /// <summary> /// 返回表示当前对象的字符串 /// </summary> /// <returns>表示当前对象的字符串</returns> public override string ToString () { StringBuilder builder = new StringBuilder (); builder.AppendLine (string.Format ("ID: {0}", this.Id)); builder.AppendLine (string.Format ("正则消息: {0}", this.IsRegexMessage)); builder.AppendLine ("消息: "); if (this.IsRegexMessage) { foreach (KeyValuePair<string, string> keyValue in this.RegexResult) { builder.AppendFormat (" {0}-{1}, ", keyValue.Key, keyValue.Value); } } else { builder.AppendFormat (" {0}", this.Text); } return builder.ToString (); } #endregion #region --私有方法-- /// <summary> /// 比较 <see cref="QQMessage"/> 中的内容和 string 是否相等 /// </summary> /// <param name="msg">相比较的 <see cref="QQMessage"/> 对象</param> /// <param name="str">相比较的字符串</param> /// <returns>如果相同返回 <code>true</code>, 不同返回 <code>false</code></returns> private static bool Equals (QQMessage msg, string str) { if (object.ReferenceEquals (msg, null) || object.ReferenceEquals (str, null)) { return false; } return string.Compare (msg.Text, str) == 0; } /// <summary> /// 解析正则消息 /// </summary> /// <param name="message">需要解析的消息</param> /// <returns>解析成功返回 <see cref="Dictionary{TKey, TValue}"/>, 解析失败返回 <see langword="null"/></returns> private static Dictionary<string, string> ParseRegexMessage (string message) { byte[] data = Convert.FromBase64String (message); if (data == null) { #if DEBUG throw new InvalidDataException ("获取的数据为 null"); #else return null; #endif } using (BinaryReader reader = new BinaryReader (new MemoryStream (data))) { if (reader.Length () < 4) { #if DEBUG throw new InvalidDataException ("读取失败, 原始数据格式错误"); #else return null; #endif } int length = reader.ReadInt32_Ex (); // 获取长度 if (length > 0) { Dictionary<string, string> pairs = new Dictionary<string, string> (length); for (int i = 0; i < length; i++) { using (BinaryReader tempReader = new BinaryReader (new MemoryStream (reader.ReadToken_Ex ()))) { if (tempReader.Length () < 4) { #if DEBUG throw new InvalidDataException ("读取失败, 原始数据格式错误"); #else return null; #endif } // 读取结果 string key = tempReader.ReadString_Ex (CQApi.DefaultEncoding); string content = tempReader.ReadString_Ex (CQApi.DefaultEncoding); pairs.Add (key, content); } } } } return null; } #endregion #region --运算符方法-- /// <summary> /// 确定<see cref="QQMessage"/> 和字符串是否具有相同的值 /// </summary> /// <param name="msg">要比较的第一个<see cref="QQMessage"/>对象,或 null</param> /// <param name="str">要比较的第二个字符串,或 null</param> /// <returns>如果 msg 中的值与 str 相同, 则为 <code>true</code>, 否则为 <code>false</code></returns> [TargetedPatchingOptOut ("性能至关重要的内联跨NGen图像边界")] public static bool operator == (QQMessage msg, string str) { return Equals (msg, str); } /// <summary> /// 确定<see cref="QQMessage"/> 和字符串是否具有相同的值 /// </summary> /// <param name="str">要比较的第一个字符串,或 null</param> /// <param name="msg">要比较的第二个<see cref="QQMessage"/>对象,或 null</param> /// <returns>如果 str与 msg 中的值相同, 则为 <code>true</code>, 否则为 <code>false</code></returns> [TargetedPatchingOptOut ("性能至关重要的内联跨NGen图像边界")] public static bool operator == (string str, QQMessage msg) { return Equals (msg, str); } /// <summary> /// 确定<see cref="QQMessage"/> 和字符串是否具有相同的值 /// </summary> /// <param name="msg">要比较的第一个<see cref="QQMessage"/>对象,或 null</param> /// <param name="str">要比较的第二个字符串,或 null</param> /// <returns>如果 msg 中的值与 str 不同, 则为 <code>true</code>, 否则为 <code>false</code></returns> [TargetedPatchingOptOut ("性能至关重要的内联跨NGen图像边界")] public static bool operator != (QQMessage msg, string str) { return !Equals (msg, str); } /// <summary> /// 确定<see cref="QQMessage"/> 和字符串是否具有相同的值 /// </summary> /// <param name="str">要比较的第一个字符串,或 null</param> /// <param name="msg">要比较的第二个<see cref="QQMessage"/>对象,或 null</param> /// <returns>如果 str与 msg 中的值不同, 则为 <code>true</code>, 否则为 <code>false</code></returns> [TargetedPatchingOptOut ("性能至关重要的内联跨NGen图像边界")] public static bool operator != (string str, QQMessage msg) { return !Equals (msg, str); } #endregion } }
24.651741
110
0.626135
[ "Apache-2.0" ]
hd80606b/AVTOBV
Native.Sdk/Cqp/Model/QQMessage.cs
11,822
C#
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, 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.Drawing; using System.Runtime.InteropServices; namespace Cube.Icons { /* --------------------------------------------------------------------- */ /// /// FileIcon /// /// <summary> /// Provides functionality to get an icon associated by the provided /// file or directory. /// </summary> /// /* --------------------------------------------------------------------- */ public static class FileIcon { #region Methods /* ----------------------------------------------------------------- */ /// /// Get /// /// <summary> /// Gets a new instance of the Icon class with the specified /// arguments. /// </summary> /// /// <param name="src">File or directory path.</param> /// <param name="size">Icon size.</param> /// /// <returns>Icon object.</returns> /// /* ----------------------------------------------------------------- */ public static Icon Get(string src, IconSize size) { var s0 = new ShFileIinfo(); var f0 = 0x4010u; // SHGFI_SYSICONINDEX | SHGFI_USEFILEATTRIBUTES _ = Shell32.NativeMethods.SHGetFileInfo(src, 0, ref s0, (uint)Marshal.SizeOf(s0), f0); var s1 = new Guid("46EB5926-582E-4017-9FDF-E8998DAA0950"); // IID_IImageList var r1 = Shell32.NativeMethods.SHGetImageList((uint)size, s1, out var images); if (r1 != 0 || images == null) return default; var s2 = IntPtr.Zero; var f2 = 0x01; // ILD_TRANSPARENT var r2 = images.GetIcon(s0.iIcon, f2, ref s2); return (r2 == 0 && s2 != IntPtr.Zero) ? Icon.FromHandle(s2) : default; } /* ----------------------------------------------------------------- */ /// /// GetImage /// /// <summary> /// Gets a new instance of the Image instance with the specified /// arguments. /// </summary> /// /// <param name="src">File or directory path.</param> /// <param name="size">Icon size.</param> /// /// <returns>Image object.</returns> /// /* ----------------------------------------------------------------- */ public static Image GetImage(string src, IconSize size) { using var icon = Get(src, size); return icon?.ToBitmap() ?? default; } #endregion } }
35.387097
98
0.460954
[ "Apache-2.0" ]
bubdm/Cube.Core
Libraries/Core/Sources/Icons/FileIcon.cs
3,293
C#
namespace EventTraceKit.EventTracing.Schema.Base { using System.Xml; using System.Xml.Linq; using EventTraceKit.EventTracing.Internal.Extensions; internal sealed class OutType { public OutType(QName xmlType, bool isDefault) { XmlType = xmlType; IsDefault = isDefault; } public QName XmlType { get; } public bool IsDefault { get; } public static OutType Create(XElement elem, IXmlNamespaceResolver resolver) { QName xmlType = elem.GetQName("xmlType"); bool isDefault = elem.GetOptionalBool("default", false); return new OutType(xmlType, isDefault); } } }
26.148148
83
0.617564
[ "MIT" ]
gix/event-trace-kit
src/EventTraceKit.EventTracing/Schema/Base/OutType.cs
706
C#
using Newtonsoft.Json.Linq; namespace Crossroads.Service.HubSpot.Sync.Core.Serialization { public interface IJsonSerializer { string Serialize<T>(T inputToBeSerialized); T Deserialize<T>(string serializedInput, string selector = null); T ToObject<T>(JObject jObject); } //public interface ISerializer<TSerialized, TDeserialized> //{ // TSerialized Serialize(TDeserialized obj); // TDeserialized Deserialize(TSerialized obj); //} }
24.9
73
0.688755
[ "BSD-3-Clause" ]
agause/crds-mp-to-hubspot-sync
Crossroads.Service.HubSpot.Sync.Core/Serialization/IJsonSerializer.cs
500
C#