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 System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.IO; using System.Linq; /* https://blog.sqlauthority.com/2011/10/02/sql-server-ce-list-of-information_schema-system-tables/ -- Get all the columns of the database SELECT * FROM INFORMATION_SCHEMA.COLUMNS -- Get all the indexes of the database SELECT * FROM INFORMATION_SCHEMA.INDEXES -- Get all the indexes and columns of the database SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE -- Get all the datatypes of the database SELECT * FROM INFORMATION_SCHEMA.PROVIDER_TYPES -- Get all the tables of the database SELECT * FROM INFORMATION_SCHEMA.TABLES -- Get all the constraint of the database SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS -- Get all the foreign keys of the database SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS */ namespace LinqToDB.DataProvider.SqlCe { using System.Data.SqlTypes; using Common; using Data; using SchemaProvider; class SqlCeSchemaProvider : SchemaProviderBase { protected override List<TableInfo> GetTables(DataConnection dataConnection, GetSchemaOptions options) { var tables = ((DbConnection)dataConnection.Connection).GetSchema("Tables"); return ( from t in tables.AsEnumerable() where new[] {"TABLE", "VIEW"}.Contains(t.Field<string>("TABLE_TYPE")) let catalog = t.Field<string>("TABLE_CATALOG") let schema = t.Field<string>("TABLE_SCHEMA") let name = t.Field<string>("TABLE_NAME") select new TableInfo { TableID = catalog + '.' + schema + '.' + name, CatalogName = catalog, SchemaName = schema, TableName = name, IsDefaultSchema = schema.IsNullOrEmpty(), IsView = t.Field<string>("TABLE_TYPE") == "VIEW" } ).ToList(); } protected override IReadOnlyCollection<PrimaryKeyInfo> GetPrimaryKeys(DataConnection dataConnection, IEnumerable<TableSchema> tables, GetSchemaOptions options) { var data = dataConnection.Query<PrimaryKeyInfo>( @" SELECT COALESCE(TABLE_CATALOG, '') + '.' + COALESCE(TABLE_SCHEMA, '') + '.' + TABLE_NAME AS TableID, INDEX_NAME AS PrimaryKeyName, COLUMN_NAME AS ColumnName, ORDINAL_POSITION AS Ordinal FROM INFORMATION_SCHEMA.INDEXES WHERE PRIMARY_KEY = 1"); return data.ToList(); } protected override List<ColumnInfo> GetColumns(DataConnection dataConnection, GetSchemaOptions options) { var cs = ((DbConnection)dataConnection.Connection).GetSchema("Columns"); return ( from c in cs.AsEnumerable() select new ColumnInfo { TableID = c.Field<string>("TABLE_CATALOG") + "." + c.Field<string>("TABLE_SCHEMA") + "." + c.Field<string>("TABLE_NAME"), Name = c.Field<string>("COLUMN_NAME")!, IsNullable = c.Field<string>("IS_NULLABLE") == "YES", Ordinal = Converter.ChangeTypeTo<int> (c["ORDINAL_POSITION"]), DataType = c.Field<string>("DATA_TYPE"), Length = Converter.ChangeTypeTo<long>(c["CHARACTER_MAXIMUM_LENGTH"]), Precision = Converter.ChangeTypeTo<int> (c["NUMERIC_PRECISION"]), Scale = Converter.ChangeTypeTo<int> (c["NUMERIC_SCALE"]), IsIdentity = false, } ).ToList(); } protected override IReadOnlyCollection<ForeignKeyInfo> GetForeignKeys(DataConnection dataConnection, IEnumerable<TableSchema> tables, GetSchemaOptions options) { var data = dataConnection.Query<ForeignKeyInfo>( @" SELECT COALESCE(rc.CONSTRAINT_CATALOG, '') + '.' + COALESCE(rc.CONSTRAINT_SCHEMA, '') + '.' + rc.CONSTRAINT_TABLE_NAME ThisTableID, COALESCE(rc.UNIQUE_CONSTRAINT_CATALOG, '') + '.' + COALESCE(rc.UNIQUE_CONSTRAINT_SCHEMA, '') + '.' + rc.UNIQUE_CONSTRAINT_TABLE_NAME OtherTableID, rc.CONSTRAINT_NAME Name, tc.COLUMN_NAME ThisColumn, oc.COLUMN_NAME OtherColumn FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE tc ON tc.CONSTRAINT_NAME = rc.CONSTRAINT_NAME INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE oc ON oc.CONSTRAINT_NAME = rc.UNIQUE_CONSTRAINT_NAME"); return data.ToList(); } protected override string GetDatabaseName(DataConnection dbConnection) { return Path.GetFileNameWithoutExtension(((DbConnection)dbConnection.Connection).Database); } protected override Type? GetSystemType(string? dataType, string? columnType, DataTypeInfo? dataTypeInfo, long? length, int? precision, int? scale, GetSchemaOptions options) { return (dataType?.ToLower()) switch { "tinyint" => typeof(byte), _ => base.GetSystemType(dataType, columnType, dataTypeInfo, length, precision, scale, options), }; } protected override DataType GetDataType(string? dataType, string? columnType, long? length, int? prec, int? scale) { return dataType?.ToLower() switch { "smallint" => DataType.Int16, "int" => DataType.Int32, "real" => DataType.Single, "float" => DataType.Double, "money" => DataType.Money, "bit" => DataType.Boolean, "tinyint" => DataType.Byte, "bigint" => DataType.Int64, "uniqueidentifier" => DataType.Guid, "varbinary" => DataType.VarBinary, "binary" => DataType.Binary, "image" => DataType.Image, "nvarchar" => DataType.NVarChar, "nchar" => DataType.NChar, "ntext" => DataType.NText, "numeric" => DataType.Decimal, "datetime" => DataType.DateTime, "rowversion" => DataType.Timestamp, _ => DataType.Undefined, }; } protected override string GetProviderSpecificTypeNamespace() => SqlTypes.TypesNamespace; protected override string? GetProviderSpecificType(string? dataType) { switch (dataType) { case "varbinary" : case "rowversion" : case "image" : case "binary" : return nameof(SqlBinary); case "tinyint" : return nameof(SqlByte); case "datetime" : return nameof(SqlDateTime); case "bit" : return nameof(SqlBoolean); case "smallint" : return nameof(SqlInt16); case "numeric" : case "decimal" : return nameof(SqlDecimal); case "int" : return nameof(SqlInt32); case "real" : return nameof(SqlSingle); case "float" : return nameof(SqlDouble); case "money" : return nameof(SqlMoney); case "bigint" : return nameof(SqlInt64); case "nvarchar" : case "nchar" : case "ntext" : return nameof(SqlString); case "uniqueidentifier" : return nameof(SqlGuid); } return base.GetProviderSpecificType(dataType); } } }
38.704663
175
0.608835
[ "MIT" ]
Kshitij-Kafle-123/linq2db
Source/LinqToDB/DataProvider/SqlCe/SqlCeSchemaProvider.cs
7,280
C#
using System; namespace TicketingSystem.Areas.HelpPage.ModelDescriptions { /// <summary> /// Describes a type model. /// </summary> public abstract class ModelDescription { public string Documentation { get; set; } public Type ModelType { get; set; } public string Name { get; set; } } }
21.125
58
0.62426
[ "MIT" ]
nkl58/WEB-SERVISI-TIM13
TicketingSystem/TicketingSystem/Areas/HelpPage/ModelDescriptions/ModelDescription.cs
338
C#
using System.IO; using NUnit.Framework; namespace LibDescent3.Tests { class D3BitmapTests { [Test] public void TestReadBitmapHeader() { //Test 1: Unmipped image from HOG2 file. HOG2File hogFile = new HOG2File(TestUtils.GetResourceStream("EXTRA13.HOG")); BinaryReader br = new BinaryReader(hogFile.GetLumpAsStream(0)); Descent3Bitmap bm = Descent3Bitmap.ReadBitmapFromOGFStream(br); Assert.AreEqual(32, bm.Width); Assert.AreEqual(32, bm.Height); Assert.AreEqual(1, bm.MipLevels); Assert.AreEqual(BitmapType.Outrage1555CompressedMipped, bm.Type); Assert.AreEqual(ImageType.Format1555, bm.Format); Assert.AreEqual("BLpyrobottomback1.ogf", bm.Name); //Test 2: Mipped image from disk br.Close(); br = new BinaryReader(TestUtils.GetResourceStream("Angle Tile 1.ogf")); bm = Descent3Bitmap.ReadBitmapFromOGFStream(br); Assert.AreEqual(128, bm.Width); Assert.AreEqual(128, bm.Height); Assert.AreEqual(5, bm.MipLevels); Assert.AreEqual(BitmapType.Outrage1555CompressedMipped, bm.Type); Assert.AreEqual("Angle Tile 1.ogf", bm.Name); Assert.AreEqual(ImageType.Format1555, bm.Format); //Test 3: unmipped 4444 image from disk br.Close(); br = new BinaryReader(TestUtils.GetResourceStream("CED Grid2S.ogf")); bm = Descent3Bitmap.ReadBitmapFromOGFStream(br); Assert.AreEqual(128, bm.Width); Assert.AreEqual(128, bm.Height); Assert.AreEqual(1, bm.MipLevels); Assert.AreEqual(BitmapType.Outrage4444CompressedMipped, bm.Type); Assert.AreEqual("CED Grid2S.ogf", bm.Name); Assert.AreEqual(ImageType.Format4444, bm.Format); } } }
37.686275
88
0.619667
[ "MIT" ]
InsanityBringer/LibDescent3
LibDescent3.Tests/D3BitmapTests.cs
1,924
C#
#if !COREFX using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Xunit; using ProtoBuf; using ProtoBuf.Meta; namespace Examples { public class Pipeline { [Fact] public void TestEnumerable() { EnumWrapper obj = new EnumWrapper(); EnumWrapper clone = Serializer.DeepClone(obj); // the source object should have been read once, but not had any data added Assert.Equal(1, obj.SubData.IteratorCount); //, "obj IteratorCount"); Assert.Equal(0, obj.SubData.Count); //, "obj Count"); Assert.Equal(0, obj.SubData.Sum); //, "obj Sum"); // the destination object should never have been read, but should have // had 5 values added Assert.Equal(0, clone.SubData.IteratorCount); //, "clone IteratorCount"); Assert.Equal(5, clone.SubData.Count); //, "clone Count"); Assert.Equal(1 + 2 + 3 + 4 + 5, clone.SubData.Sum); //, "clone Sum"); } [Fact] public void TestEnumerableProto() { string proto = Serializer.GetProto<EnumWrapper>(); string expected = @"syntax = ""proto2""; package Examples; message EnumWrapper { repeated int32 SubData = 1; } "; Assert.Equal(expected, proto); } [Fact] public void TestEnumerableGroup() { EnumParentGroupWrapper obj = new EnumParentGroupWrapper(); EnumParentGroupWrapper clone = Serializer.DeepClone(obj); // the source object should have been read once, but not had any data added Assert.Equal(1, obj.Wrapper.SubData.IteratorCount); //, "obj IteratorCount"); Assert.Equal(0, obj.Wrapper.SubData.Count); //, "obj Count"); Assert.Equal(0, obj.Wrapper.SubData.Sum); //, "obj Sum"); // the destination object should never have been read, but should have // had 5 values added Assert.Equal(0, clone.Wrapper.SubData.IteratorCount); //, "clone IteratorCount"); Assert.Equal(5, clone.Wrapper.SubData.Count); //, "clone Count"); Assert.Equal(1 + 2 + 3 + 4 + 5, clone.Wrapper.SubData.Sum); //, "clone Sum"); } [Fact] public void TestEnumerableBinary() { EnumParentStandardWrapper obj = new EnumParentStandardWrapper(); Assert.True(Program.CheckBytes(obj, 0x0A, 0x0A, // field 1: obj, 10 bytes 0x08, 0x01, // field 1: variant, 1 0x08, 0x02, // field 1: variant, 2 0x08, 0x03, // field 1: variant, 3 0x08, 0x04, // field 1: variant, 4 0x08, 0x05)); // field 1: variant, 5 } [Fact] public void TestEnumerableStandard() { EnumParentStandardWrapper obj = new EnumParentStandardWrapper(); EnumParentStandardWrapper clone = Serializer.DeepClone(obj); // old: the source object should have been read twice // old: once to get the length-prefix, and once for the data // update: once only with buffering Assert.Equal(1, obj.Wrapper.SubData.IteratorCount); //, "obj IteratorCount"); Assert.Equal(0, obj.Wrapper.SubData.Count); //, "obj Count"); Assert.Equal(0, obj.Wrapper.SubData.Sum); //, "obj Sum"); // the destination object should never have been read, but should have // had 5 values added Assert.Equal(0, clone.Wrapper.SubData.IteratorCount); //, "clone IteratorCount"); Assert.Equal(5, clone.Wrapper.SubData.Count); //, "clone Count"); Assert.Equal(1 + 2 + 3 + 4 + 5, clone.Wrapper.SubData.Sum); //, "clone Sum"); } [Fact] public void TestEnumerableGroupProto() { string proto = Serializer.GetProto<EnumParentGroupWrapper>(); string expected = @"syntax = ""proto2""; package Examples; message EnumParentWrapper { optional group EnumWrapper Wrapper = 1; } message EnumWrapper { repeated int32 SubData = 1; } "; Assert.Equal(expected, proto); } [Fact] public void NWindPipeline() { DAL.Database masterDb = DAL.NWindTests.LoadDatabaseFromFile<DAL.Database>(RuntimeTypeModel.Default); int orderCount = masterDb.Orders.Count, lineCount = masterDb.Orders.Sum(o => o.Lines.Count), unitCount = masterDb.Orders.SelectMany(o => o.Lines).Sum(l => (int)l.Quantity); decimal freight = masterDb.Orders.Sum(order => order.Freight).GetValueOrDefault(), value = masterDb.Orders.SelectMany(o => o.Lines).Sum(l => l.Quantity * l.UnitPrice); Assert.Equal(830, orderCount); Assert.Equal(2155, lineCount); Assert.Equal(51317, unitCount); Assert.Equal(1354458.59M, value); DatabaseReader db = DAL.NWindTests.LoadDatabaseFromFile<DatabaseReader>(RuntimeTypeModel.Default); Assert.Equal(orderCount, db.OrderReader.OrderCount); Assert.Equal(lineCount, db.OrderReader.LineCount); Assert.Equal(unitCount, db.OrderReader.UnitCount); Assert.Equal(freight, db.OrderReader.FreightTotal); Assert.Equal(value, db.OrderReader.ValueTotal); } [ProtoContract] class DatabaseReader { public DatabaseReader() { OrderReader = new OrderReader(); } [ProtoMember(1)] public OrderReader OrderReader { get; private set; } } class OrderReader : IEnumerable<DAL.Order> { public int OrderCount { get; private set; } public int LineCount { get; private set; } public int UnitCount { get; private set; } public decimal FreightTotal { get; private set; } public decimal ValueTotal { get; private set; } public void Add(DAL.Order order) { OrderCount++; LineCount += order.Lines.Count; UnitCount += order.Lines.Sum(l => l.Quantity); FreightTotal += order.Freight.GetValueOrDefault(); ValueTotal += order.Lines.Sum(l => l.UnitPrice * l.Quantity); } IEnumerator<DAL.Order> IEnumerable<DAL.Order>.GetEnumerator() { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } [Fact] public void TestEnumerableStandardProto() { string proto = Serializer.GetProto<EnumParentStandardWrapper>(); string expected = @"syntax = ""proto2""; package Examples; message EnumParentWrapper { optional EnumWrapper Wrapper = 1; } message EnumWrapper { repeated int32 SubData = 1; } "; Assert.Equal(expected, proto); } } [ProtoContract(Name = "EnumParentWrapper")] class EnumParentGroupWrapper { public EnumParentGroupWrapper() { Wrapper = new EnumWrapper(); } [ProtoMember(1, DataFormat = DataFormat.Group)] public EnumWrapper Wrapper { get; private set; } } [ProtoContract(Name = "EnumParentWrapper")] class EnumParentStandardWrapper { public EnumParentStandardWrapper() { Wrapper = new EnumWrapper(); } [ProtoMember(1, DataFormat = DataFormat.Default)] public EnumWrapper Wrapper { get; private set; } } [ProtoContract] class EnumWrapper { public EnumWrapper() { SubData = new EnumData(); } [ProtoMember(1)] public EnumData SubData { get; private set; } } public class EnumData : IEnumerable<int> { public EnumData() { } public int IteratorCount { get; private set; } public int Sum { get; private set; } public int Count { get; private set; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IEnumerator<int> GetEnumerator() { IteratorCount++; yield return 1; yield return 2; yield return 3; yield return 4; yield return 5; } public void Add(int data) { Count++; Sum += data; } } } #endif
34.666667
112
0.582552
[ "Apache-2.0" ]
mustang2247/protobuf-net-ILRuntime
src/Examples/Pipeline.cs
8,530
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis.Semantics; namespace System.Runtime.Analyzers { /// <summary> /// CA2242: Test for NaN correctly /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class TestForNaNCorrectlyAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA2242"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.TestForNaNCorrectlyTitle), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources)); private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.TestForNaNCorrectlyMessage), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.TestForNaNCorrectlyDescription), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources)); internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessage, DiagnosticCategory.Usage, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: s_localizableDescription, helpLinkUri: "https://msdn.microsoft.com/en-us/library/bb264491.aspx", customTags: WellKnownDiagnosticTags.Telemetry); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); private readonly BinaryOperationKind[] _comparisonOperators = new[] { BinaryOperationKind.FloatingEquals, BinaryOperationKind.FloatingGreaterThan, BinaryOperationKind.FloatingGreaterThanOrEqual, BinaryOperationKind.FloatingLessThan, BinaryOperationKind.FloatingLessThanOrEqual, BinaryOperationKind.FloatingNotEquals }; public override void Initialize(AnalysisContext analysisContext) { analysisContext.RegisterOperationAction( operationAnalysisContext => { var binaryOperatorExpression = (IBinaryOperatorExpression)operationAnalysisContext.Operation; if (!_comparisonOperators.Contains(binaryOperatorExpression.BinaryOperationKind)) { return; } if (IsNan(binaryOperatorExpression.LeftOperand) || IsNan(binaryOperatorExpression.RightOperand)) { operationAnalysisContext.ReportDiagnostic( binaryOperatorExpression.Syntax.CreateDiagnostic(Rule)); } }, OperationKind.BinaryOperatorExpression); } private static bool IsNan(IOperation expr) { if (expr == null || !expr.ConstantValue.HasValue) { return false; } object value = expr.ConstantValue.Value; if (value is float) { return float.IsNaN((float)value); } if (value is double) { return double.IsNaN((double)value); } return false; } } }
49.155556
269
0.595389
[ "Apache-2.0" ]
Therzok/roslyn-analyzers
src/System.Runtime.Analyzers/Core/TestForNaNCorrectly.cs
4,424
C#
using System.Collections.Generic; namespace Prolix.Configuration.Ui { public static class UiThemes { public static List<UiThemeInfo> All { get; } static UiThemes() { All = new List<UiThemeInfo> { new UiThemeInfo("Red", "red"), new UiThemeInfo("Pink", "pink"), new UiThemeInfo("Purple", "purple"), new UiThemeInfo("Deep Purple", "deep-purple"), new UiThemeInfo("Indigo", "indigo"), new UiThemeInfo("Blue", "blue"), new UiThemeInfo("Light Blue", "light-blue"), new UiThemeInfo("Cyan", "cyan"), new UiThemeInfo("Teal", "teal"), new UiThemeInfo("Green", "green"), new UiThemeInfo("Light Green", "light-green"), new UiThemeInfo("Lime", "lime"), new UiThemeInfo("Yellow", "yellow"), new UiThemeInfo("Amber", "amber"), new UiThemeInfo("Orange", "orange"), new UiThemeInfo("Deep Orange", "deep-orange"), new UiThemeInfo("Brown", "brown"), new UiThemeInfo("Grey", "grey"), new UiThemeInfo("Blue Grey", "blue-grey"), new UiThemeInfo("Black", "black") }; } } }
36.567568
62
0.493718
[ "MIT" ]
shanesterb/prolix
aspnet-core/src/Prolix.Application/Configuration/Ui/UiThemes.cs
1,355
C#
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.DevTools.ContainerAnalysis.V1.Snippets { using Grafeas.V1; using Google.Api.Gax; using Google.Cloud.Iam.V1; using System.Collections.Generic; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedContainerAnalysisClientSnippets { /// <summary>Snippet for SetIamPolicy</summary> public void SetIamPolicy_RequestObject() { // Snippet: SetIamPolicy(SetIamPolicyRequest, CallSettings) // Create client ContainerAnalysisClient containerAnalysisClient = ContainerAnalysisClient.Create(); // Initialize request argument(s) SetIamPolicyRequest request = new SetIamPolicyRequest { ResourceAsResourceName = new UnknownResourceName("a/wildcard/resource"), Policy = new Policy(), }; // Make the request Policy response = containerAnalysisClient.SetIamPolicy(request); // End snippet } /// <summary>Snippet for SetIamPolicyAsync</summary> public async Task SetIamPolicyAsync_RequestObject() { // Snippet: SetIamPolicyAsync(SetIamPolicyRequest, CallSettings) // Additional: SetIamPolicyAsync(SetIamPolicyRequest, CancellationToken) // Create client ContainerAnalysisClient containerAnalysisClient = await ContainerAnalysisClient.CreateAsync(); // Initialize request argument(s) SetIamPolicyRequest request = new SetIamPolicyRequest { ResourceAsResourceName = new UnknownResourceName("a/wildcard/resource"), Policy = new Policy(), }; // Make the request Policy response = await containerAnalysisClient.SetIamPolicyAsync(request); // End snippet } /// <summary>Snippet for SetIamPolicy</summary> public void SetIamPolicy() { // Snippet: SetIamPolicy(string, Policy, CallSettings) // Create client ContainerAnalysisClient containerAnalysisClient = ContainerAnalysisClient.Create(); // Initialize request argument(s) string resource = "a/wildcard/resource"; Policy policy = new Policy(); // Make the request Policy response = containerAnalysisClient.SetIamPolicy(resource, policy); // End snippet } /// <summary>Snippet for SetIamPolicyAsync</summary> public async Task SetIamPolicyAsync() { // Snippet: SetIamPolicyAsync(string, Policy, CallSettings) // Additional: SetIamPolicyAsync(string, Policy, CancellationToken) // Create client ContainerAnalysisClient containerAnalysisClient = await ContainerAnalysisClient.CreateAsync(); // Initialize request argument(s) string resource = "a/wildcard/resource"; Policy policy = new Policy(); // Make the request Policy response = await containerAnalysisClient.SetIamPolicyAsync(resource, policy); // End snippet } /// <summary>Snippet for SetIamPolicy</summary> public void SetIamPolicy_ResourceNames() { // Snippet: SetIamPolicy(IResourceName, Policy, CallSettings) // Create client ContainerAnalysisClient containerAnalysisClient = ContainerAnalysisClient.Create(); // Initialize request argument(s) IResourceName resource = new UnknownResourceName("a/wildcard/resource"); Policy policy = new Policy(); // Make the request Policy response = containerAnalysisClient.SetIamPolicy(resource, policy); // End snippet } /// <summary>Snippet for SetIamPolicyAsync</summary> public async Task SetIamPolicyAsync_ResourceNames() { // Snippet: SetIamPolicyAsync(IResourceName, Policy, CallSettings) // Additional: SetIamPolicyAsync(IResourceName, Policy, CancellationToken) // Create client ContainerAnalysisClient containerAnalysisClient = await ContainerAnalysisClient.CreateAsync(); // Initialize request argument(s) IResourceName resource = new UnknownResourceName("a/wildcard/resource"); Policy policy = new Policy(); // Make the request Policy response = await containerAnalysisClient.SetIamPolicyAsync(resource, policy); // End snippet } /// <summary>Snippet for GetIamPolicy</summary> public void GetIamPolicy_RequestObject() { // Snippet: GetIamPolicy(GetIamPolicyRequest, CallSettings) // Create client ContainerAnalysisClient containerAnalysisClient = ContainerAnalysisClient.Create(); // Initialize request argument(s) GetIamPolicyRequest request = new GetIamPolicyRequest { ResourceAsResourceName = new UnknownResourceName("a/wildcard/resource"), Options = new GetPolicyOptions(), }; // Make the request Policy response = containerAnalysisClient.GetIamPolicy(request); // End snippet } /// <summary>Snippet for GetIamPolicyAsync</summary> public async Task GetIamPolicyAsync_RequestObject() { // Snippet: GetIamPolicyAsync(GetIamPolicyRequest, CallSettings) // Additional: GetIamPolicyAsync(GetIamPolicyRequest, CancellationToken) // Create client ContainerAnalysisClient containerAnalysisClient = await ContainerAnalysisClient.CreateAsync(); // Initialize request argument(s) GetIamPolicyRequest request = new GetIamPolicyRequest { ResourceAsResourceName = new UnknownResourceName("a/wildcard/resource"), Options = new GetPolicyOptions(), }; // Make the request Policy response = await containerAnalysisClient.GetIamPolicyAsync(request); // End snippet } /// <summary>Snippet for GetIamPolicy</summary> public void GetIamPolicy() { // Snippet: GetIamPolicy(string, CallSettings) // Create client ContainerAnalysisClient containerAnalysisClient = ContainerAnalysisClient.Create(); // Initialize request argument(s) string resource = "a/wildcard/resource"; // Make the request Policy response = containerAnalysisClient.GetIamPolicy(resource); // End snippet } /// <summary>Snippet for GetIamPolicyAsync</summary> public async Task GetIamPolicyAsync() { // Snippet: GetIamPolicyAsync(string, CallSettings) // Additional: GetIamPolicyAsync(string, CancellationToken) // Create client ContainerAnalysisClient containerAnalysisClient = await ContainerAnalysisClient.CreateAsync(); // Initialize request argument(s) string resource = "a/wildcard/resource"; // Make the request Policy response = await containerAnalysisClient.GetIamPolicyAsync(resource); // End snippet } /// <summary>Snippet for GetIamPolicy</summary> public void GetIamPolicy_ResourceNames() { // Snippet: GetIamPolicy(IResourceName, CallSettings) // Create client ContainerAnalysisClient containerAnalysisClient = ContainerAnalysisClient.Create(); // Initialize request argument(s) IResourceName resource = new UnknownResourceName("a/wildcard/resource"); // Make the request Policy response = containerAnalysisClient.GetIamPolicy(resource); // End snippet } /// <summary>Snippet for GetIamPolicyAsync</summary> public async Task GetIamPolicyAsync_ResourceNames() { // Snippet: GetIamPolicyAsync(IResourceName, CallSettings) // Additional: GetIamPolicyAsync(IResourceName, CancellationToken) // Create client ContainerAnalysisClient containerAnalysisClient = await ContainerAnalysisClient.CreateAsync(); // Initialize request argument(s) IResourceName resource = new UnknownResourceName("a/wildcard/resource"); // Make the request Policy response = await containerAnalysisClient.GetIamPolicyAsync(resource); // End snippet } /// <summary>Snippet for TestIamPermissions</summary> public void TestIamPermissions_RequestObject() { // Snippet: TestIamPermissions(TestIamPermissionsRequest, CallSettings) // Create client ContainerAnalysisClient containerAnalysisClient = ContainerAnalysisClient.Create(); // Initialize request argument(s) TestIamPermissionsRequest request = new TestIamPermissionsRequest { ResourceAsResourceName = new UnknownResourceName("a/wildcard/resource"), Permissions = { "", }, }; // Make the request TestIamPermissionsResponse response = containerAnalysisClient.TestIamPermissions(request); // End snippet } /// <summary>Snippet for TestIamPermissionsAsync</summary> public async Task TestIamPermissionsAsync_RequestObject() { // Snippet: TestIamPermissionsAsync(TestIamPermissionsRequest, CallSettings) // Additional: TestIamPermissionsAsync(TestIamPermissionsRequest, CancellationToken) // Create client ContainerAnalysisClient containerAnalysisClient = await ContainerAnalysisClient.CreateAsync(); // Initialize request argument(s) TestIamPermissionsRequest request = new TestIamPermissionsRequest { ResourceAsResourceName = new UnknownResourceName("a/wildcard/resource"), Permissions = { "", }, }; // Make the request TestIamPermissionsResponse response = await containerAnalysisClient.TestIamPermissionsAsync(request); // End snippet } /// <summary>Snippet for TestIamPermissions</summary> public void TestIamPermissions() { // Snippet: TestIamPermissions(string, IEnumerable<string>, CallSettings) // Create client ContainerAnalysisClient containerAnalysisClient = ContainerAnalysisClient.Create(); // Initialize request argument(s) string resource = "a/wildcard/resource"; IEnumerable<string> permissions = new string[] { "", }; // Make the request TestIamPermissionsResponse response = containerAnalysisClient.TestIamPermissions(resource, permissions); // End snippet } /// <summary>Snippet for TestIamPermissionsAsync</summary> public async Task TestIamPermissionsAsync() { // Snippet: TestIamPermissionsAsync(string, IEnumerable<string>, CallSettings) // Additional: TestIamPermissionsAsync(string, IEnumerable<string>, CancellationToken) // Create client ContainerAnalysisClient containerAnalysisClient = await ContainerAnalysisClient.CreateAsync(); // Initialize request argument(s) string resource = "a/wildcard/resource"; IEnumerable<string> permissions = new string[] { "", }; // Make the request TestIamPermissionsResponse response = await containerAnalysisClient.TestIamPermissionsAsync(resource, permissions); // End snippet } /// <summary>Snippet for TestIamPermissions</summary> public void TestIamPermissions_ResourceNames() { // Snippet: TestIamPermissions(IResourceName, IEnumerable<string>, CallSettings) // Create client ContainerAnalysisClient containerAnalysisClient = ContainerAnalysisClient.Create(); // Initialize request argument(s) IResourceName resource = new UnknownResourceName("a/wildcard/resource"); IEnumerable<string> permissions = new string[] { "", }; // Make the request TestIamPermissionsResponse response = containerAnalysisClient.TestIamPermissions(resource, permissions); // End snippet } /// <summary>Snippet for TestIamPermissionsAsync</summary> public async Task TestIamPermissionsAsync_ResourceNames() { // Snippet: TestIamPermissionsAsync(IResourceName, IEnumerable<string>, CallSettings) // Additional: TestIamPermissionsAsync(IResourceName, IEnumerable<string>, CancellationToken) // Create client ContainerAnalysisClient containerAnalysisClient = await ContainerAnalysisClient.CreateAsync(); // Initialize request argument(s) IResourceName resource = new UnknownResourceName("a/wildcard/resource"); IEnumerable<string> permissions = new string[] { "", }; // Make the request TestIamPermissionsResponse response = await containerAnalysisClient.TestIamPermissionsAsync(resource, permissions); // End snippet } } }
46.618421
127
0.644228
[ "Apache-2.0" ]
bijalvakharia/google-cloud-dotnet
apis/Google.Cloud.DevTools.ContainerAnalysis.V1/Google.Cloud.DevTools.ContainerAnalysis.V1.Snippets/ContainerAnalysisClientSnippets.g.cs
14,172
C#
//------------------------------------------------------------------------------ // <auto-generated> // 이 코드는 도구를 사용하여 생성되었습니다. // 런타임 버전:4.0.30319.42000 // // 파일 내용을 변경하면 잘못된 동작이 발생할 수 있으며, 코드를 다시 생성하면 // 이러한 변경 내용이 손실됩니다. // </auto-generated> //------------------------------------------------------------------------------ namespace test_Progress.Properties { /// <summary> /// 지역화된 문자열 등을 찾기 위한 강력한 형식의 리소스 클래스입니다. /// </summary> // 이 클래스는 ResGen 또는 Visual Studio와 같은 도구를 통해 StronglyTypedResourceBuilder // 클래스에서 자동으로 생성되었습니다. // 멤버를 추가하거나 제거하려면 .ResX 파일을 편집한 다음 /str 옵션을 사용하여 // ResGen을 다시 실행하거나 VS 프로젝트를 다시 빌드하십시오. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// 이 클래스에서 사용하는 캐시된 ResourceManager 인스턴스를 반환합니다. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("test_Progress.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// 이 강력한 형식의 리소스 클래스를 사용하여 모든 리소스 조회에 대해 현재 스레드의 CurrentUICulture 속성을 /// 재정의합니다. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
35.75
179
0.580031
[ "MIT" ]
daejinseok/books
C# in a Nutshell/ch14 - task/test_Progress/Properties/Resources.Designer.cs
3,058
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.Linq; using System.Text; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http; using Microsoft.Extensions.Primitives; using Microsoft.Net.Http.Headers; using Xunit; using static CodeGenerator.KnownHeaders; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Tests { public class HttpRequestHeadersTests { [Fact] public void InitialDictionaryIsEmpty() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); Assert.Equal(0, headers.Count); Assert.False(headers.IsReadOnly); } [Fact] public void SettingUnknownHeadersWorks() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); headers["custom"] = new[] { "value" }; var header = Assert.Single(headers["custom"]); Assert.Equal("value", header); } [Fact] public void SettingKnownHeadersWorks() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); headers["host"] = new[] { "value" }; headers["content-length"] = new[] { "0" }; var host = Assert.Single(headers["host"]); var contentLength = Assert.Single(headers["content-length"]); Assert.Equal("value", host); Assert.Equal("0", contentLength); } [Fact] public void KnownAndCustomHeaderCountAddedTogether() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); headers["host"] = new[] { "value" }; headers["custom"] = new[] { "value" }; headers["Content-Length"] = new[] { "0" }; Assert.Equal(3, headers.Count); } [Fact] public void TryGetValueWorksForKnownAndUnknownHeaders() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); StringValues value; Assert.False(headers.TryGetValue("host", out value)); Assert.False(headers.TryGetValue("custom", out value)); Assert.False(headers.TryGetValue("Content-Length", out value)); headers["host"] = new[] { "value" }; Assert.True(headers.TryGetValue("host", out value)); Assert.False(headers.TryGetValue("custom", out value)); Assert.False(headers.TryGetValue("Content-Length", out value)); headers["custom"] = new[] { "value" }; Assert.True(headers.TryGetValue("host", out value)); Assert.True(headers.TryGetValue("custom", out value)); Assert.False(headers.TryGetValue("Content-Length", out value)); headers["Content-Length"] = new[] { "0" }; Assert.True(headers.TryGetValue("host", out value)); Assert.True(headers.TryGetValue("custom", out value)); Assert.True(headers.TryGetValue("Content-Length", out value)); } [Fact] public void SameExceptionThrownForMissingKey() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); Assert.Throws<KeyNotFoundException>(() => headers["custom"]); Assert.Throws<KeyNotFoundException>(() => headers["host"]); Assert.Throws<KeyNotFoundException>(() => headers["Content-Length"]); } [Fact] public void EntriesCanBeEnumerated() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); var v1 = new[] { "localhost" }; var v2 = new[] { "0" }; var v3 = new[] { "value" }; headers["host"] = v1; headers["Content-Length"] = v2; headers["custom"] = v3; Assert.Equal( new[] { new KeyValuePair<string, StringValues>("Host", v1), new KeyValuePair<string, StringValues>("Content-Length", v2), new KeyValuePair<string, StringValues>("custom", v3), }, headers); } [Fact] public void KeysAndValuesCanBeEnumerated() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); StringValues v1 = new[] { "localhost" }; StringValues v2 = new[] { "0" }; StringValues v3 = new[] { "value" }; headers["host"] = v1; headers["Content-Length"] = v2; headers["custom"] = v3; Assert.Equal<string>( new[] { "Host", "Content-Length", "custom" }, headers.Keys); Assert.Equal<StringValues>( new[] { v1, v2, v3 }, headers.Values); } [Fact] public void ContainsAndContainsKeyWork() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); var kv1 = new KeyValuePair<string, StringValues>("host", new[] { "localhost" }); var kv2 = new KeyValuePair<string, StringValues>("custom", new[] { "value" }); var kv3 = new KeyValuePair<string, StringValues>("Content-Length", new[] { "0" }); var kv1b = new KeyValuePair<string, StringValues>("host", new[] { "not-localhost" }); var kv2b = new KeyValuePair<string, StringValues>("custom", new[] { "not-value" }); var kv3b = new KeyValuePair<string, StringValues>("Content-Length", new[] { "1" }); Assert.False(headers.ContainsKey("host")); Assert.False(headers.ContainsKey("custom")); Assert.False(headers.ContainsKey("Content-Length")); Assert.False(headers.Contains(kv1)); Assert.False(headers.Contains(kv2)); Assert.False(headers.Contains(kv3)); headers["host"] = kv1.Value; Assert.True(headers.ContainsKey("host")); Assert.False(headers.ContainsKey("custom")); Assert.False(headers.ContainsKey("Content-Length")); Assert.True(headers.Contains(kv1)); Assert.False(headers.Contains(kv2)); Assert.False(headers.Contains(kv3)); Assert.False(headers.Contains(kv1b)); Assert.False(headers.Contains(kv2b)); Assert.False(headers.Contains(kv3b)); headers["custom"] = kv2.Value; Assert.True(headers.ContainsKey("host")); Assert.True(headers.ContainsKey("custom")); Assert.False(headers.ContainsKey("Content-Length")); Assert.True(headers.Contains(kv1)); Assert.True(headers.Contains(kv2)); Assert.False(headers.Contains(kv3)); Assert.False(headers.Contains(kv1b)); Assert.False(headers.Contains(kv2b)); Assert.False(headers.Contains(kv3b)); headers["Content-Length"] = kv3.Value; Assert.True(headers.ContainsKey("host")); Assert.True(headers.ContainsKey("custom")); Assert.True(headers.ContainsKey("Content-Length")); Assert.True(headers.Contains(kv1)); Assert.True(headers.Contains(kv2)); Assert.True(headers.Contains(kv3)); Assert.False(headers.Contains(kv1b)); Assert.False(headers.Contains(kv2b)); Assert.False(headers.Contains(kv3b)); } [Fact] public void AddWorksLikeSetAndThrowsIfKeyExists() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); StringValues value; Assert.False(headers.TryGetValue("host", out value)); Assert.False(headers.TryGetValue("custom", out value)); Assert.False(headers.TryGetValue("Content-Length", out value)); headers.Add("host", new[] { "localhost" }); headers.Add("custom", new[] { "value" }); headers.Add("Content-Length", new[] { "0" }); Assert.True(headers.TryGetValue("host", out value)); Assert.True(headers.TryGetValue("custom", out value)); Assert.True(headers.TryGetValue("Content-Length", out value)); Assert.Throws<ArgumentException>(() => headers.Add("host", new[] { "localhost" })); Assert.Throws<ArgumentException>(() => headers.Add("custom", new[] { "value" })); Assert.Throws<ArgumentException>(() => headers.Add("Content-Length", new[] { "0" })); Assert.True(headers.TryGetValue("host", out value)); Assert.True(headers.TryGetValue("custom", out value)); Assert.True(headers.TryGetValue("Content-Length", out value)); } [Fact] public void ClearRemovesAllHeaders() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); headers.Add("host", new[] { "localhost" }); headers.Add("custom", new[] { "value" }); headers.Add("Content-Length", new[] { "0" }); StringValues value; Assert.Equal(3, headers.Count); Assert.True(headers.TryGetValue("host", out value)); Assert.True(headers.TryGetValue("custom", out value)); Assert.True(headers.TryGetValue("Content-Length", out value)); headers.Clear(); Assert.Equal(0, headers.Count); Assert.False(headers.TryGetValue("host", out value)); Assert.False(headers.TryGetValue("custom", out value)); Assert.False(headers.TryGetValue("Content-Length", out value)); } [Fact] public void RemoveTakesHeadersOutOfDictionary() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); headers.Add("host", new[] { "localhost" }); headers.Add("custom", new[] { "value" }); headers.Add("Content-Length", new[] { "0" }); StringValues value; Assert.Equal(3, headers.Count); Assert.True(headers.TryGetValue("host", out value)); Assert.True(headers.TryGetValue("custom", out value)); Assert.True(headers.TryGetValue("Content-Length", out value)); Assert.True(headers.Remove("host")); Assert.False(headers.Remove("host")); Assert.Equal(2, headers.Count); Assert.False(headers.TryGetValue("host", out value)); Assert.True(headers.TryGetValue("custom", out value)); Assert.True(headers.Remove("custom")); Assert.False(headers.Remove("custom")); Assert.Equal(1, headers.Count); Assert.False(headers.TryGetValue("host", out value)); Assert.False(headers.TryGetValue("custom", out value)); Assert.True(headers.TryGetValue("Content-Length", out value)); Assert.True(headers.Remove("Content-Length")); Assert.False(headers.Remove("Content-Length")); Assert.Equal(0, headers.Count); Assert.False(headers.TryGetValue("host", out value)); Assert.False(headers.TryGetValue("custom", out value)); Assert.False(headers.TryGetValue("Content-Length", out value)); } [Fact] public void CopyToMovesDataIntoArray() { IDictionary<string, StringValues> headers = new HttpRequestHeaders(); headers.Add("host", new[] { "localhost" }); headers.Add("Content-Length", new[] { "0" }); headers.Add("custom", new[] { "value" }); var entries = new KeyValuePair<string, StringValues>[5]; headers.CopyTo(entries, 1); Assert.Null(entries[0].Key); Assert.Equal(new StringValues(), entries[0].Value); Assert.Equal("Host", entries[1].Key); Assert.Equal(new[] { "localhost" }, entries[1].Value); Assert.Equal("Content-Length", entries[2].Key); Assert.Equal(new[] { "0" }, entries[2].Value); Assert.Equal("custom", entries[3].Key); Assert.Equal(new[] { "value" }, entries[3].Value); Assert.Null(entries[4].Key); Assert.Equal(new StringValues(), entries[4].Value); } [Fact] public void AppendThrowsWhenHeaderNameContainsNonASCIICharacters() { var headers = new HttpRequestHeaders(); const string key = "\u00141\u00F3d\017c"; #pragma warning disable CS0618 // Type or member is obsolete var exception = Assert.Throws<BadHttpRequestException>( #pragma warning restore CS0618 // Type or member is obsolete () => headers.Append(Encoding.Latin1.GetBytes(key), Encoding.ASCII.GetBytes("value"))); Assert.Equal(StatusCodes.Status400BadRequest, exception.StatusCode); } [Theory] [MemberData(nameof(KnownRequestHeaders))] public void ValueReuseOnlyWhenAllowed(bool reuseValue, KnownHeader header) { const string HeaderValue = "Hello"; var headers = new HttpRequestHeaders(reuseHeaderValues: reuseValue); for (var i = 0; i < 6; i++) { var prevName = ChangeNameCase(header.Name, variant: i); var nextName = ChangeNameCase(header.Name, variant: i + 1); var values = GetHeaderValues(headers, prevName, nextName, HeaderValue, HeaderValue); Assert.Equal(HeaderValue, values.PrevHeaderValue); Assert.NotSame(HeaderValue, values.PrevHeaderValue); Assert.Equal(HeaderValue, values.NextHeaderValue); Assert.NotSame(HeaderValue, values.NextHeaderValue); Assert.Equal(values.PrevHeaderValue, values.NextHeaderValue); if (reuseValue) { // When materialized string is reused previous and new should be the same object Assert.Same(values.PrevHeaderValue, values.NextHeaderValue); } else { // When materialized string is not reused previous and new should be the different objects Assert.NotSame(values.PrevHeaderValue, values.NextHeaderValue); } } } [Theory] [MemberData(nameof(KnownRequestHeaders))] public void ValueReuseChangedValuesOverwrite(bool reuseValue, KnownHeader header) { const string HeaderValue1 = "Hello1"; const string HeaderValue2 = "Hello2"; var headers = new HttpRequestHeaders(reuseHeaderValues: reuseValue); for (var i = 0; i < 6; i++) { var prevName = ChangeNameCase(header.Name, variant: i); var nextName = ChangeNameCase(header.Name, variant: i + 1); var values = GetHeaderValues(headers, prevName, nextName, HeaderValue1, HeaderValue2); Assert.Equal(HeaderValue1, values.PrevHeaderValue); Assert.NotSame(HeaderValue1, values.PrevHeaderValue); Assert.Equal(HeaderValue2, values.NextHeaderValue); Assert.NotSame(HeaderValue2, values.NextHeaderValue); Assert.NotEqual(values.PrevHeaderValue, values.NextHeaderValue); } } [Theory] [MemberData(nameof(KnownRequestHeaders))] public void ValueReuseMissingValuesClear(bool reuseValue, KnownHeader header) { const string HeaderValue1 = "Hello1"; var headers = new HttpRequestHeaders(reuseHeaderValues: reuseValue); for (var i = 0; i < 6; i++) { var prevName = ChangeNameCase(header.Name, variant: i); var nextName = ChangeNameCase(header.Name, variant: i + 1); var values = GetHeaderValues(headers, prevName, nextName, HeaderValue1, nextValue: null); Assert.Equal(HeaderValue1, values.PrevHeaderValue); Assert.NotSame(HeaderValue1, values.PrevHeaderValue); Assert.Equal(string.Empty, values.NextHeaderValue); Assert.NotEqual(values.PrevHeaderValue, values.NextHeaderValue); } } [Theory] [MemberData(nameof(KnownRequestHeaders))] public void ValueReuseNeverWhenNotAscii(bool reuseValue, KnownHeader header) { const string HeaderValue = "Hello \u03a0"; var headers = new HttpRequestHeaders(reuseHeaderValues: reuseValue); for (var i = 0; i < 6; i++) { var prevName = ChangeNameCase(header.Name, variant: i); var nextName = ChangeNameCase(header.Name, variant: i + 1); var values = GetHeaderValues(headers, prevName, nextName, HeaderValue, HeaderValue); Assert.Equal(HeaderValue, values.PrevHeaderValue); Assert.NotSame(HeaderValue, values.PrevHeaderValue); Assert.Equal(HeaderValue, values.NextHeaderValue); Assert.NotSame(HeaderValue, values.NextHeaderValue); Assert.Equal(values.PrevHeaderValue, values.NextHeaderValue); Assert.NotSame(values.PrevHeaderValue, values.NextHeaderValue); } } [Theory] [MemberData(nameof(KnownRequestHeaders))] public void ValueReuseLatin1NotConfusedForUtf16AndStillRejected(bool reuseValue, KnownHeader header) { var headers = new HttpRequestHeaders(reuseHeaderValues: reuseValue); var headerValue = new char[127]; // 64 + 32 + 16 + 8 + 4 + 2 + 1 for (var i = 0; i < headerValue.Length; i++) { headerValue[i] = 'a'; } for (var i = 0; i < headerValue.Length; i++) { // Set non-ascii Latin char that is valid Utf16 when widened; but not a valid utf8 -> utf16 conversion. headerValue[i] = '\u00a3'; for (var mode = 0; mode <= 1; mode++) { string headerValueUtf16Latin1CrossOver; if (mode == 0) { // Full length headerValueUtf16Latin1CrossOver = new string(headerValue); } else { // Truncated length (to ensure different paths from changing lengths in matching) headerValueUtf16Latin1CrossOver = new string(headerValue.AsSpan().Slice(0, i + 1)); } headers.Reset(); var headerName = Encoding.ASCII.GetBytes(header.Name).AsSpan(); var prevSpan = Encoding.UTF8.GetBytes(headerValueUtf16Latin1CrossOver).AsSpan(); headers.Append(headerName, prevSpan); headers.OnHeadersComplete(); var prevHeaderValue = ((IHeaderDictionary)headers)[header.Name].ToString(); Assert.Equal(headerValueUtf16Latin1CrossOver, prevHeaderValue); Assert.NotSame(headerValueUtf16Latin1CrossOver, prevHeaderValue); headers.Reset(); Assert.Throws<InvalidOperationException>(() => { var headerName = Encoding.ASCII.GetBytes(header.Name).AsSpan(); var nextSpan = Encoding.Latin1.GetBytes(headerValueUtf16Latin1CrossOver).AsSpan(); Assert.False(nextSpan.SequenceEqual(Encoding.ASCII.GetBytes(headerValueUtf16Latin1CrossOver))); headers.Append(headerName, nextSpan); }); } // Reset back to Ascii headerValue[i] = 'a'; } } [Theory] [MemberData(nameof(KnownRequestHeaders))] public void Latin1ValuesAcceptedInLatin1ModeButNotReused(bool reuseValue, KnownHeader header) { var headers = new HttpRequestHeaders(reuseHeaderValues: reuseValue, _ => Encoding.Latin1); var headerValue = new char[127]; // 64 + 32 + 16 + 8 + 4 + 2 + 1 for (var i = 0; i < headerValue.Length; i++) { headerValue[i] = 'a'; } for (var i = 0; i < headerValue.Length; i++) { // Set non-ascii Latin char that is valid Utf16 when widened; but not a valid utf8 -> utf16 conversion. headerValue[i] = '\u00a3'; for (var mode = 0; mode <= 1; mode++) { string headerValueUtf16Latin1CrossOver; if (mode == 0) { // Full length headerValueUtf16Latin1CrossOver = new string(headerValue); } else { // Truncated length (to ensure different paths from changing lengths in matching) headerValueUtf16Latin1CrossOver = new string(headerValue.AsSpan().Slice(0, i + 1)); } var headerName = Encoding.ASCII.GetBytes(header.Name).AsSpan(); var latinValueSpan = Encoding.Latin1.GetBytes(headerValueUtf16Latin1CrossOver).AsSpan(); Assert.False(latinValueSpan.SequenceEqual(Encoding.ASCII.GetBytes(headerValueUtf16Latin1CrossOver))); headers.Reset(); headers.Append(headerName, latinValueSpan); headers.OnHeadersComplete(); var parsedHeaderValue1 = ((IHeaderDictionary)headers)[header.Name].ToString(); headers.Reset(); headers.Append(headerName, latinValueSpan); headers.OnHeadersComplete(); var parsedHeaderValue2 = ((IHeaderDictionary)headers)[header.Name].ToString(); Assert.Equal(headerValueUtf16Latin1CrossOver, parsedHeaderValue1); Assert.Equal(parsedHeaderValue1, parsedHeaderValue2); Assert.NotSame(parsedHeaderValue1, parsedHeaderValue2); } // Reset back to Ascii headerValue[i] = 'a'; } } [Theory] [MemberData(nameof(KnownRequestHeaders))] public void NullCharactersRejectedInUTF8AndLatin1Mode(bool useLatin1, KnownHeader header) { var headers = new HttpRequestHeaders(encodingSelector: useLatin1 ? _ => Encoding.Latin1 : (Func<string, Encoding>)null); var valueArray = new char[127]; // 64 + 32 + 16 + 8 + 4 + 2 + 1 for (var i = 0; i < valueArray.Length; i++) { valueArray[i] = 'a'; } for (var i = 1; i < valueArray.Length; i++) { // Set non-ascii Latin char that is valid Utf16 when widened; but not a valid utf8 -> utf16 conversion. valueArray[i] = '\0'; string valueString = new string(valueArray); headers.Reset(); Assert.Throws<InvalidOperationException>(() => { var headerName = Encoding.ASCII.GetBytes(header.Name).AsSpan(); var valueSpan = Encoding.ASCII.GetBytes(valueString).AsSpan(); headers.Append(headerName, valueSpan); }); valueArray[i] = 'a'; } } [Fact] public void CanSpecifyEncodingBasedOnHeaderName() { const string headerValue = "Hello \u03a0"; var acceptNameBytes = Encoding.ASCII.GetBytes(HeaderNames.Accept); var cookieNameBytes = Encoding.ASCII.GetBytes(HeaderNames.Cookie); var headerValueBytes = Encoding.UTF8.GetBytes(headerValue); var headers = new HttpRequestHeaders(encodingSelector: headerName => { // For known headers, the HeaderNames value is passed in. if (ReferenceEquals(headerName, HeaderNames.Accept)) { return Encoding.GetEncoding("ASCII", EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback); } return Encoding.UTF8; }); Assert.Throws<InvalidOperationException>(() => headers.Append(acceptNameBytes, headerValueBytes)); headers.Append(cookieNameBytes, headerValueBytes); headers.OnHeadersComplete(); var parsedAcceptHeaderValue = ((IHeaderDictionary)headers).Accept.ToString(); var parsedCookieHeaderValue = ((IHeaderDictionary)headers).Cookie.ToString(); Assert.Empty(parsedAcceptHeaderValue); Assert.Equal(headerValue, parsedCookieHeaderValue); } [Fact] public void CanSpecifyEncodingForContentLength() { var contentLengthNameBytes = Encoding.ASCII.GetBytes(HeaderNames.ContentLength); // Always 32 bits per code point, so not a superset of ASCII var contentLengthValueBytes = Encoding.UTF32.GetBytes("1337"); var headers = new HttpRequestHeaders(encodingSelector: _ => Encoding.UTF32); headers.Append(contentLengthNameBytes, contentLengthValueBytes); headers.OnHeadersComplete(); Assert.Equal(1337, headers.ContentLength); Assert.Throws<InvalidOperationException>(() => new HttpRequestHeaders().Append(contentLengthNameBytes, contentLengthValueBytes)); } [Fact] public void ValueReuseNeverWhenUnknownHeader() { const string HeaderName = "An-Unknown-Header"; const string HeaderValue = "Hello"; var headers = new HttpRequestHeaders(reuseHeaderValues: true); for (var i = 0; i < 6; i++) { var prevName = ChangeNameCase(HeaderName, variant: i); var nextName = ChangeNameCase(HeaderName, variant: i + 1); var values = GetHeaderValues(headers, prevName, nextName, HeaderValue, HeaderValue); Assert.Equal(HeaderValue, values.PrevHeaderValue); Assert.NotSame(HeaderValue, values.PrevHeaderValue); Assert.Equal(HeaderValue, values.NextHeaderValue); Assert.NotSame(HeaderValue, values.NextHeaderValue); Assert.Equal(values.PrevHeaderValue, values.NextHeaderValue); Assert.NotSame(values.PrevHeaderValue, values.NextHeaderValue); } } [Theory] [MemberData(nameof(KnownRequestHeaders))] public void ValueReuseEmptyAfterReset(bool reuseValue, KnownHeader header) { const string HeaderValue = "Hello"; var headers = new HttpRequestHeaders(reuseHeaderValues: reuseValue); var headerName = Encoding.ASCII.GetBytes(header.Name).AsSpan(); var prevSpan = Encoding.UTF8.GetBytes(HeaderValue).AsSpan(); headers.Append(headerName, prevSpan); headers.OnHeadersComplete(); var prevHeaderValue = ((IHeaderDictionary)headers)[header.Name].ToString(); Assert.NotNull(prevHeaderValue); Assert.NotEqual(string.Empty, prevHeaderValue); Assert.Equal(HeaderValue, prevHeaderValue); Assert.NotSame(HeaderValue, prevHeaderValue); Assert.Single(headers); var count = headers.Count; Assert.Equal(1, count); headers.Reset(); // Empty after reset var nextHeaderValue = ((IHeaderDictionary)headers)[header.Name].ToString(); Assert.NotNull(nextHeaderValue); Assert.Equal(string.Empty, nextHeaderValue); Assert.NotEqual(HeaderValue, nextHeaderValue); Assert.Empty(headers); count = headers.Count; Assert.Equal(0, count); headers.OnHeadersComplete(); // Still empty after complete nextHeaderValue = ((IHeaderDictionary)headers)[header.Name].ToString(); Assert.NotNull(nextHeaderValue); Assert.Equal(string.Empty, nextHeaderValue); Assert.NotEqual(HeaderValue, nextHeaderValue); Assert.Empty(headers); count = headers.Count; Assert.Equal(0, count); } [Theory] [MemberData(nameof(KnownRequestHeaders))] public void MultiValueReuseEmptyAfterReset(bool reuseValue, KnownHeader header) { const string HeaderValue1 = "Hello1"; const string HeaderValue2 = "Hello2"; var headers = new HttpRequestHeaders(reuseHeaderValues: reuseValue); var headerName = Encoding.ASCII.GetBytes(header.Name).AsSpan(); var prevSpan1 = Encoding.UTF8.GetBytes(HeaderValue1).AsSpan(); var prevSpan2 = Encoding.UTF8.GetBytes(HeaderValue2).AsSpan(); headers.Append(headerName, prevSpan1); headers.Append(headerName, prevSpan2); headers.OnHeadersComplete(); var prevHeaderValue = ((IHeaderDictionary)headers)[header.Name]; Assert.Equal(2, prevHeaderValue.Count); Assert.NotEqual(string.Empty, prevHeaderValue.ToString()); Assert.Single(headers); var count = headers.Count; Assert.Equal(1, count); headers.Reset(); // Empty after reset var nextHeaderValue = ((IHeaderDictionary)headers)[header.Name].ToString(); Assert.NotNull(nextHeaderValue); Assert.Equal(string.Empty, nextHeaderValue); Assert.Empty(headers); count = headers.Count; Assert.Equal(0, count); headers.OnHeadersComplete(); // Still empty after complete nextHeaderValue = ((IHeaderDictionary)headers)[header.Name].ToString(); Assert.NotNull(nextHeaderValue); Assert.Equal(string.Empty, nextHeaderValue); Assert.Empty(headers); count = headers.Count; Assert.Equal(0, count); } private static (string PrevHeaderValue, string NextHeaderValue) GetHeaderValues(HttpRequestHeaders headers, string prevName, string nextName, string prevValue, string nextValue) { headers.Reset(); var headerName = Encoding.ASCII.GetBytes(prevName).AsSpan(); var prevSpan = Encoding.UTF8.GetBytes(prevValue).AsSpan(); headers.Append(headerName, prevSpan); headers.OnHeadersComplete(); var prevHeaderValue = ((IHeaderDictionary)headers)[prevName].ToString(); headers.Reset(); if (nextValue != null) { headerName = Encoding.ASCII.GetBytes(prevName).AsSpan(); var nextSpan = Encoding.UTF8.GetBytes(nextValue).AsSpan(); headers.Append(headerName, nextSpan); } headers.OnHeadersComplete(); var newHeaderValue = ((IHeaderDictionary)headers)[nextName].ToString(); return (prevHeaderValue, newHeaderValue); } private static string ChangeNameCase(string name, int variant) { switch ((variant / 2) % 3) { case 0: return name; case 1: return name.ToLowerInvariant(); case 2: return name.ToUpperInvariant(); } // Never reached Assert.False(true); return name; } // Content-Length is numeric not a string, so we exclude it from the string reuse tests public static IEnumerable<object[]> KnownRequestHeaders => RequestHeaders.Where(h => h.Name != "Content-Length").Select(h => new object[] { true, h }).Concat( RequestHeaders.Where(h => h.Name != "Content-Length").Select(h => new object[] { false, h })); } }
40.866499
185
0.577694
[ "MIT" ]
FWest98/MicrosoftAspNetCore
src/Servers/Kestrel/Core/test/HttpRequestHeadersTests.cs
32,448
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace TomJulie { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddOrchardCms(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseOrchardCore(); } } }
28.166667
106
0.650888
[ "MIT" ]
tom-mckinney/tom-and-julie
TomJulie/Startup.cs
1,016
C#
namespace MrRobot.Core.Boundaries.Clean { using System.Collections.Generic; public sealed class Request : IRequest { public Position InitialPosition { get; } public IList<Command> Commands { get; } public Request(Position initialPosition, IList<Command> commands) { InitialPosition = initialPosition; Commands = commands; } } }
25.5625
73
0.633252
[ "Apache-2.0" ]
ivanpaulovich/MrRobot
source/MrRobot.Core/Boundaries/Clean/Request.cs
409
C#
using System; namespace IndependentReserve.DotNetClientApi.Data { /// <summary> /// Your independent reserve bank account; when you confirm your user account we create accounts for you in digital and fiat currencies /// </summary> public class Account { /// <summary> /// Account guid /// </summary> public Guid AccountGuid { get; set; } /// <summary> /// Gets account status /// </summary> public AccountStatus AccountStatus { get; set; } /// <summary> /// Gets current available balance of this bank account, thats it total balance minus all funds reserved by account orders /// </summary> public decimal AvailableBalance { get; set; } /// <summary> /// Gets account's currency /// </summary> public CurrencyCode CurrencyCode { get; set; } /// <summary> /// Gets total current balance of this bank account /// </summary> public decimal TotalBalance { get; set; } } }
29.416667
139
0.588291
[ "Apache-2.0" ]
independentreserve/dotNetApiClient
src/DotNetClientApi/Data/Account.cs
1,061
C#
using System; using System.Collections.Generic; namespace Monospace.NoThreads.AsyncCoroutines { public class Coordinator<T> { private readonly Queue<Action> _actions = new Queue<Action>(); public Coordinator(IEnumerable<Func<Coordinator<T>, Action>> coroutines) { // prime continuation queue with each coroutine's entrypoint foreach(var coroutine in coroutines) { _actions.Enqueue(coroutine(this)); } } public void Execute() { // iterate over continuations while(_actions.Count > 0) { _actions.Dequeue().Invoke(); } } // the shared state for all coroutines public T State { get; set; } // required to make Coordinator "await"able public Coordinator<T> GetAwaiter() { return this; } // has the awaitable finished? public bool IsCompleted { get { return false; } } // if it hasn't finished here's the continuation to pick up execution public void OnCompleted(Action continuation) { // put the continuation into the queue, so we can pick it back up when we've run the other coroutine continuations in line _actions.Enqueue(continuation); } // the value of the awaitable (void for the coordinator) public void GetResult() { } } }
32.133333
135
0.594053
[ "Apache-2.0" ]
MindTouch/Monospace.NoThreads
Monospace.NoThreads.AsyncCoroutines/Coordinator.cs
1,446
C#
using System; using System.ComponentModel; using System.Runtime.InteropServices; namespace DCSoftDotfuscate { [Serializable] [ComVisible(false)] public class GClass401 : GClass383 { private string string_0 = null; [DefaultValue(null)] public string Name { get { return string_0; } set { string_0 = value; } } public override string ToString() { return "BookMark:" + string_0; } } }
13.59375
37
0.666667
[ "MIT" ]
h1213159982/HDF
Example/WinForm/Editor/DCWriter/DCSoft.Writer.Cleaned/DCSoftDotfuscate/GClass401.cs
435
C#
namespace DedicatingServerMatchMaker.Enums { public enum EGameServerState { None = 0, Starting = 1, Running = 2, } }
15.3
42
0.575163
[ "MIT" ]
insthync/dedicating-server-maker-unity
Scripts/Enums/EGameServerState.cs
153
C#
using System.Collections; using System.Collections.Generic; using EventType = ColaFrame.EventType; /// <summary> /// 接收消息后触发的回调 /// </summary> /// <param name="data"></param> public delegate void MsgHandler(EventData data); /// <summary> /// 事件处理器的接口 /// </summary> public interface IEventHandler { bool HandleMessage(GameEvent evt); bool IsHasHandler(GameEvent evt); } /// <summary> /// 事件消息传递的数据 /// </summary> public class EventData { public string Cmd; public List<object> ParaList; } /// <summary> /// 游戏中的事件 /// </summary> public class GameEvent { /// <summary> /// 事件类型 /// </summary> public EventType EventType { get; set; } /// <summary> /// 携带参数 /// </summary> public object Para { get; set; } } namespace ColaFrame { /// <summary> /// 事件的类型 /// </summary> public enum EventType : byte { /// <summary> /// 系统的消息 /// </summary> SystemMsg = 0, /// <summary> /// 来自服务器推送的消息 /// </summary> ServerMsg = 1, /// <summary> /// UI界面消息 /// </summary> UIMsg = 2, } }
16.808824
48
0.552931
[ "MIT" ]
Aver58/ColaFrameWork
Assets/Scripts/Global/EventData.cs
1,275
C#
using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using ICSharpCode.CodeConverter.DotNetTool.Util; using McMaster.Extensions.CommandLineUtils; namespace ICSharpCode.CodeConverter.CommandLine.Util; internal static class DirectoryInfoExtensions { public static async Task CopyExceptAsync(this DirectoryInfo sourceDirectory, DirectoryInfo targetDirectory, bool overwrite, params string[] excludeNames) { targetDirectory.Create(); foreach (var fileSystemEntry in sourceDirectory.GetFileSystemInfos().Where(d => !excludeNames.Contains(d.Name, StringComparer.OrdinalIgnoreCase))) { var targetPath = Path.Combine(targetDirectory.FullName, fileSystemEntry.Name); if (fileSystemEntry is DirectoryInfo currentSourceDir) { await CopyExceptAsync(currentSourceDir, new DirectoryInfo(targetPath), overwrite, excludeNames); } else if (fileSystemEntry is FileInfo fi) { await fi.RetryAsync(f => f.CopyTo(targetPath, overwrite)); } } } /// <returns>true iff directory is completely deleted</returns> public static async Task<bool> DeleteExceptAsync(this DirectoryInfo targetDirectory, params string[] excludeNames) { if (!targetDirectory.Exists) return true; var filesAndDirs = targetDirectory.GetFileSystemInfos(); var excluded = filesAndDirs.Where(d => excludeNames.Contains(d.Name, StringComparer.OrdinalIgnoreCase)).ToArray(); bool foundExclusion = excluded.Any(); foreach (var fileSystemInfo in filesAndDirs.Except(excluded)) { if (fileSystemInfo is DirectoryInfo di) { foundExclusion |= await DeleteExceptAsync(di, excludeNames); } else { fileSystemInfo.Delete(); } } if (!foundExclusion) await targetDirectory.RetryAsync(d => d.Delete(true)); return !foundExclusion; } private static async Task RetryAsync<T>(this T fileSystemInfo, Action<T> action, byte retries = 10, ushort delayMs = 10) where T: FileSystemInfo { for (int i = 0; i <= retries; i++) { try { action(fileSystemInfo); return; } catch (Exception) when (i < retries) { await Task.Delay(delayMs); fileSystemInfo.Refresh(); } } } public static async Task<bool> IsGitDiffEmptyAsync(this DirectoryInfo outputDirectory) { var gitDiff = new ProcessStartInfo("git") { Arguments = ArgumentEscaper.EscapeAndConcatenate(new[] { "diff", "--exit-code", "--relative", "--summary", "--diff-filter=ACMRTUXB*" }), WorkingDirectory = outputDirectory.FullName }; var (exitCode, stdErr, _) = await gitDiff.GetOutputAsync(); if (exitCode == 1) Console.WriteLine(stdErr); return exitCode == 0; } public static bool ContainsDataOtherThanGitDir(this DirectoryInfo outputDirectory) { var filesAndFolders = outputDirectory.GetFileSystemInfos(); return filesAndFolders.Any(d => !string.Equals(d.Name, ".git", StringComparison.OrdinalIgnoreCase)); } }
44.16
158
0.650966
[ "MIT" ]
BingCheng21/CodeConverter
CommandLine/CodeConv.Shared/Util/DirectoryInfoExtensions.cs
3,240
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using Voxel.View; using Voxel.Model.Languages; using System.IO; using System.Diagnostics; using System.Windows.Input; using System.Windows.Controls; namespace Voxel.ViewModel { sealed class MainViewModel : ViewModel { public MainViewModel(MainView mainView) : base(new MainLanguage()) { View = mainView; } public MainView View { get; private set; } public string WindowTitle => language[nameof(WindowTitle)]; public string ButtonNonscalableTile => language[nameof(ButtonNonscalableTile)]; public string ButtonScalableTile => language[nameof(ButtonScalableTile)]; public string ButtonImageTile => language[nameof(ButtonImageTile)]; public string ButtonClearTileCache => language[nameof(ButtonClearTileCache)]; public static void ClearTileCache(Func<FileInfo, bool> fileFilter = null) { void clearTileCacheInFolder(DirectoryInfo directoryInfo) { var subDirs = directoryInfo.EnumerateDirectories(); if (subDirs.Count() != 0) { foreach (var subDir in subDirs) { clearTileCacheInFolder(subDir); } } foreach (var file in directoryInfo.EnumerateFiles()) { try { if (fileFilter?.Invoke(file) ?? true) { file.LastWriteTime = DateTime.Now; } } catch (IOException) { continue; } catch (UnauthorizedAccessException) { continue; } } } DirectoryInfo commonStart = new DirectoryInfo(Environment.GetEnvironmentVariable("ProgramData") + @"\Microsoft\Windows\Start Menu\Programs"); DirectoryInfo userStart = new DirectoryInfo(Environment.GetEnvironmentVariable("UserProfile") + @"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs"); clearTileCacheInFolder(commonStart); clearTileCacheInFolder(userStart); } private bool isClearTileCacheBusy = false; public bool IsClearTileCacheBusy { get => isClearTileCacheBusy; set { isClearTileCacheBusy = value; View.Cursor = value ? Cursors.AppStarting : Cursors.Arrow; OnPropertyChanged(nameof(IsClearTileCacheBusy)); } } //private bool isNonscalableTileBusy; //public bool IsNonscalableTileBusy //{ // get => isNonscalableTileBusy; // set // { // isNonscalableTileBusy = value; // View.Cursor = value ? Cursors.AppStarting : Cursors.Arrow; // OnPropertyChanged(nameof(IsNonscalableTileBusy)); // } //} public BindingCommand NonscalableTileCommand => new BindingCommand { ExcuteAction = (o) => { View.NonscalableTileView.Owner = View; View.NonscalableTileView.ShowDialog(); }, }; public BindingCommand ImageTileCommand => new BindingCommand { ExcuteAction = (o) => { //View.ImageTileView.Owner = View; //View.ImageTileView.ShowDialog(); }, }; public BindingCommand ClearTileCacheCommand => new BindingCommand { ExcuteAction = async (o) => { if (!Ace.Utils.IsAdministratorProcess) { View.ShowMessage(App.GeneralLanguage["AdminTip"], language["ClearFailedTitle"], false); return; } IsClearTileCacheBusy = true; await Task.Run(() => { ClearTileCache(); View.Dispatcher.Invoke(() => { View.ShowMessage("", language["ClearSuccessTitle"], false); }); }); IsClearTileCacheBusy = false; }, }; public BindingCommand AboutCommand => new BindingCommand { ExcuteAction = (o) => { //var window = new AboutView //{ // Owner = View //}; //window.ShowDialog(); }, }; } }
32.437086
167
0.508167
[ "MIT" ]
the1812/Voxel
Voxel/ViewModel/MainViewModel.cs
4,898
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ArtEvolver.Extensions { public static class DoubleExtensions { public static bool IsNumber(this double value) { return MathUtility.IsNumber(value); } public static bool IsNaN(this double value) { return double.IsNaN(value); } } }
16.666667
48
0.74
[ "MIT" ]
MarcosLopezC/ArtEvolver2014
Sources/Extensions/DoubleExtensions.cs
352
C#
using System; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; namespace WonderTools.Inspector { public class InspectorMiddleWare { private readonly InspectorRepository _repository; private readonly InspectorOptions _options; public InspectorMiddleWare(InspectorRepository repository, InspectorOptions options) { _repository = repository; _options = options; } public async Task Process(HttpContext context, Func<Task> next) { var path = context.Request.Path; var method = context.Request.Method; if (IsRequestForInspection(path, method)) await HandleInspection(context); else if (IsRequestForPreflightInspection(path, method)) await HandlePreflight(context); else if (IsRequestForInspectionLogin(path, method)) await HandleInspectionLogin(context); else await next.Invoke(); } private bool IsRequestForPreflightInspection(string path, string method) { return IsRequestValid(path, method, _options.GetInspectorUri(), "options"); } private bool IsRequestForInspectionLogin(string path, string method) { return IsRequestValid(path, method, _options.GetInspectorLoginUri(), "get"); } private bool IsRequestForInspection(string path, string method) { return IsRequestValid(path, method, _options.GetInspectorUri(), "get"); } private bool IsRequestValid(string requestPath, string requestMethod, string expectedPath, string expectedMethod) { if (string.IsNullOrWhiteSpace(requestPath)) return false; if (string.IsNullOrEmpty(requestMethod)) return false; if (!requestMethod.Equals(expectedMethod, StringComparison.InvariantCultureIgnoreCase)) return false; if (requestPath.Equals(expectedPath, StringComparison.InvariantCultureIgnoreCase)) return true; if (requestPath.Equals(expectedPath + "/", StringComparison.InvariantCultureIgnoreCase)) return true; return false; } private async Task HandlePreflight(HttpContext context) { if (_options.IsCorsEnabled) { AddCorsResponseHeaders(context); context.Response.StatusCode = 204; await context.Response.WriteAsync(string.Empty, Encoding.UTF8); } else { await RespondWith404(context); } } private static async Task RespondWith404(HttpContext context) { context.Response.StatusCode = 404; await context.Response.WriteAsync(string.Empty); } private static async Task RespondWith403(HttpContext context) { context.Response.StatusCode = 403; await context.Response.WriteAsync(string.Empty); } private static void AddCorsResponseHeaders(HttpContext context) { context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); context.Response.Headers.Add("Access-Control-Allow-Credentials", "true"); context.Response.Headers.Add("Access-Control-Allow-Headers", "*"); context.Response.Headers.Add("Access-Control-Allow-Methods", "GET"); context.Response.Headers.Add("Vary", new[] {"Origin"}); } private async Task HandleInspection(HttpContext context) { var isAuthenticated = true; if (_options.Authenticator != null) { isAuthenticated = IsAuthenticated(context); } if (isAuthenticated) await RespondWithData(context); else await RespondWith403(context); } private bool IsAuthenticated(HttpContext context) { if (!context.Request.Headers.ContainsKey(_options.AuthenticationHeader)) return false; var token = context.Request.Headers[_options.AuthenticationHeader]; return _options.Authenticator(token); } private async Task RespondWithData(HttpContext context) { context.Response.StatusCode = 200; context.Response.ContentType = "application/json"; var dictionary = _repository.GetDictionary(); if (_options.IsCorsEnabled) AddCorsResponseHeaders(context); var jsonString = JsonConvert.SerializeObject(dictionary, Formatting.Indented); await context.Response.WriteAsync(jsonString, Encoding.UTF8); } private async Task HandleInspectionLogin(HttpContext context) { if (!_options.IsLoginPageEnabled) { await RespondWith404(context); return; } context.Response.StatusCode = 200; context.Response.ContentType = " text/html; charset=utf-8"; var html = InspectorHtmlProvider.GetHtml(_options.BaseEndPoint + "/version", _options.AuthenticationHeader); await context.Response.WriteAsync(html, Encoding.UTF8); } //private async Task HandleJitUiRequest(HttpContext context) //{ // context.Response.StatusCode = 200; // context.Response.ContentType = "text/html"; // var html = HtmlGenerator.GetIndex(css, js); // await context.Response.WriteAsync(html, Encoding.UTF8); //} //private async Task HandleJsRequest(HttpContext context) //{ // context.Response.ContentType = "application/javascript"; // context.Response.StatusCode = 200; // var data = ReadEmbeddedResource("WonderTools.JitLogger.Resource." + js); // await context.Response.Body.WriteAsync(data, 0, data.Length); //} //private async Task HandleCssRequest(HttpContext context) //{ // context.Response.ContentType = "text/css"; // context.Response.StatusCode = 200; // var data = ReadEmbeddedResource("WonderTools.JitLogger.Resource." + css); // await context.Response.Body.WriteAsync(data, 0, data.Length); //} //private static List<Log> FilterLogsBasedOnQueryString(HttpContext context, List<Log> logs) //{ // var QueryParameter = "exclusion-log-id-limit"; // if (!context.Request.Query.ContainsKey(QueryParameter)) return logs; // var idAsString = context.Request.Query[QueryParameter].ToString(); // if (!Int32.TryParse(idAsString, out var id)) return logs; // if (!logs.Any(x => x.LogId == id)) return logs; // return logs.Where(x => x.LogId > id).ToList(); //} //private bool IsRequestForJitUi(string path, string method) //{ // return IsRequestValid(path, method, "/ui", "get"); //} //private bool IsRequestForPreflightJitUi(string path, string method) //{ // return IsRequestValid(path, method, "/ui", "options"); //} //private byte[] ReadEmbeddedResource(String filename) //{ // Assembly assembly = Assembly.GetExecutingAssembly(); // using (Stream filestream = assembly.GetManifestResourceStream(filename)) // { // if (filestream == null) return null; // byte[] bytes = new byte[filestream.Length]; // filestream.Read(bytes, 0, bytes.Length); // return bytes; // } //} } }
38.108911
121
0.614705
[ "MIT" ]
WonderTools/Inspector
Inspector/Inspector/InspectorMiddleWare.cs
7,700
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.IO; using System.Collections.Generic; using Microsoft.JSInterop; using Bicep.Core.Diagnostics; using Bicep.Core.Text; using Bicep.Core.Emit; using Bicep.Core.SemanticModel; using Bicep.Core.Syntax; using Bicep.Wasm.LanguageHelpers; using System.Linq; namespace Bicep.Wasm { public class Interop { private readonly IJSRuntime jsRuntime; public Interop(IJSRuntime jsRuntime) { this.jsRuntime = jsRuntime; } [JSInvokable] public object CompileAndEmitDiagnostics(string content) { var (output, diagnostics) = CompileInternal(content); return new { template = output, diagnostics = diagnostics, }; } [JSInvokable] public object GetSemanticTokensLegend() { var tokenTypes = Enum.GetValues(typeof(SemanticTokenType)).Cast<SemanticTokenType>(); var tokenStrings = tokenTypes.OrderBy(t => (int)t).Select(t => t.ToString().ToLowerInvariant()); return new { tokenModifiers = new string[] { }, tokenTypes = tokenStrings.ToArray(), }; } [JSInvokable] public object GetSemanticTokens(string content) { var lineStarts = TextCoordinateConverter.GetLineStarts(content); var compilation = new Compilation(SyntaxFactory.CreateFromText(content)); var tokens = SemanticTokenVisitor.BuildSemanticTokens(compilation.ProgramSyntax, lineStarts); var data = new List<int>(); SemanticToken? prevToken = null; foreach (var token in tokens) { if (prevToken == null) { data.Add(token.Line); data.Add(token.Character); data.Add(token.Length); } else if (prevToken.Line != token.Line) { data.Add(token.Line - prevToken.Line); data.Add(token.Character); data.Add(token.Length); } else { data.Add(0); data.Add(token.Character - prevToken.Character); data.Add(token.Length); } data.Add((int)token.TokenType); data.Add(0); prevToken = token; } return new { data = data.ToArray(), }; } private static (string, IEnumerable<dynamic>) CompileInternal(string content) { try { var lineStarts = TextCoordinateConverter.GetLineStarts(content); var compilation = new Compilation(SyntaxFactory.CreateFromText(content)); var emitter = new TemplateEmitter(compilation.GetSemanticModel()); // memory stream is not ideal for frequent large allocations using var stream = new MemoryStream(); var emitResult = emitter.Emit(stream); if (emitResult.Status != EmitStatus.Failed) { // compilation was successful or had warnings - return the compiled template stream.Position = 0; return (ReadStreamToEnd(stream), emitResult.Diagnostics.Select(d => ToMonacoDiagnostic(d, lineStarts))); } // compilation failed return ("Compilation failed!", emitResult.Diagnostics.Select(d => ToMonacoDiagnostic(d, lineStarts))); } catch (Exception exception) { return (exception.ToString(), Enumerable.Empty<dynamic>()); } } private static string ReadStreamToEnd(Stream stream) { using var reader = new StreamReader(stream); return reader.ReadToEnd(); } private static object ToMonacoDiagnostic(Diagnostic diagnostic, IReadOnlyList<int> lineStarts) { var (startLine, startChar) = TextCoordinateConverter.GetPosition(lineStarts, diagnostic.Span.Position); var (endLine, endChar) = TextCoordinateConverter.GetPosition(lineStarts, diagnostic.Span.Position + diagnostic.Span.Length); return new { code = diagnostic.Code, message = diagnostic.Message, severity = ToMonacoSeverity(diagnostic.Level), startLineNumber = startLine + 1, startColumn = startChar + 1, endLineNumber = endLine + 1, endColumn = endChar + 1, }; } private static int ToMonacoSeverity(DiagnosticLevel level) => level switch { DiagnosticLevel.Info => 2, DiagnosticLevel.Warning => 4, DiagnosticLevel.Error => 8, _ => throw new ArgumentException($"Unrecognized level {level}"), }; } }
35.268966
136
0.559054
[ "MIT" ]
anwather/bicep
src/Bicep.Wasm/Interop.cs
5,114
C#
using System; using System.Collections.Generic; using System.Data; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; namespace LinqToDB.DataProvider.Firebird { using Common; using Data; using Mapping; using SqlProvider; public class FirebirdDataProvider : DynamicDataProviderBase { public FirebirdDataProvider() : this(ProviderName.Firebird, new FirebirdMappingSchema(), null) { } public FirebirdDataProvider(ISqlOptimizer sqlOptimizer) : this(ProviderName.Firebird, new FirebirdMappingSchema(), sqlOptimizer) { } protected FirebirdDataProvider(string name, MappingSchema mappingSchema, ISqlOptimizer sqlOptimizer) : base(name, mappingSchema) { SqlProviderFlags.IsIdentityParameterRequired = true; SqlProviderFlags.IsCommonTableExpressionsSupported = true; SqlProviderFlags.IsSubQueryOrderBySupported = true; SqlProviderFlags.IsDistinctSetOperationsSupported = false; SetCharField("CHAR", (r,i) => r.GetString(i).TrimEnd(' ')); SetCharFieldToType<char>("CHAR", (r, i) => DataTools.GetChar(r, i)); SetProviderField<IDataReader,TimeSpan,DateTime>((r,i) => r.GetDateTime(i) - new DateTime(1970, 1, 1)); SetProviderField<IDataReader,DateTime,DateTime>((r,i) => GetDateTime(r, i)); _sqlOptimizer = sqlOptimizer ?? new FirebirdSqlOptimizer(SqlProviderFlags); } static DateTime GetDateTime(IDataReader dr, int idx) { var value = dr.GetDateTime(idx); if (value.Year == 1970 && value.Month == 1 && value.Day == 1) return new DateTime(1, 1, 1, value.Hour, value.Minute, value.Second, value.Millisecond); return value; } Action<IDbDataParameter> _setTimeStamp; public override string ConnectionNamespace => "FirebirdSql.Data.FirebirdClient"; protected override string ConnectionTypeName => $"{ConnectionNamespace}.FbConnection, {ConnectionNamespace}"; protected override string DataReaderTypeName => $"{ConnectionNamespace}.FbDataReader, {ConnectionNamespace}"; protected override void OnConnectionTypeCreated(Type connectionType) { // ((FbParameter)parameter).FbDbType = FbDbType. TimeStamp; _setTimeStamp = GetSetParameter(connectionType, "FbParameter", "FbDbType", "FbDbType", "TimeStamp"); } public override ISqlBuilder CreateSqlBuilder(MappingSchema mappingSchema) { return new FirebirdSqlBuilder(GetSqlOptimizer(), SqlProviderFlags, mappingSchema.ValueToSqlConverter); } readonly ISqlOptimizer _sqlOptimizer; public override ISqlOptimizer GetSqlOptimizer() { return _sqlOptimizer; } #if !NETSTANDARD1_6 public override SchemaProvider.ISchemaProvider GetSchemaProvider() { return new FirebirdSchemaProvider(); } #endif public override bool? IsDBNullAllowed(IDataReader reader, int idx) { return true; } public override void SetParameter(IDbDataParameter parameter, string name, DbDataType dataType, object value) { if (value is bool) { value = (bool)value ? "1" : "0"; dataType = dataType.WithDataType(DataType.Char); } base.SetParameter(parameter, name, dataType, value); } protected override void SetParameterType(IDbDataParameter parameter, DbDataType dataType) { switch (dataType.DataType) { case DataType.SByte : dataType = dataType.WithDataType(DataType.Int16); break; case DataType.UInt16 : dataType = dataType.WithDataType(DataType.Int32); break; case DataType.UInt32 : dataType = dataType.WithDataType(DataType.Int64); break; case DataType.UInt64 : dataType = dataType.WithDataType(DataType.Decimal); break; case DataType.VarNumeric : dataType = dataType.WithDataType(DataType.Decimal); break; case DataType.DateTime : case DataType.DateTime2 : _setTimeStamp(parameter); return; } base.SetParameterType(parameter, dataType); } #region BulkCopy public override BulkCopyRowsCopied BulkCopy<T>( [JetBrains.Annotations.NotNull] ITable<T> table, BulkCopyOptions options, IEnumerable<T> source) { return new FirebirdBulkCopy().BulkCopy( options.BulkCopyType == BulkCopyType.Default ? FirebirdTools.DefaultBulkCopyType : options.BulkCopyType, table, options, source); } #endregion #region Merge public override int Merge<T>(DataConnection dataConnection, Expression<Func<T,bool>> deletePredicate, bool delete, IEnumerable<T> source, string tableName, string databaseName, string schemaName) { if (delete) throw new LinqToDBException("Firebird MERGE statement does not support DELETE by source."); return new FirebirdMerge().Merge(dataConnection, deletePredicate, delete, source, tableName, databaseName, schemaName); } public override Task<int> MergeAsync<T>(DataConnection dataConnection, Expression<Func<T,bool>> deletePredicate, bool delete, IEnumerable<T> source, string tableName, string databaseName, string schemaName, CancellationToken token) { if (delete) throw new LinqToDBException("Firebird MERGE statement does not support DELETE by source."); return new FirebirdMerge().MergeAsync(dataConnection, deletePredicate, delete, source, tableName, databaseName, schemaName, token); } protected override BasicMergeBuilder<TTarget, TSource> GetMergeBuilder<TTarget, TSource>( DataConnection connection, IMergeable<TTarget, TSource> merge) { return new FirebirdMergeBuilder<TTarget, TSource>(connection, merge); } #endregion } }
35.149068
151
0.721682
[ "MIT" ]
FrancisChung/linq2db
Source/LinqToDB/DataProvider/Firebird/FirebirdDataProvider.cs
5,501
C#
namespace HSL { using System.Collections.Generic; public partial class Pattern : Node { public string id { get; set; } public Route route { get; set; } public int directionId { get; set; } public string name { get; set; } public string code { get; set; } public string headsign { get; set; } public List<Trip> trips { get; set; } public List<Trip> tripsForDate { get; set; } public List<Stop> stops { get; set; } public List<Coordinates> geometry { get; set; } public string semanticHash { get; set; } public List<Alert> alerts { get; set; } } }
32.9
55
0.580547
[ "Apache-2.0" ]
Giorgi/GraphQLinq
src/GraphQLinq.Generated/HSL/Pattern.cs
658
C#
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.Storage; using Microsoft.Azure.Management.Storage.Models; namespace Microsoft.Azure.Management.Storage { /// <summary> /// The Storage Management Client. /// </summary> public static partial class StorageAccountOperationsExtensions { /// <summary> /// Asynchronously creates a new storage account with the specified /// parameters. Existing accounts cannot be updated with this API and /// should instead use the Update Storage Account API. If an account /// is already created and subsequent PUT request is issued with exact /// same set of properties, then HTTP 200 would be returned. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Storage.IStorageAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group within the user’s /// subscription. /// </param> /// <param name='accountName'> /// Required. The name of the storage account within the specified /// resource group. Storage account names must be between 3 and 24 /// characters in length and use numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// Required. The parameters to provide for the created account. /// </param> /// <returns> /// The Create storage account operation response. /// </returns> public static StorageAccountCreateResponse BeginCreate(this IStorageAccountOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IStorageAccountOperations)s).BeginCreateAsync(resourceGroupName, accountName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Asynchronously creates a new storage account with the specified /// parameters. Existing accounts cannot be updated with this API and /// should instead use the Update Storage Account API. If an account /// is already created and subsequent PUT request is issued with exact /// same set of properties, then HTTP 200 would be returned. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Storage.IStorageAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group within the user’s /// subscription. /// </param> /// <param name='accountName'> /// Required. The name of the storage account within the specified /// resource group. Storage account names must be between 3 and 24 /// characters in length and use numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// Required. The parameters to provide for the created account. /// </param> /// <returns> /// The Create storage account operation response. /// </returns> public static Task<StorageAccountCreateResponse> BeginCreateAsync(this IStorageAccountOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters) { return operations.BeginCreateAsync(resourceGroupName, accountName, parameters, CancellationToken.None); } /// <summary> /// Checks that account name is valid and is not in use. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Storage.IStorageAccountOperations. /// </param> /// <param name='accountName'> /// Required. The name of the storage account within the specified /// resource group. Storage account names must be between 3 and 24 /// characters in length and use numbers and lower-case letters only. /// </param> /// <returns> /// The CheckNameAvailability operation response. /// </returns> public static CheckNameAvailabilityResponse CheckNameAvailability(this IStorageAccountOperations operations, string accountName) { return Task.Factory.StartNew((object s) => { return ((IStorageAccountOperations)s).CheckNameAvailabilityAsync(accountName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Checks that account name is valid and is not in use. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Storage.IStorageAccountOperations. /// </param> /// <param name='accountName'> /// Required. The name of the storage account within the specified /// resource group. Storage account names must be between 3 and 24 /// characters in length and use numbers and lower-case letters only. /// </param> /// <returns> /// The CheckNameAvailability operation response. /// </returns> public static Task<CheckNameAvailabilityResponse> CheckNameAvailabilityAsync(this IStorageAccountOperations operations, string accountName) { return operations.CheckNameAvailabilityAsync(accountName, CancellationToken.None); } /// <summary> /// Asynchronously creates a new storage account with the specified /// parameters. Existing accounts cannot be updated with this API and /// should instead use the Update Storage Account API. If an account /// is already created and subsequent create request is issued with /// exact same set of properties, the request succeeds.The max number /// of storage accounts that can be created per subscription is /// limited to 20. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Storage.IStorageAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group within the user’s /// subscription. /// </param> /// <param name='accountName'> /// Required. The name of the storage account within the specified /// resource group. Storage account names must be between 3 and 24 /// characters in length and use numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// Required. The parameters to provide for the created account. /// </param> /// <returns> /// The Create storage account operation response. /// </returns> public static StorageAccountCreateResponse Create(this IStorageAccountOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IStorageAccountOperations)s).CreateAsync(resourceGroupName, accountName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Asynchronously creates a new storage account with the specified /// parameters. Existing accounts cannot be updated with this API and /// should instead use the Update Storage Account API. If an account /// is already created and subsequent create request is issued with /// exact same set of properties, the request succeeds.The max number /// of storage accounts that can be created per subscription is /// limited to 20. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Storage.IStorageAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group within the user’s /// subscription. /// </param> /// <param name='accountName'> /// Required. The name of the storage account within the specified /// resource group. Storage account names must be between 3 and 24 /// characters in length and use numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// Required. The parameters to provide for the created account. /// </param> /// <returns> /// The Create storage account operation response. /// </returns> public static Task<StorageAccountCreateResponse> CreateAsync(this IStorageAccountOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters) { return operations.CreateAsync(resourceGroupName, accountName, parameters, CancellationToken.None); } /// <summary> /// Deletes a storage account in Microsoft Azure. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Storage.IStorageAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group within the user’s /// subscription. /// </param> /// <param name='accountName'> /// Required. The name of the storage account within the specified /// resource group. Storage account names must be between 3 and 24 /// characters in length and use numbers and lower-case letters only. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IStorageAccountOperations operations, string resourceGroupName, string accountName) { return Task.Factory.StartNew((object s) => { return ((IStorageAccountOperations)s).DeleteAsync(resourceGroupName, accountName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a storage account in Microsoft Azure. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Storage.IStorageAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group within the user’s /// subscription. /// </param> /// <param name='accountName'> /// Required. The name of the storage account within the specified /// resource group. Storage account names must be between 3 and 24 /// characters in length and use numbers and lower-case letters only. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IStorageAccountOperations operations, string resourceGroupName, string accountName) { return operations.DeleteAsync(resourceGroupName, accountName, CancellationToken.None); } /// <summary> /// Returns the properties for the specified storage account including /// but not limited to name, account type, location, and account /// status. The ListKeys operation should be used to retrieve storage /// keys. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Storage.IStorageAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group within the user’s /// subscription. /// </param> /// <param name='accountName'> /// Required. The name of the storage account within the specified /// resource group. Storage account names must be between 3 and 24 /// characters in length and use numbers and lower-case letters only. /// </param> /// <returns> /// The Get storage account operation response. /// </returns> public static StorageAccountGetPropertiesResponse GetProperties(this IStorageAccountOperations operations, string resourceGroupName, string accountName) { return Task.Factory.StartNew((object s) => { return ((IStorageAccountOperations)s).GetPropertiesAsync(resourceGroupName, accountName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns the properties for the specified storage account including /// but not limited to name, account type, location, and account /// status. The ListKeys operation should be used to retrieve storage /// keys. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Storage.IStorageAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group within the user’s /// subscription. /// </param> /// <param name='accountName'> /// Required. The name of the storage account within the specified /// resource group. Storage account names must be between 3 and 24 /// characters in length and use numbers and lower-case letters only. /// </param> /// <returns> /// The Get storage account operation response. /// </returns> public static Task<StorageAccountGetPropertiesResponse> GetPropertiesAsync(this IStorageAccountOperations operations, string resourceGroupName, string accountName) { return operations.GetPropertiesAsync(resourceGroupName, accountName, CancellationToken.None); } /// <summary> /// Lists all the storage accounts available under the subscription. /// Note that storage keys are not returned; use the ListKeys /// operation for this. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Storage.IStorageAccountOperations. /// </param> /// <returns> /// The list storage accounts operation response. /// </returns> public static StorageAccountListResponse List(this IStorageAccountOperations operations) { return Task.Factory.StartNew((object s) => { return ((IStorageAccountOperations)s).ListAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all the storage accounts available under the subscription. /// Note that storage keys are not returned; use the ListKeys /// operation for this. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Storage.IStorageAccountOperations. /// </param> /// <returns> /// The list storage accounts operation response. /// </returns> public static Task<StorageAccountListResponse> ListAsync(this IStorageAccountOperations operations) { return operations.ListAsync(CancellationToken.None); } /// <summary> /// Lists all the storage accounts available under the given resource /// group. Note that storage keys are not returned; use the ListKeys /// operation for this. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Storage.IStorageAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group within the user’s /// subscription. /// </param> /// <returns> /// The list storage accounts operation response. /// </returns> public static StorageAccountListResponse ListByResourceGroup(this IStorageAccountOperations operations, string resourceGroupName) { return Task.Factory.StartNew((object s) => { return ((IStorageAccountOperations)s).ListByResourceGroupAsync(resourceGroupName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all the storage accounts available under the given resource /// group. Note that storage keys are not returned; use the ListKeys /// operation for this. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Storage.IStorageAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group within the user’s /// subscription. /// </param> /// <returns> /// The list storage accounts operation response. /// </returns> public static Task<StorageAccountListResponse> ListByResourceGroupAsync(this IStorageAccountOperations operations, string resourceGroupName) { return operations.ListByResourceGroupAsync(resourceGroupName, CancellationToken.None); } /// <summary> /// Lists the access keys for the specified storage account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Storage.IStorageAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='accountName'> /// Required. The name of the storage account. /// </param> /// <returns> /// The ListKeys operation response. /// </returns> public static StorageAccountListKeysResponse ListKeys(this IStorageAccountOperations operations, string resourceGroupName, string accountName) { return Task.Factory.StartNew((object s) => { return ((IStorageAccountOperations)s).ListKeysAsync(resourceGroupName, accountName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the access keys for the specified storage account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Storage.IStorageAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='accountName'> /// Required. The name of the storage account. /// </param> /// <returns> /// The ListKeys operation response. /// </returns> public static Task<StorageAccountListKeysResponse> ListKeysAsync(this IStorageAccountOperations operations, string resourceGroupName, string accountName) { return operations.ListKeysAsync(resourceGroupName, accountName, CancellationToken.None); } /// <summary> /// Regenerates the access keys for the specified storage account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Storage.IStorageAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group within the user’s /// subscription. /// </param> /// <param name='accountName'> /// Required. The name of the storage account within the specified /// resource group. Storage account names must be between 3 and 24 /// characters in length and use numbers and lower-case letters only. /// </param> /// <param name='regenerateKey'> /// Required. Specifies name of the key which should be regenerated. /// </param> /// <returns> /// The RegenerateKey operation response. /// </returns> public static StorageAccountRegenerateKeyResponse RegenerateKey(this IStorageAccountOperations operations, string resourceGroupName, string accountName, KeyName regenerateKey) { return Task.Factory.StartNew((object s) => { return ((IStorageAccountOperations)s).RegenerateKeyAsync(resourceGroupName, accountName, regenerateKey); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Regenerates the access keys for the specified storage account. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Storage.IStorageAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group within the user’s /// subscription. /// </param> /// <param name='accountName'> /// Required. The name of the storage account within the specified /// resource group. Storage account names must be between 3 and 24 /// characters in length and use numbers and lower-case letters only. /// </param> /// <param name='regenerateKey'> /// Required. Specifies name of the key which should be regenerated. /// </param> /// <returns> /// The RegenerateKey operation response. /// </returns> public static Task<StorageAccountRegenerateKeyResponse> RegenerateKeyAsync(this IStorageAccountOperations operations, string resourceGroupName, string accountName, KeyName regenerateKey) { return operations.RegenerateKeyAsync(resourceGroupName, accountName, regenerateKey, CancellationToken.None); } /// <summary> /// Updates the account type or tags for a storage account. It can also /// be used to add a custom domain (note that custom domains cannot be /// added via the Create operation). Only one custom domain is /// supported per storage account. This API can only be used to update /// one of tags, accountType, or customDomain per call. To update /// multiple of these properties, call the API multiple times with one /// change per call. This call does not change the storage keys for /// the account. If you want to change storage account keys, use the /// RegenerateKey operation. The location and name of the storage /// account cannot be changed after creation. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Storage.IStorageAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group within the user’s /// subscription. /// </param> /// <param name='accountName'> /// Required. The name of the storage account within the specified /// resource group. Storage account names must be between 3 and 24 /// characters in length and use numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// Required. The parameters to update on the account. Note that only /// one property can be changed at a time using this API. /// </param> /// <returns> /// The Update storage account operation response. /// </returns> public static StorageAccountUpdateResponse Update(this IStorageAccountOperations operations, string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IStorageAccountOperations)s).UpdateAsync(resourceGroupName, accountName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates the account type or tags for a storage account. It can also /// be used to add a custom domain (note that custom domains cannot be /// added via the Create operation). Only one custom domain is /// supported per storage account. This API can only be used to update /// one of tags, accountType, or customDomain per call. To update /// multiple of these properties, call the API multiple times with one /// change per call. This call does not change the storage keys for /// the account. If you want to change storage account keys, use the /// RegenerateKey operation. The location and name of the storage /// account cannot be changed after creation. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Storage.IStorageAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group within the user’s /// subscription. /// </param> /// <param name='accountName'> /// Required. The name of the storage account within the specified /// resource group. Storage account names must be between 3 and 24 /// characters in length and use numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// Required. The parameters to update on the account. Note that only /// one property can be changed at a time using this API. /// </param> /// <returns> /// The Update storage account operation response. /// </returns> public static Task<StorageAccountUpdateResponse> UpdateAsync(this IStorageAccountOperations operations, string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters) { return operations.UpdateAsync(resourceGroupName, accountName, parameters, CancellationToken.None); } } }
47.790268
205
0.628445
[ "Apache-2.0" ]
j82w/azure-sdk-for-net
src/ResourceManagement/Storage/StorageManagement/Generated/StorageAccountOperationsExtensions.cs
28,511
C#
using EmptyUmbracoWebApp.Repositories; using Umbraco.Pylon.Controllers; namespace EmptyUmbracoWebApp.Controllers { /// <summary> /// Base class for a surface controller, to use for key CMS action bindings. /// </summary> /// <seealso cref="Umbraco.Pylon.Controllers.PylonSurfaceController{ISampleSite, ISamplePublishedContentRepository}" /> public abstract class SampleSurfaceController : PylonSurfaceController<ISampleSite, ISamplePublishedContentRepository> { #region | Construction | /// <summary> /// Initializes a new instance of the <see cref="SampleSurfaceController" /> class. /// </summary> /// <param name="site">The site.</param> protected SampleSurfaceController(ISampleSite site) : base(site) { } #endregion } }
33.32
123
0.678271
[ "MIT" ]
ministryotech/Umbraco.Pylon
EmptyUmbracoWebApp/Controllers/SampleSurfaceController.cs
835
C#
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; public class SwordController : MonoBehaviour { //References private SkinnedMeshRenderer swordMeshRenderer; private MeshCollider swordMeshCollider; private Mesh currSwordMesh; //External private PlayerController player; private SwordTrail swordTrail; //Tweakables public int meleeSlash1Damage = 1; public float meleeSlash1PushBack = 200.0f; public int meleeSlash2Damage = 1; public float meleeSlash2PushBack = 200.0f; public int meleeSlash3Damage = 2; public float meleeSlash3PushBack = 200.0f; public bool dynamicCollider; //Internal private bool firstStrike = true; private bool secondStrike = true; private bool thirdStrike = true; private float meleeEndComboTimer = 0.15f; private float meleeEndComboTimerDuration = 0.15f; private void Start() { player = GetComponentInParent<PlayerController>(); swordMeshRenderer = GetComponent<SkinnedMeshRenderer>(); swordMeshCollider = GetComponent<MeshCollider>(); swordTrail = GetComponent<SwordTrail>(); swordTrail.Init(); currSwordMesh = new Mesh(); dynamicCollider = false; } private void Update() { if (dynamicCollider) { RenderMeshToCollisionMesh(); } else { DisableCollider(); } //Melee End Combo SFX Buffer if (meleeEndComboTimer > 0.0f) { meleeEndComboTimer -= Time.deltaTime; } } private void RenderMeshToCollisionMesh() { swordMeshRenderer.BakeMesh(currSwordMesh); swordMeshCollider.sharedMesh = currSwordMesh; } private void SwordSlashEnemy(Collider anObject, int currentAttack) { switch (currentAttack) { case 1: { switch (anObject.name) { case "Enemy": case "Enemy(Clone)": { SFXManager.Instance.PlaySFX("swordHitZombie1SFX"); firstStrike = false; break; } } break; } case 2: { switch (anObject.name) { case "Enemy": case "Enemy(Clone)": { SFXManager.Instance.PlaySFX("swordHitZombie2SFX"); secondStrike = false; break; } } break; } case 3: { switch (anObject.name) { case "Enemy": case "Enemy(Clone)": { SFXManager.Instance.PlaySFX("swordHitZombie3SFX"); thirdStrike = false; break; } } break; } } } private void SwordSlashMiss(Collider anObject, int currentAttack) { switch (currentAttack) { case 1: { SFXManager.Instance.PlaySFX("swordMiss1SFX"); firstStrike = false; break; } case 2: { SFXManager.Instance.PlaySFX("swordMiss2SFX"); secondStrike = false; break; } case 3: { SFXManager.Instance.PlaySFX("swordMiss3SFX"); thirdStrike = false; break; } } } private void SwordSlashWall(Collider anObject, int currentAttack) { switch (currentAttack) { case 1: { SFXManager.Instance.PlaySFX("swordHitWall1SFX"); firstStrike = false; break; } case 2: { SFXManager.Instance.PlaySFX("swordHitWall1SFX"); secondStrike = false; break; } case 3: { SFXManager.Instance.PlaySFX("swordHitWall3SFX"); thirdStrike = false; break; } } } private void SwordSlashSpawner(Collider anObject, int currentAttack) { switch (currentAttack) { case 1: { SFXManager.Instance.PlaySFX("swordHitSpawnerSFX1"); firstStrike = false; break; } case 2: { SFXManager.Instance.PlaySFX("swordHitSpawnerSFX2"); secondStrike = false; break; } case 3: { SFXManager.Instance.PlaySFX("swordHitSpawnerSFX1"); thirdStrike = false; break; } } } public void ResetSlashes() { DisableCollider(); firstStrike = true; secondStrike = true; thirdStrike = true; meleeEndComboTimer = meleeEndComboTimerDuration; } public void DisableCollider() { swordTrail.TrailColor.a = 0.0f; swordMeshCollider.sharedMesh = null; } private void OnTriggerEnter(Collider other) { //Debug.Log(other.gameObject.name); switch (other.tag) { case "Enemy": { StopOrDeleteMissSFX(); if (player.AnimatorIsPlaying("MeleeSlash1") && firstStrike) { swordTrail.TrailColor = Color.red; SwordSlashEnemy(other, 1); firstStrike = false; } else if (player.AnimatorIsPlaying("MeleeSlash2") && secondStrike) { swordTrail.TrailColor = Color.red; SwordSlashEnemy(other, 2); secondStrike = false; } else if (player.AnimatorIsPlaying("MeleeSlash3") && thirdStrike && meleeEndComboTimer < 0.0f) { swordTrail.TrailColor = Color.red; SwordSlashEnemy(other, 3); thirdStrike = false; } break; } case "Spawner": { StopOrDeleteMissSFX(); if (player.AnimatorIsPlaying("MeleeSlash1") && firstStrike) { swordTrail.TrailColor = Color.magenta; SwordSlashSpawner(other, 1); firstStrike = false; } else if (player.AnimatorIsPlaying("MeleeSlash2") && secondStrike) { swordTrail.TrailColor = Color.magenta; SwordSlashSpawner(other, 2); secondStrike = false; } else if (player.AnimatorIsPlaying("MeleeSlash3") && thirdStrike && meleeEndComboTimer < 0.0f) { swordTrail.TrailColor = Color.magenta; SwordSlashSpawner(other, 3); thirdStrike = false; } break; } case "Wall": { StopOrDeleteMissSFX(); if (player.AnimatorIsPlaying("MeleeSlash1") && firstStrike) { swordTrail.TrailColor = Color.gray; SwordSlashWall(other, 1); firstStrike = false; } else if (player.AnimatorIsPlaying("MeleeSlash2") && secondStrike) { swordTrail.TrailColor = Color.gray; SwordSlashWall(other, 2); secondStrike = false; } else if (player.AnimatorIsPlaying("MeleeSlash3") && thirdStrike && meleeEndComboTimer < 0.0f) { swordTrail.TrailColor = Color.gray; SwordSlashWall(other, 3); thirdStrike = false; } break; } } } void StopOrDeleteMissSFX() { GameObject[] missSFXGameObjects = new GameObject[3]; missSFXGameObjects[0] = GameObject.Find("SFX Object: swordMiss1SFX"); missSFXGameObjects[1] = GameObject.Find("SFX Object: swordMiss2SFX"); missSFXGameObjects[2] = GameObject.Find("SFX Object: swordMiss3SFX"); if (missSFXGameObjects[0]) { if (missSFXGameObjects[0].name != "Null") { Destroy(missSFXGameObjects[0]); } } if (missSFXGameObjects[1]) { if (missSFXGameObjects[1].name != "Null") { Destroy(missSFXGameObjects[1]); } } if (missSFXGameObjects[2]) { if (missSFXGameObjects[2].name != "Null") { Destroy(missSFXGameObjects[2]); } } } }
29.936747
113
0.443304
[ "MIT" ]
d4rkz3r0/GPGamesPrototype
Assets/Scripts/Player/Weapons/SwordController.cs
9,941
C#
// Generated on 03/23/2022 09:50:22 using System; using System.Collections.Generic; using System.Linq; using AmaknaProxy.API.Protocol.Types; using AmaknaProxy.API.IO; using AmaknaProxy.API.Network; namespace AmaknaProxy.API.Protocol.Messages { public class BreachRewardBoughtMessage : NetworkMessage { public const uint Id = 8594; public override uint MessageId { get { return Id; } } public uint id; public bool bought; public BreachRewardBoughtMessage() { } public BreachRewardBoughtMessage(uint id, bool bought) { this.id = id; this.bought = bought; } public override void Serialize(IDataWriter writer) { writer.WriteVarInt((int)id); writer.WriteBoolean(bought); } public override void Deserialize(IDataReader reader) { id = reader.ReadVarUInt(); bought = reader.ReadBoolean(); } } }
22.666667
62
0.565257
[ "MIT" ]
ImNotARobot742/DofusProtocol
DofusProtocol/D2Parser/Protocol/Messages/game/context/roleplay/breach/reward/BreachRewardBoughtMessage.cs
1,088
C#
using System; using Prism.Windows.Mvvm; namespace wts.ItemName.ViewModels { public class PivotViewModel : ViewModelBase { public PivotViewModel() { } } }
14.769231
47
0.625
[ "MIT" ]
DalavanCloud/WindowsTemplateStudio
templates/Uwp/_composition/Prism/Project.TabbedPivot/ViewModels/PivotViewModel.cs
194
C#
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using NewLife.Data; using NewLife.Model; using NewLife.Reflection; namespace NewLife.Serialization { /// <summary>Json读取器</summary> public class JsonReader { #region 属性 /// <summary>是否使用UTC时间</summary> public Boolean UseUTCDateTime { get; set; } ///// <summary>对象工厂集合。用于为指定类创建实例</summary> //public IDictionary<Type, Func<Type, Object>> ObjectFactories { get; } = new Dictionary<Type, Func<Type, Object>>(); #endregion #region 方法 ///// <summary>注册对象工厂,创建指定类实例时调用</summary> ///// <param name="type"></param> ///// <param name="func"></param> //public void AddObjectFactory(Type type, Func<Type, Object> func) //{ // ObjectFactories[type] = func; //} ///// <summary>注册对象工厂,创建指定类实例时调用</summary> ///// <typeparam name="T"></typeparam> ///// <param name="func"></param> //public void AddObjectFactory<T>(Func<Type, Object> func) => AddObjectFactory(typeof(T), func); private Object CreateObject(Type type) { //if (ObjectFactories.TryGetValue(type, out var func)) return func(type); var obj = ObjectContainer.Provider.GetService(type); if (obj != null) return obj; return type.CreateInstance(); } #endregion #region 转换方法 /// <summary>读取Json到指定类型</summary> /// <typeparam name="T"></typeparam> /// <param name="json"></param> /// <returns></returns> public T Read<T>(String json) { return (T)Read(json, typeof(T)); } /// <summary>读取Json到指定类型</summary> /// <param name="json"></param> /// <param name="type"></param> /// <returns></returns> public Object Read(String json, Type type) { // 解码得到字典或列表 var obj = new JsonParser(json).Decode(); if (obj == null) return null; return ToObject(obj, type, null); } /// <summary>Json字典或列表转为具体类型对象</summary> /// <param name="jobj">Json对象</param> /// <param name="type">模板类型</param> /// <param name="target">目标对象</param> /// <returns></returns> public Object ToObject(Object jobj, Type type, Object target) { if (type == null && target != null) type = target.GetType(); if (type.IsAssignableFrom(jobj.GetType())) return jobj; // Json对象是字典,目标类型可以是字典或复杂对象 if (jobj is IDictionary<String, Object> vdic) { if (type.IsDictionary()) return ParseDictionary(vdic, type, target as IDictionary); else return ParseObject(vdic, type, target); } // Json对象是列表,目标类型只能是列表或数组 if (jobj is IList<Object> vlist) { if (type.IsList()) return ParseList(vlist, type, target); if (type.IsArray) return ParseArray(vlist, type, target); // 复杂键值的字典,也可能保存为Json数组 if (type.IsDictionary()) return CreateDictionary(vlist, type, target); if (vlist.Count == 0) return target; throw new InvalidCastException($"Json数组无法转为目标类型[{type.FullName}],仅支持数组和List<T>/IList<T>"); } if (type != null && jobj.GetType() != type) return ChangeType(jobj, type); return jobj; } #endregion #region 复杂类型 /// <summary>转为泛型列表</summary> /// <param name="vlist"></param> /// <param name="type"></param> /// <param name="target">目标对象</param> /// <returns></returns> private IList ParseList(IList<Object> vlist, Type type, Object target) { var elmType = type.GetGenericArguments().FirstOrDefault(); // 处理一下type是IList<>的情况 if (type.IsInterface) type = typeof(List<>).MakeGenericType(elmType); // 创建列表 var list = (target ?? type.CreateInstance()) as IList; foreach (var item in vlist) { if (item == null) continue; var val = ToObject(item, elmType, null); list.Add(val); } return list; } /// <summary>转为数组</summary> /// <param name="list"></param> /// <param name="type"></param> /// <param name="target">目标对象</param> /// <returns></returns> private Array ParseArray(IList<Object> list, Type type, Object target) { var elmType = type?.GetElementTypeEx(); if (elmType == null) elmType = typeof(Object); var arr = target as Array; if (arr == null) arr = Array.CreateInstance(elmType, list.Count); // 如果源数组有值,则最大只能创建源数组那么多项,抛弃多余项 for (var i = 0; i < list.Count && i < arr.Length; i++) { var item = list[i]; if (item == null) continue; var val = ToObject(item, elmType, arr.GetValue(i)); arr.SetValue(val, i); } return arr; } /// <summary>转为泛型字典</summary> /// <param name="dic"></param> /// <param name="type"></param> /// <param name="target">目标对象</param> /// <returns></returns> private IDictionary ParseDictionary(IDictionary<String, Object> dic, Type type, IDictionary target) { var types = type.GetGenericArguments(); if (target == null) { // 处理一下type是Dictionary<,>的情况 if (type.IsInterface) type = typeof(Dictionary<,>).MakeGenericType(types[0], types[1]); target = type.CreateInstance() as IDictionary; } foreach (var kv in dic) { var key = ToObject(kv.Key, types[0], null); var val = ToObject(kv.Value, types[1], null); target.Add(key, val); } return target; } private readonly Dictionary<Object, Int32> _circobj = new Dictionary<Object, Int32>(); private readonly Dictionary<Int32, Object> _cirrev = new Dictionary<Int32, Object>(); /// <summary>字典转复杂对象,反射属性赋值</summary> /// <param name="dic"></param> /// <param name="type"></param> /// <param name="target">目标对象</param> /// <returns></returns> internal Object ParseObject(IDictionary<String, Object> dic, Type type, Object target) { if (type == typeof(NameValueCollection)) return CreateNV(dic); if (type == typeof(StringDictionary)) return CreateSD(dic); if (type == typeof(Object)) return dic; if (target == null) target = CreateObject(type); if (type.IsDictionary()) return CreateDic(dic, type, target); if (!_circobj.TryGetValue(target, out var circount)) { circount = _circobj.Count + 1; _circobj.Add(target, circount); _cirrev.Add(circount, target); } // 扩展属性 var ext = target as IExtend; // 遍历所有可用于序列化的属性 var props = target.GetType().GetProperties(true).ToDictionary(e => SerialHelper.GetName(e), e => e); foreach (var item in dic) { var v = item.Value; if (v == null) continue; if (!props.TryGetValue(item.Key, out var pi)) { // 可能有小写 pi = props.Values.FirstOrDefault(e => e.Name.EqualIgnoreCase(item.Key)); if (pi == null) { // 可能有扩展属性 if (ext != null) ext[item.Key] = item.Value; continue; } } if (!pi.CanWrite) continue; var pt = pi.PropertyType; if (pt.GetTypeCode() != TypeCode.Object) target.SetValue(pi, ChangeType(v, pt)); else { var orig = target.GetValue(pi); var val = ToObject(v, pt, orig); if (val != orig) target.SetValue(pi, val); } } return target; } #endregion #region 辅助 private Object ChangeType(Object value, Type type) { // 支持可空类型 if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { if (value == null) return value; type = type.GetGenericArguments()[0]; } if (type == typeof(Int32)) return value.ToInt(); if (type == typeof(Int64)) return value.ToLong(); if (type == typeof(String)) return value + ""; if (type.IsEnum) return Enum.Parse(type, value + ""); if (type == typeof(DateTime)) return CreateDateTime(value); if (type == typeof(Guid)) return new Guid((String)value); if (type == typeof(Byte[])) { if (value is Byte[]) return (Byte[])value; return Convert.FromBase64String(value + ""); } if (type == typeof(TimeSpan)) return TimeSpan.Parse(value + ""); if (type.GetTypeCode() == TypeCode.Object) return null; return value.ChangeType(type); } private StringDictionary CreateSD(IDictionary<String, Object> dic) { var nv = new StringDictionary(); foreach (var item in dic) nv.Add(item.Key, (String)item.Value); return nv; } private NameValueCollection CreateNV(IDictionary<String, Object> dic) { var nv = new NameValueCollection(); foreach (var item in dic) nv.Add(item.Key, (String)item.Value); return nv; } private IDictionary CreateDic(IDictionary<String, Object> dic, Type type, Object obj) { var nv = obj as IDictionary; if (type.IsGenericType && type.GetGenericArguments().Length >= 2) { var tval = type.GetGenericArguments()[1]; foreach (var item in dic) nv.Add(item.Key, item.Value.ChangeType(tval)); } else { foreach (var item in dic) nv.Add(item.Key, item.Value); } return nv; } private Int32 CreateInteger(String str, Int32 index, Int32 count) { var num = 0; var neg = false; for (var x = 0; x < count; x++, index++) { var cc = str[index]; if (cc == '-') neg = true; else if (cc == '+') neg = false; else { num *= 10; num += cc - '0'; } } if (neg) num = -num; return num; } /// <summary>创建时间</summary> /// <param name="value"></param> /// <returns></returns> private DateTime CreateDateTime(Object value) { if (value is DateTime) return (DateTime)value; if (value is Int64 || value is Int32) { var dt = value.ToDateTime(); if (UseUTCDateTime) dt = dt.ToUniversalTime(); return dt; } //用于解决奇葩json中时间字段使用了utc时间戳,还是用双引号包裹起来的情况。 if (value is String str) { if (str.IsNullOrEmpty()) return DateTime.MinValue; if (Int64.TryParse(str, out var result) && result > 0) { var sdt = result.ToDateTime(); if (UseUTCDateTime) sdt = sdt.ToUniversalTime(); return sdt; } // 尝试直转时间 var dt = str.ToDateTime(); if (dt.Year > 1) return UseUTCDateTime ? dt.ToUniversalTime() : dt; var utc = false; var year = 0; var month = 0; var day = 0; var hour = 0; var min = 0; var sec = 0; var ms = 0; year = CreateInteger(str, 0, 4); month = CreateInteger(str, 5, 2); day = CreateInteger(str, 8, 2); if (str.Length >= 19) { hour = CreateInteger(str, 11, 2); min = CreateInteger(str, 14, 2); sec = CreateInteger(str, 17, 2); if (str.Length > 21 && str[19] == '.') ms = CreateInteger(str, 20, 3); if (str[str.Length - 1] == 'Z' || str.EndsWithIgnoreCase("UTC")) utc = true; } if (!UseUTCDateTime && !utc) return new DateTime(year, month, day, hour, min, sec, ms); else return new DateTime(year, month, day, hour, min, sec, ms, DateTimeKind.Utc).ToLocalTime(); } return DateTime.MinValue; } private Object CreateDictionary(IList<Object> list, Type type, Object target) { var types = type.GetGenericArguments(); var dic = (target ?? type.CreateInstance()) as IDictionary; foreach (IDictionary<String, Object> values in list) { var key = ToObject(values["k"], types[0], null); var val = ToObject(values["v"], types[1], null); dic.Add(key, val); } return dic; } #endregion } }
34.699284
126
0.474242
[ "MIT" ]
SpringLeee/X
NewLife.Core/Serialization/Json/JsonReader.cs
15,265
C#
namespace BikesBooking.Web.Controllers.ApiController { using BikesBooking.Services.Data.Motorcycle; using BikesBooking.Services.Data.User; using BikesBooking.Web.ViewModels.Api.Statistics; using Microsoft.AspNetCore.Mvc; [ApiController] [Route("api/statistics")] [ResponseCache(Duration = 40)] public class StatisticApiController : BaseController { private readonly IMotorcycleService motorcycleService; private readonly IUserService userService; public StatisticApiController( IMotorcycleService motorcycleService, IUserService userService) { this.motorcycleService = motorcycleService; this.userService = userService; } [HttpGet] public StatisticsResponseModel GetStatistics() { var totalMotorcycles = this.motorcycleService.GetMotorcycleCount(); var totalDealers = this.userService.GetTotalDeales(); var totalUsers = this.userService.GetTotalUsers(); var totalClients = this.userService.GetTotalClients(); var totalRent = this.motorcycleService.GetNotAvailableMotorcycleCount(); return new StatisticsResponseModel { TotalsMotorcycles = totalMotorcycles, TotalsUsers = totalUsers, TotalsRent = totalRent, TotalsDealers = totalDealers, TotalsClients = totalClients, }; } } }
35.255814
84
0.649077
[ "MIT" ]
VelinovAngel/My-ASP-Core-Web-Project
Web/BikesBooking.Web/Controllers/ApiController/StatisticApiController.cs
1,518
C#
// Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Python.Analysis.Diagnostics; using Microsoft.Python.Analysis.Types; using Microsoft.Python.Core.Collections; using Microsoft.Python.Parsing.Ast; namespace Microsoft.Python.Analysis.Analyzer { public interface IPythonAnalyzer { Task WaitForCompleteAnalysisAsync(CancellationToken cancellationToken = default); /// <summary> /// Schedules module for analysis. Module will be scheduled if version of AST is greater than the one used to get previous analysis /// </summary> void EnqueueDocumentForAnalysis(IPythonModule module, PythonAst ast, int version); /// <summary> /// Schedules module for analysis for its existing AST, but with new dependencies. /// Module will be scheduled if any of the dependencies has analysis version greater than the module. /// </summary> void EnqueueDocumentForAnalysis(IPythonModule module, ImmutableArray<IPythonModule> dependencies); /// <summary> /// Invalidates current analysis for the module, assuming that AST for the new analysis will be provided later. /// </summary> void InvalidateAnalysis(IPythonModule module); /// <summary> /// Removes modules from the analysis. /// </summary> void RemoveAnalysis(IPythonModule module); /// <summary> /// Get most recent analysis for module. If after specified time analysis isn't available, returns previously calculated analysis. /// </summary> Task<IDocumentAnalysis> GetAnalysisAsync(IPythonModule module, int waitTime = 200, CancellationToken cancellationToken = default); /// <summary> /// Runs linters on the modules /// </summary> IReadOnlyList<DiagnosticsEntry> LintModule(IPythonModule module); /// <summary> /// Removes all the modules from the analysis and restarts it, including stubs. /// </summary> Task ResetAnalyzer(); /// <summary> /// Returns list of currently loaded modules. /// </summary> IReadOnlyList<IPythonModule> LoadedModules { get; } /// <summary> /// Fires when analysis is complete. /// </summary> event EventHandler<AnalysisCompleteEventArgs> AnalysisComplete; /// <summary> /// Attempts to restore modules analysis from database. /// </summary> /// <param name="module"></param> /// <returns></returns> IDocumentAnalysis TryRestoreCachedAnalysis(IPythonModule module); } }
40.590361
139
0.68596
[ "Apache-2.0" ]
6paklata/python-language-server
src/Analysis/Ast/Impl/Analyzer/Definitions/IPythonAnalyzer.cs
3,371
C#
using DevanagariApp.BL; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace DevanagariApp.Forms { public partial class frmProcrastination : Form { public frmProcrastination() { InitializeComponent(); } private void frmProcrastination_Load(object sender, EventArgs e) { if (!File.Exists(Appender.TodaysFile)) { File.Create(Appender.TodaysFile); } txtLog.Text = Appender.ReadAllText(false); //Scroll to end txtLog.SelectionStart = txtLog.Text.Length; txtLog.ScrollToCaret(); } private void nmThreashold_ValueChanged(object sender, EventArgs e) { if (nmThreashold.Value <= 1) { nmThreashold.Value = 1; } } private void btnClear_Click(object sender, EventArgs e) { try { File.Delete(Appender.TodaysFile); File.Create(AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.ToString("MM-dd-yyyy") + ".bin"); frmProcrastination_Load(null, null); } catch { } } private void tmrMain_Tick(object sender, EventArgs e) { tmrMain.Interval = Convert.ToInt32(nmThreashold.Value) * 1000; } private void tmrClock_Tick(object sender, EventArgs e) { lblTime.Text = DateTime.Now.ToString("hh:mm:ss tt"); } } }
25.735294
114
0.569714
[ "Apache-2.0" ]
nitinjs/devanagari-keyboard
Source Code/DevanagariApp/Forms/frmProcrastination.cs
1,752
C#
using System; using System.Net.Http; using System.Text.Json; using System.Threading.Tasks; namespace Extensions.IP { public static class IpClientExtension { public static async Task<IPInfo> GetIpInfoAsync(this string ipAddress) { string url = null; if (string.IsNullOrEmpty(ipAddress)) { url = "json?fields=66846719"; } else { url = $"json/{ipAddress}?fields=66846719"; } HttpClient httpClient = new HttpClient { BaseAddress = new Uri("http://ip-api.com"), Timeout = TimeSpan.FromSeconds(20) }; var resposne = await httpClient.GetAsync(url); return JsonSerializer.Deserialize<IPInfo>(await resposne.Content.ReadAsStringAsync()); } } }
30.310345
98
0.554039
[ "MIT" ]
Yaroslav08/Extensions
Extensions/Extensions.IP/IpClientExtension.cs
881
C#
namespace AngleSharp.Css.Values { using AngleSharp.Css.Dom; using System; /// <summary> /// Represents the CSS initial value. /// </summary> struct CssInitialValue : ICssSpecialValue { #region Fields private readonly ICssValue _value; #endregion #region ctor /// <summary> /// Creates a new initial value using the provided data. /// </summary> /// <param name="value">The initial data.</param> public CssInitialValue(ICssValue value) { _value = value; } #endregion #region Properties /// <summary> /// Gets the initial value. /// </summary> public ICssValue Value => _value; /// <summary> /// Gets the CSS text representation. /// </summary> public String CssText => CssKeywords.Initial; #endregion } }
20.755556
64
0.543897
[ "MIT" ]
AngleSharp/AngleSharp.Css
src/AngleSharp.Css/Values/Raws/CssInitialValue.cs
934
C#
// Copyright 2011 Murray Grant // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using MurrayGrant.ReadablePassphrase.Words; using MurrayGrant.ReadablePassphrase.Dictionaries; namespace MurrayGrant.ReadablePassphrase.WordTemplate { public class IndefinitePronounTemplate : Template { private readonly bool _IsPlural; private readonly bool _IsPersonal; public override bool IncludeInAlreadyUsedList { get { return false; } } public bool IsPlural { get { return _IsPlural; } } public IndefinitePronounTemplate(bool isPlural, bool isPersonal) { this._IsPlural = isPlural; this._IsPersonal = isPersonal; } public override WordAndString ChooseWord(WordDictionary words, Random.RandomSourceBase randomness, IEnumerable<Word> alreadyChosen) { _ = words ?? throw new ArgumentNullException(nameof(words)); _ = randomness ?? throw new ArgumentNullException(nameof(randomness)); _ = alreadyChosen ?? throw new ArgumentNullException(nameof(alreadyChosen)); var word = words.ChooseWord<IndefinitePronoun>(randomness, alreadyChosen, x => x.IsPersonal == _IsPersonal); if (!this._IsPlural) return new WordAndString(word, word.Singular); else return new WordAndString(word, word.Plural); } } }
40.9
140
0.684597
[ "Apache-2.0" ]
4-FLOSS-Free-Libre-Open-Source-Software/readablepassphrasegenerator
trunk/ReadablePassphrase.Core/WordTemplate/IndefinitePronounTemplate.cs
2,047
C#
namespace PortDetection { partial class PreSetting { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.lbExpSequence = new System.Windows.Forms.ListBox(); this.tbLastTime = new System.Windows.Forms.TextBox(); this.lblTrainOrTest = new System.Windows.Forms.Label(); this.lblLastTime = new System.Windows.Forms.Label(); this.rbTrain = new System.Windows.Forms.RadioButton(); this.rbTest = new System.Windows.Forms.RadioButton(); this.btnSetSAdd = new System.Windows.Forms.Button(); this.btnSetSDelete = new System.Windows.Forms.Button(); this.gbSetSequence = new System.Windows.Forms.GroupBox(); this.cbSecondOrMinute = new System.Windows.Forms.CheckBox(); this.gbSetDataPath = new System.Windows.Forms.GroupBox(); this.textBox2 = new System.Windows.Forms.TextBox(); this.lblExName = new System.Windows.Forms.Label(); this.lblDataPath = new System.Windows.Forms.Label(); this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker(); this.lblDPValue = new System.Windows.Forms.Label(); this.btnChooseDataPath = new System.Windows.Forms.Button(); this.gbSetName = new System.Windows.Forms.GroupBox(); this.gbSetPattern = new System.Windows.Forms.GroupBox(); this.rbDownT = new System.Windows.Forms.RadioButton(); this.rbUpT = new System.Windows.Forms.RadioButton(); this.lblWhichToPunishment = new System.Windows.Forms.Label(); this.gbPunishmentChoose = new System.Windows.Forms.GroupBox(); this.rbPCShake = new System.Windows.Forms.RadioButton(); this.rbPCHeat = new System.Windows.Forms.RadioButton(); this.gbSetSequence.SuspendLayout(); this.gbSetDataPath.SuspendLayout(); this.gbSetName.SuspendLayout(); this.gbSetPattern.SuspendLayout(); this.gbPunishmentChoose.SuspendLayout(); this.SuspendLayout(); // // lbExpSequence // this.lbExpSequence.FormattingEnabled = true; this.lbExpSequence.ItemHeight = 15; this.lbExpSequence.Location = new System.Drawing.Point(21, 188); this.lbExpSequence.Name = "lbExpSequence"; this.lbExpSequence.Size = new System.Drawing.Size(228, 199); this.lbExpSequence.TabIndex = 0; // // tbLastTime // this.tbLastTime.Location = new System.Drawing.Point(149, 87); this.tbLastTime.Name = "tbLastTime"; this.tbLastTime.Size = new System.Drawing.Size(57, 25); this.tbLastTime.TabIndex = 2; this.tbLastTime.Text = "3"; // // lblTrainOrTest // this.lblTrainOrTest.AutoSize = true; this.lblTrainOrTest.Location = new System.Drawing.Point(19, 57); this.lblTrainOrTest.Name = "lblTrainOrTest"; this.lblTrainOrTest.Size = new System.Drawing.Size(95, 15); this.lblTrainOrTest.TabIndex = 3; this.lblTrainOrTest.Text = "TrainOrTest"; // // lblLastTime // this.lblLastTime.AutoSize = true; this.lblLastTime.Location = new System.Drawing.Point(156, 57); this.lblLastTime.Name = "lblLastTime"; this.lblLastTime.Size = new System.Drawing.Size(71, 15); this.lblLastTime.TabIndex = 4; this.lblLastTime.Text = "LastTime"; this.lblLastTime.Click += new System.EventHandler(this.lblLastTime_Click); // // rbTrain // this.rbTrain.AutoSize = true; this.rbTrain.Checked = true; this.rbTrain.Location = new System.Drawing.Point(21, 87); this.rbTrain.Name = "rbTrain"; this.rbTrain.Size = new System.Drawing.Size(68, 19); this.rbTrain.TabIndex = 5; this.rbTrain.TabStop = true; this.rbTrain.Text = "Train"; this.rbTrain.UseVisualStyleBackColor = true; // // rbTest // this.rbTest.AutoSize = true; this.rbTest.Location = new System.Drawing.Point(21, 111); this.rbTest.Name = "rbTest"; this.rbTest.Size = new System.Drawing.Size(60, 19); this.rbTest.TabIndex = 6; this.rbTest.TabStop = true; this.rbTest.Text = "Test"; this.rbTest.UseVisualStyleBackColor = true; // // btnSetSAdd // this.btnSetSAdd.Location = new System.Drawing.Point(21, 148); this.btnSetSAdd.Name = "btnSetSAdd"; this.btnSetSAdd.Size = new System.Drawing.Size(92, 23); this.btnSetSAdd.TabIndex = 7; this.btnSetSAdd.Text = "Add"; this.btnSetSAdd.UseVisualStyleBackColor = true; this.btnSetSAdd.Click += new System.EventHandler(this.btnSetSAdd_Click); // // btnSetSDelete // this.btnSetSDelete.Location = new System.Drawing.Point(149, 148); this.btnSetSDelete.Name = "btnSetSDelete"; this.btnSetSDelete.Size = new System.Drawing.Size(89, 23); this.btnSetSDelete.TabIndex = 8; this.btnSetSDelete.Text = "Detele"; this.btnSetSDelete.UseVisualStyleBackColor = true; this.btnSetSDelete.Click += new System.EventHandler(this.btnSetSDelete_Click); // // gbSetSequence // this.gbSetSequence.Controls.Add(this.cbSecondOrMinute); this.gbSetSequence.Controls.Add(this.btnSetSDelete); this.gbSetSequence.Controls.Add(this.lbExpSequence); this.gbSetSequence.Controls.Add(this.btnSetSAdd); this.gbSetSequence.Controls.Add(this.tbLastTime); this.gbSetSequence.Controls.Add(this.rbTest); this.gbSetSequence.Controls.Add(this.lblTrainOrTest); this.gbSetSequence.Controls.Add(this.rbTrain); this.gbSetSequence.Controls.Add(this.lblLastTime); this.gbSetSequence.Location = new System.Drawing.Point(27, 28); this.gbSetSequence.Name = "gbSetSequence"; this.gbSetSequence.Size = new System.Drawing.Size(292, 432); this.gbSetSequence.TabIndex = 9; this.gbSetSequence.TabStop = false; this.gbSetSequence.Text = "Set-Sequence"; // // cbSecondOrMinute // this.cbSecondOrMinute.AutoSize = true; this.cbSecondOrMinute.Location = new System.Drawing.Point(212, 89); this.cbSecondOrMinute.Name = "cbSecondOrMinute"; this.cbSecondOrMinute.Size = new System.Drawing.Size(37, 19); this.cbSecondOrMinute.TabIndex = 9; this.cbSecondOrMinute.Text = "s"; this.cbSecondOrMinute.UseVisualStyleBackColor = true; this.cbSecondOrMinute.CheckedChanged += new System.EventHandler(this.cbTimeOrHour_CheckedChanged); // // gbSetDataPath // this.gbSetDataPath.Controls.Add(this.btnChooseDataPath); this.gbSetDataPath.Controls.Add(this.lblDPValue); this.gbSetDataPath.Controls.Add(this.lblDataPath); this.gbSetDataPath.Location = new System.Drawing.Point(373, 28); this.gbSetDataPath.Name = "gbSetDataPath"; this.gbSetDataPath.Size = new System.Drawing.Size(300, 130); this.gbSetDataPath.TabIndex = 10; this.gbSetDataPath.TabStop = false; this.gbSetDataPath.Text = "ExInit-SetPath"; // // textBox2 // this.textBox2.Location = new System.Drawing.Point(151, 40); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(100, 25); this.textBox2.TabIndex = 14; // // lblExName // this.lblExName.AutoSize = true; this.lblExName.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.lblExName.Location = new System.Drawing.Point(6, 43); this.lblExName.Name = "lblExName"; this.lblExName.Size = new System.Drawing.Size(127, 15); this.lblExName.TabIndex = 13; this.lblExName.Text = "ExperimentName:"; // // lblDataPath // this.lblDataPath.AutoSize = true; this.lblDataPath.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.lblDataPath.Location = new System.Drawing.Point(14, 34); this.lblDataPath.Name = "lblDataPath"; this.lblDataPath.Size = new System.Drawing.Size(79, 15); this.lblDataPath.TabIndex = 11; this.lblDataPath.Text = "DataPath:"; // // lblDPValue // this.lblDPValue.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.lblDPValue.Location = new System.Drawing.Point(99, 34); this.lblDPValue.Name = "lblDPValue"; this.lblDPValue.Size = new System.Drawing.Size(71, 15); this.lblDPValue.TabIndex = 19; this.lblDPValue.Text = "DataPath"; this.lblDPValue.Click += new System.EventHandler(this.lblDPValue_Click); // // btnChooseDataPath // this.btnChooseDataPath.Location = new System.Drawing.Point(94, 95); this.btnChooseDataPath.Name = "btnChooseDataPath"; this.btnChooseDataPath.Size = new System.Drawing.Size(89, 29); this.btnChooseDataPath.TabIndex = 20; this.btnChooseDataPath.Text = "Open"; this.btnChooseDataPath.UseVisualStyleBackColor = true; this.btnChooseDataPath.Click += new System.EventHandler(this.btnChooseDataPath_Click); // // gbSetName // this.gbSetName.Controls.Add(this.textBox2); this.gbSetName.Controls.Add(this.lblExName); this.gbSetName.Location = new System.Drawing.Point(373, 176); this.gbSetName.Name = "gbSetName"; this.gbSetName.Size = new System.Drawing.Size(300, 91); this.gbSetName.TabIndex = 19; this.gbSetName.TabStop = false; this.gbSetName.Text = "ExInit-SetName"; // // gbSetPattern // this.gbSetPattern.Controls.Add(this.lblWhichToPunishment); this.gbSetPattern.Controls.Add(this.rbDownT); this.gbSetPattern.Controls.Add(this.rbUpT); this.gbSetPattern.Location = new System.Drawing.Point(373, 282); this.gbSetPattern.Name = "gbSetPattern"; this.gbSetPattern.Size = new System.Drawing.Size(300, 82); this.gbSetPattern.TabIndex = 20; this.gbSetPattern.TabStop = false; this.gbSetPattern.Text = "ExInit-SetPattern"; // // rbDownT // this.rbDownT.AutoSize = true; this.rbDownT.Location = new System.Drawing.Point(183, 34); this.rbDownT.Name = "rbDownT"; this.rbDownT.Size = new System.Drawing.Size(68, 19); this.rbDownT.TabIndex = 8; this.rbDownT.TabStop = true; this.rbDownT.Text = "DownT"; this.rbDownT.UseVisualStyleBackColor = true; // // rbUpT // this.rbUpT.AutoSize = true; this.rbUpT.Checked = true; this.rbUpT.Location = new System.Drawing.Point(115, 34); this.rbUpT.Name = "rbUpT"; this.rbUpT.Size = new System.Drawing.Size(52, 19); this.rbUpT.TabIndex = 7; this.rbUpT.TabStop = true; this.rbUpT.Text = "UpT"; this.rbUpT.UseVisualStyleBackColor = true; // // lblWhichToPunishment // this.lblWhichToPunishment.AutoSize = true; this.lblWhichToPunishment.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.lblWhichToPunishment.Location = new System.Drawing.Point(6, 34); this.lblWhichToPunishment.Name = "lblWhichToPunishment"; this.lblWhichToPunishment.Size = new System.Drawing.Size(102, 15); this.lblWhichToPunishment.TabIndex = 14; this.lblWhichToPunishment.Text = "Punishment:"; // // gbPunishmentChoose // this.gbPunishmentChoose.Controls.Add(this.rbPCShake); this.gbPunishmentChoose.Controls.Add(this.rbPCHeat); this.gbPunishmentChoose.Location = new System.Drawing.Point(373, 378); this.gbPunishmentChoose.Name = "gbPunishmentChoose"; this.gbPunishmentChoose.Size = new System.Drawing.Size(300, 82); this.gbPunishmentChoose.TabIndex = 21; this.gbPunishmentChoose.TabStop = false; this.gbPunishmentChoose.Text = "ExInit-setPunishment"; // // rbPCShake // this.rbPCShake.AutoSize = true; this.rbPCShake.Location = new System.Drawing.Point(151, 36); this.rbPCShake.Name = "rbPCShake"; this.rbPCShake.Size = new System.Drawing.Size(68, 19); this.rbPCShake.TabIndex = 8; this.rbPCShake.TabStop = true; this.rbPCShake.Text = "Shake"; this.rbPCShake.UseVisualStyleBackColor = true; // // rbPCHeat // this.rbPCHeat.AutoSize = true; this.rbPCHeat.Checked = true; this.rbPCHeat.Location = new System.Drawing.Point(66, 36); this.rbPCHeat.Name = "rbPCHeat"; this.rbPCHeat.Size = new System.Drawing.Size(60, 19); this.rbPCHeat.TabIndex = 7; this.rbPCHeat.TabStop = true; this.rbPCHeat.Text = "Heat"; this.rbPCHeat.UseVisualStyleBackColor = true; // // PreSetting // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(742, 498); this.Controls.Add(this.gbPunishmentChoose); this.Controls.Add(this.gbSetPattern); this.Controls.Add(this.gbSetName); this.Controls.Add(this.gbSetDataPath); this.Controls.Add(this.gbSetSequence); this.Name = "PreSetting"; this.Text = "PreSetting"; this.gbSetSequence.ResumeLayout(false); this.gbSetSequence.PerformLayout(); this.gbSetDataPath.ResumeLayout(false); this.gbSetDataPath.PerformLayout(); this.gbSetName.ResumeLayout(false); this.gbSetName.PerformLayout(); this.gbSetPattern.ResumeLayout(false); this.gbSetPattern.PerformLayout(); this.gbPunishmentChoose.ResumeLayout(false); this.gbPunishmentChoose.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ListBox lbExpSequence; private System.Windows.Forms.TextBox tbLastTime; private System.Windows.Forms.Label lblTrainOrTest; private System.Windows.Forms.Label lblLastTime; private System.Windows.Forms.RadioButton rbTrain; private System.Windows.Forms.RadioButton rbTest; private System.Windows.Forms.Button btnSetSAdd; private System.Windows.Forms.Button btnSetSDelete; private System.Windows.Forms.GroupBox gbSetSequence; private System.Windows.Forms.GroupBox gbSetDataPath; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.Label lblExName; private System.Windows.Forms.Label lblDataPath; private System.ComponentModel.BackgroundWorker backgroundWorker1; private System.Windows.Forms.CheckBox cbSecondOrMinute; private System.Windows.Forms.Button btnChooseDataPath; private System.Windows.Forms.Label lblDPValue; private System.Windows.Forms.GroupBox gbSetName; private System.Windows.Forms.GroupBox gbSetPattern; private System.Windows.Forms.Label lblWhichToPunishment; private System.Windows.Forms.RadioButton rbDownT; private System.Windows.Forms.RadioButton rbUpT; private System.Windows.Forms.GroupBox gbPunishmentChoose; private System.Windows.Forms.RadioButton rbPCShake; private System.Windows.Forms.RadioButton rbPCHeat; } }
48.245989
163
0.59898
[ "MIT" ]
Taaccoo-beta/Flight-Simulator-In-Drosophila
PortDetection/PortDetection/PreSetting.Designer.cs
18,064
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.IO { public sealed class FileStreamOptions { private FileMode _mode = FileMode.Open; private FileAccess _access = FileAccess.Read; private FileShare _share = FileStream.DefaultShare; private FileOptions _options; private long _preallocationSize; private int _bufferSize = FileStream.DefaultBufferSize; /// <summary> /// One of the enumeration values that determines how to open or create the file. /// </summary> /// <exception cref="T:System.ArgumentOutOfRangeException">When <paramref name="value" /> contains an invalid value.</exception> public FileMode Mode { get => _mode; set { if (value < FileMode.CreateNew || value > FileMode.Append) { ThrowHelper.ArgumentOutOfRangeException_Enum_Value(); } _mode = value; } } /// <summary> /// A bitwise combination of the enumeration values that determines how the file can be accessed by the <see cref="FileStream" /> object. This also determines the values returned by the <see cref="System.IO.FileStream.CanRead" /> and <see cref="System.IO.FileStream.CanWrite" /> properties of the <see cref="FileStream" /> object. /// </summary> /// <exception cref="T:System.ArgumentOutOfRangeException">When <paramref name="value" /> contains an invalid value.</exception> public FileAccess Access { get => _access; set { if (value < FileAccess.Read || value > FileAccess.ReadWrite) { ThrowHelper.ArgumentOutOfRangeException_Enum_Value(); } _access = value; } } /// <summary> /// A bitwise combination of the enumeration values that determines how the file will be shared by processes. The default value is <see cref="System.IO.FileShare.Read" />. /// </summary> /// <exception cref="T:System.ArgumentOutOfRangeException">When <paramref name="value" /> contains an invalid value.</exception> public FileShare Share { get => _share; set { // don't include inheritable in our bounds check for share FileShare tempshare = value & ~FileShare.Inheritable; if (tempshare < FileShare.None || tempshare > (FileShare.ReadWrite | FileShare.Delete)) { ThrowHelper.ArgumentOutOfRangeException_Enum_Value(); } _share = value; } } /// <summary> /// A bitwise combination of the enumeration values that specifies additional file options. The default value is <see cref="System.IO.FileOptions.None" />, which indicates synchronous IO. /// </summary> /// <exception cref="T:System.ArgumentOutOfRangeException">When <paramref name="value" /> contains an invalid value.</exception> public FileOptions Options { get => _options; set { // NOTE: any change to FileOptions enum needs to be matched here in the error validation if (value != FileOptions.None && (value & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose | FileOptions.SequentialScan | FileOptions.Encrypted | (FileOptions)0x20000000 /* NoBuffering */)) != 0) { ThrowHelper.ArgumentOutOfRangeException_Enum_Value(); } _options = value; } } /// <summary> /// The initial allocation size in bytes for the file. A positive value is effective only when a regular file is being created, overwritten, or replaced. /// Negative values are not allowed. /// In other cases (including the default 0 value), it's ignored. /// </summary> /// <exception cref="T:System.ArgumentOutOfRangeException">When <paramref name="value" /> is negative.</exception> public long PreallocationSize { get => _preallocationSize; set => _preallocationSize = value >= 0 ? value : throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); } /// <summary> /// The size of the buffer used by <see cref="FileStream" /> for buffering. The default buffer size is 4096. /// 0 or 1 means that buffering should be disabled. Negative values are not allowed. /// </summary> /// <exception cref="T:System.ArgumentOutOfRangeException">When <paramref name="value" /> is negative.</exception> public int BufferSize { get => _bufferSize; set => _bufferSize = value >= 0 ? value : throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); } } }
45.692982
338
0.604339
[ "MIT" ]
333fred/runtime
src/libraries/System.Private.CoreLib/src/System/IO/FileStreamOptions.cs
5,209
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player_Range : MonoBehaviour { Player _player; private Tower target; private Queue<Tower> towers = new Queue<Tower>(); [SerializeField] private AudioSource tirar; // Start is called before the first frame update void Start() { _player = transform.parent.gameObject.GetComponent<Player>(); } // Update is called once per frame void Update(){ //Se não houver um alvo definido, mas houverem inimigos na lista: if(target == null && towers.Count > 0){ //Essa função pega o primeiro inimigo da lista, atribui ao alvo e o remove da lista target = towers.Dequeue(); target.GetComponent<Tower>().SetRemoveVisibility(true); } if(target != null && Input.GetKeyDown(KeyCode.R)){ target.GetComponent<Tower>().SetRemoveVisibility(false); _player.DreamPower(target.GetComponent<Tower>().NecessaryPower()); Destroy(target.gameObject); tirar.Play(0); } } void OnTriggerEnter2D(Collider2D col){ if(col.tag == "Tower"){ //Adiciona o inimigo à fila de inimigos towers.Enqueue(col.GetComponent<Tower>()); } } //É chamada quando algum objeto sai no alcance da torre void OnTriggerExit2D(Collider2D col){ if(col.tag == "Tower"){ target.GetComponent<Tower>().SetRemoveVisibility(false); target = null; } } //Retorna o alvo atual da torre public Tower Target(){ return target; } }
22.351351
89
0.618501
[ "MIT" ]
FellowshipOfTheGame/Pesadelho
Pesadelho/Assets/Scripts/Player/Player_Range.cs
1,661
C#
using System; using System.Collections.Generic; using System.Linq; namespace A3_DbContext { public class StudentRepository: Repository<Student> { public static Dictionary<string, Student> studentByDni = new Dictionary<string, Student>(); public override SaveValidation<Student> Add(Student entity) { var output = base.Add(entity); if (output.SaveValidationSuccesful) { studentByDni.Add(entity.Dni, entity); } return output; } public override SaveValidation<Student> Update(Student entity) { var output = base.Update(entity); if (output.SaveValidationSuccesful) { studentByDni[output.Entity.Dni] = output.Entity; } return output; } public override DeleteValidation<Student> Delete(Student entity) { var output = base.Delete(entity); if (output.DeleteValidationSuccesful) { studentByDni.Remove(output.Entity.Dni); } return output; } public static Student GetStudentByDni(string strDni) { if (studentByDni.ContainsKey(strDni)) { return studentByDni[strDni]; } return null; } } }
23.87931
93
0.556679
[ "MIT" ]
marcvil/Exercicis-.NET-Course
Bloc C# y Java/Practica Troncal/A3 Repositories/A3 DbContext/Context/StudentRepository.cs
1,387
C#
// // System.Web.Security.FormsAuthentication // // Authors: // Gonzalo Paniagua Javier (gonzalo@ximian.com) // // (C) 2002,2003 Ximian, Inc (http://www.ximian.com) // Copyright (c) 2005-2010 Novell, Inc (http://www.novell.com) // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Collections; using System.IO; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Compilation; using System.Web.Util; using System.Globalization; using System.Collections.Specialized; namespace System.Web.Security { // CAS - no InheritanceDemand here as the class is sealed [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)] public sealed class FormsAuthentication { static string authConfigPath = "system.web/authentication"; static string machineKeyConfigPath = "system.web/machineKey"; static object locker = new object (); static bool initialized; static string cookieName; static string cookiePath; static int timeout; static FormsProtectionEnum protection; static bool requireSSL; static bool slidingExpiration; static string cookie_domain; static HttpCookieMode cookie_mode; static bool cookies_supported; static string default_url; static bool enable_crossapp_redirects; static string login_url; // same names and order used in xsp static string [] indexFiles = { "index.aspx", "Default.aspx", "default.aspx", "index.html", "index.htm" }; public static TimeSpan Timeout { get; private set; } public static bool IsEnabled { get { return initialized; } } public static void EnableFormsAuthentication (NameValueCollection configurationData) { BuildManager.AssertPreStartMethodsRunning (); if (configurationData == null || configurationData.Count == 0) return; string value = configurationData ["loginUrl"]; if (!String.IsNullOrEmpty (value)) login_url = value; value = configurationData ["defaultUrl"]; if (!String.IsNullOrEmpty (value)) default_url = value; } public FormsAuthentication () { } public static bool Authenticate (string name, string password) { if (name == null || password == null) return false; Initialize (); HttpContext context = HttpContext.Current; if (context == null) throw new HttpException ("Context is null!"); name = name.ToLower (Helpers.InvariantCulture); AuthenticationSection section = (AuthenticationSection) WebConfigurationManager.GetSection (authConfigPath); FormsAuthenticationCredentials config = section.Forms.Credentials; FormsAuthenticationUser user = config.Users[name]; string stored = null; if (user != null) stored = user.Password; if (stored == null) return false; bool caseInsensitive = true; switch (config.PasswordFormat) { case FormsAuthPasswordFormat.Clear: caseInsensitive = false; /* Do nothing */ break; case FormsAuthPasswordFormat.MD5: password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5); break; case FormsAuthPasswordFormat.SHA1: password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.SHA1); break; } return String.Compare (password, stored, caseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0; } static FormsAuthenticationTicket Decrypt2 (byte [] bytes) { if (protection == FormsProtectionEnum.None) return FormsAuthenticationTicket.FromByteArray (bytes); MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection (machineKeyConfigPath); byte [] result = null; if (protection == FormsProtectionEnum.All) { result = MachineKeySectionUtils.VerifyDecrypt (config, bytes); } else if (protection == FormsProtectionEnum.Encryption) { result = MachineKeySectionUtils.Decrypt (config, bytes); } else if (protection == FormsProtectionEnum.Validation) { result = MachineKeySectionUtils.Verify (config, bytes); } return FormsAuthenticationTicket.FromByteArray (result); } public static FormsAuthenticationTicket Decrypt (string encryptedTicket) { if (String.IsNullOrEmpty (encryptedTicket)) throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket"); Initialize (); FormsAuthenticationTicket ticket; byte [] bytes = Convert.FromBase64String (encryptedTicket); try { ticket = Decrypt2 (bytes); } catch (Exception) { ticket = null; } return ticket; } public static string Encrypt (FormsAuthenticationTicket ticket) { if (ticket == null) throw new ArgumentNullException ("ticket"); Initialize (); byte [] ticket_bytes = ticket.ToByteArray (); if (protection == FormsProtectionEnum.None) return Convert.ToBase64String (ticket_bytes); byte [] result = null; MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection (machineKeyConfigPath); if (protection == FormsProtectionEnum.All) { result = MachineKeySectionUtils.EncryptSign (config, ticket_bytes); } else if (protection == FormsProtectionEnum.Encryption) { result = MachineKeySectionUtils.Encrypt (config, ticket_bytes); } else if (protection == FormsProtectionEnum.Validation) { result = MachineKeySectionUtils.Sign (config, ticket_bytes); } return Convert.ToBase64String (result); } public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie) { return GetAuthCookie (userName, createPersistentCookie, null); } public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath) { Initialize (); if (userName == null) userName = String.Empty; if (strCookiePath == null || strCookiePath.Length == 0) strCookiePath = cookiePath; DateTime now = DateTime.Now; DateTime then; if (createPersistentCookie) then = now.AddMinutes(timeout); else then = DateTime.MinValue; FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1, userName, now, createPersistentCookie?then:now.AddYears (50), createPersistentCookie, String.Empty, cookiePath); HttpCookie cookie = new HttpCookie (cookieName, Encrypt (ticket), strCookiePath, then); if (requireSSL) cookie.Secure = true; if (!String.IsNullOrEmpty (cookie_domain)) cookie.Domain = cookie_domain; return cookie; } internal static string ReturnUrl { get { return HttpContext.Current.Request ["RETURNURL"]; } } public static string GetRedirectUrl (string userName, bool createPersistentCookie) { if (userName == null) return null; Initialize (); HttpRequest request = HttpContext.Current.Request; string returnUrl = ReturnUrl; if (returnUrl != null) return returnUrl; returnUrl = request.ApplicationPath; string apppath = request.PhysicalApplicationPath; bool found = false; foreach (string indexFile in indexFiles) { string filePath = Path.Combine (apppath, indexFile); if (File.Exists (filePath)) { returnUrl = UrlUtils.Combine (returnUrl, indexFile); found = true; break; } } if (!found) returnUrl = UrlUtils.Combine (returnUrl, "index.aspx"); return returnUrl; } static string HashPasswordForStoringInConfigFile (string password, FormsAuthPasswordFormat passwordFormat) { if (password == null) throw new ArgumentNullException ("password"); byte [] bytes; switch (passwordFormat) { case FormsAuthPasswordFormat.MD5: bytes = MD5.Create ().ComputeHash (Encoding.UTF8.GetBytes (password)); break; case FormsAuthPasswordFormat.SHA1: bytes = SHA1.Create ().ComputeHash (Encoding.UTF8.GetBytes (password)); break; default: throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat"); } return MachineKeySectionUtils.GetHexString (bytes); } public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat) { if (password == null) throw new ArgumentNullException ("password"); if (passwordFormat == null) throw new ArgumentNullException ("passwordFormat"); if (String.Compare (passwordFormat, "MD5", StringComparison.OrdinalIgnoreCase) == 0) { return HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5); } else if (String.Compare (passwordFormat, "SHA1", StringComparison.OrdinalIgnoreCase) == 0) { return HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.SHA1); } else { throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat"); } } public static void Initialize () { if (initialized) return; lock (locker) { if (initialized) return; AuthenticationSection section = (AuthenticationSection)WebConfigurationManager.GetSection (authConfigPath); FormsAuthenticationConfiguration config = section.Forms; cookieName = config.Name; Timeout = config.Timeout; timeout = (int)config.Timeout.TotalMinutes; cookiePath = config.Path; protection = config.Protection; requireSSL = config.RequireSSL; slidingExpiration = config.SlidingExpiration; cookie_domain = config.Domain; cookie_mode = config.Cookieless; cookies_supported = true; /* XXX ? */ if (!String.IsNullOrEmpty (default_url)) default_url = MapUrl (default_url); else default_url = MapUrl(config.DefaultUrl); enable_crossapp_redirects = config.EnableCrossAppRedirects; if (!String.IsNullOrEmpty (login_url)) login_url = MapUrl (login_url); else login_url = MapUrl(config.LoginUrl); initialized = true; } } static string MapUrl (string url) { if (UrlUtils.IsRelativeUrl (url)) return UrlUtils.Combine (HttpRuntime.AppDomainAppVirtualPath, url); else return UrlUtils.ResolveVirtualPathFromAppAbsolute (url); } public static void RedirectFromLoginPage (string userName, bool createPersistentCookie) { RedirectFromLoginPage (userName, createPersistentCookie, null); } public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath) { if (userName == null) return; Initialize (); SetAuthCookie (userName, createPersistentCookie, strCookiePath); Redirect (GetRedirectUrl (userName, createPersistentCookie), false); } public static FormsAuthenticationTicket RenewTicketIfOld (FormsAuthenticationTicket tOld) { if (tOld == null) return null; DateTime now = DateTime.Now; TimeSpan toIssue = now - tOld.IssueDate; TimeSpan toExpiration = tOld.Expiration - now; if (toExpiration > toIssue) return tOld; FormsAuthenticationTicket tNew = tOld.Clone (); tNew.SetDates (now, now + (tOld.Expiration - tOld.IssueDate)); return tNew; } public static void SetAuthCookie (string userName, bool createPersistentCookie) { Initialize (); SetAuthCookie (userName, createPersistentCookie, cookiePath); } public static void SetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath) { HttpContext context = HttpContext.Current; if (context == null) throw new HttpException ("Context is null!"); HttpResponse response = context.Response; if (response == null) throw new HttpException ("Response is null!"); response.Cookies.Add (GetAuthCookie (userName, createPersistentCookie, strCookiePath)); } public static void SignOut () { Initialize (); HttpContext context = HttpContext.Current; if (context == null) throw new HttpException ("Context is null!"); HttpResponse response = context.Response; if (response == null) throw new HttpException ("Response is null!"); HttpCookieCollection cc = response.Cookies; cc.Remove (cookieName); HttpCookie expiration_cookie = new HttpCookie (cookieName, String.Empty); expiration_cookie.Expires = new DateTime (1999, 10, 12); expiration_cookie.Path = cookiePath; if (!String.IsNullOrEmpty (cookie_domain)) expiration_cookie.Domain = cookie_domain; cc.Add (expiration_cookie); Roles.DeleteCookie (); } public static string FormsCookieName { get { Initialize (); return cookieName; } } public static string FormsCookiePath { get { Initialize (); return cookiePath; } } public static bool RequireSSL { get { Initialize (); return requireSSL; } } public static bool SlidingExpiration { get { Initialize (); return slidingExpiration; } } public static string CookieDomain { get { Initialize (); return cookie_domain; } } public static HttpCookieMode CookieMode { get { Initialize (); return cookie_mode; } } public static bool CookiesSupported { get { Initialize (); return cookies_supported; } } public static string DefaultUrl { get { Initialize (); return default_url; } } public static bool EnableCrossAppRedirects { get { Initialize (); return enable_crossapp_redirects; } } public static string LoginUrl { get { Initialize (); return login_url; } } public static void RedirectToLoginPage () { Redirect (LoginUrl); } [MonoTODO ("needs more tests")] public static void RedirectToLoginPage (string extraQueryString) { // TODO: if ? is in LoginUrl (legal?), ? in query (legal?) ... Redirect (LoginUrl + "?" + extraQueryString); } static void Redirect (string url) { HttpContext.Current.Response.Redirect (url); } static void Redirect (string url, bool end) { HttpContext.Current.Response.Redirect (url, end); } } }
29.797619
130
0.716141
[ "Apache-2.0" ]
AvolitesMarkDaniel/mono
mcs/class/System.Web/System.Web.Security/FormsAuthentication.cs
15,018
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Enums.cs" company="Jamie Dixon Ltd"> // Jamie Dixon // </copyright> // <summary> // Defines the static Enums type. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace GraphVizWrapper { public static class Enums { public enum GraphReturnType { Pdf, Jpg, Png, Plain, PlainExt, Svg } public enum RenderingEngine { Dot, // First item in enum is default rendering engine (E[0]) Neato, Twopi, Circo, Fdp, Sfdp, Patchwork, Osage } } }
23.128205
120
0.331486
[ "MIT" ]
JamieDixon/GraphViz-C-Sharp-Wrapper
src/GraphVizWrapper/Enums.cs
904
C#
using System; using SpecFlowMasterClass.SpecOverflow.Specs.WebUI.Drivers; using SpecFlowMasterClass.SpecOverflow.Web.Models; using TechTalk.SpecFlow; namespace SpecFlowMasterClass.SpecOverflow.Specs.WebUI.StepDefinitions { [Binding] public class RegistrationStepDefinitions { private readonly RegisterPageDriver _registerPageDriver; public RegistrationStepDefinitions(RegisterPageDriver registerPageDriver) { _registerPageDriver = registerPageDriver; } [Given(@"there is a user registered with user name ""([^""]*)"" and password ""([^""]*)""")] public void GivenThereIsAUserRegisteredWithUserNameAndPassword(string userName, string password) { _registerPageDriver.Perform( new RegisterInputModel { UserName = userName, Password = password, PasswordReEnter = password }); } [When(@"the user attempts to register with user name ""([^""]*)"" and password ""([^""]*)""")] public void WhenTheUserAttemptsToRegisterWithUserNameAndPassword(string userName, string password) { _registerPageDriver.Perform( new RegisterInputModel { UserName = userName, Password = password, PasswordReEnter = password }, true); } [Then(@"the registration should be successful")] public void ThenTheRegistrationShouldBeSuccessful() { _registerPageDriver.ShouldBeSuccessful(); } } }
37.525
113
0.670886
[ "MIT" ]
agentHoover/SpecFlowMasterClass.SpecOverflow
SpecFlowMasterClass.SpecOverflow.Specs.WebUI/StepDefinitions/RegistrationStepDefinitions.cs
1,501
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.IO; using System.Text; using System.Xml.Schema; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading.Tasks; namespace System.Xml { internal partial class XmlTextReaderImpl : XmlReader, IXmlLineInfo, IXmlNamespaceResolver { private static UTF8Encoding s_utf8BomThrowing; private static UTF8Encoding UTF8BomThrowing => s_utf8BomThrowing ?? (s_utf8BomThrowing = new UTF8Encoding(encoderShouldEmitUTF8Identifier: true, throwOnInvalidBytes: true)); // // Private helper types // // ParsingFunction = what should the reader do when the next Read() is called private enum ParsingFunction { ElementContent = 0, NoData, OpenUrl, SwitchToInteractive, SwitchToInteractiveXmlDecl, DocumentContent, MoveToElementContent, PopElementContext, PopEmptyElementContext, ResetAttributesRootLevel, Error, Eof, ReaderClosed, EntityReference, InIncrementalRead, FragmentAttribute, ReportEndEntity, AfterResolveEntityInContent, AfterResolveEmptyEntityInContent, XmlDeclarationFragment, GoToEof, PartialTextValue, // these two states must be last; see InAttributeValueIterator property InReadAttributeValue, InReadValueChunk, InReadContentAsBinary, InReadElementContentAsBinary, } private enum ParsingMode { Full, SkipNode, SkipContent, } private enum EntityType { CharacterDec, CharacterHex, CharacterNamed, Expanded, Skipped, FakeExpanded, Unexpanded, ExpandedInAttribute, } private enum EntityExpandType { All, OnlyGeneral, OnlyCharacter, } private enum IncrementalReadState { // Following values are used in ReadText, ReadBase64 and ReadBinHex (V1 streaming methods) Text, StartTag, PI, CDATA, Comment, Attributes, AttributeValue, ReadData, EndElement, End, // Following values are used in ReadTextChunk, ReadContentAsBase64 and ReadBinHexChunk (V2 streaming methods) ReadValueChunk_OnCachedValue, ReadValueChunk_OnPartialValue, ReadContentAsBinary_OnCachedValue, ReadContentAsBinary_OnPartialValue, ReadContentAsBinary_End, } // // Fields // private readonly bool _useAsync; #region Later Init Fields //later init means in the construction stage, do not open filestream and do not read any data from Stream/TextReader //the purpose is to make the Create of XmlReader do not block on IO. private class LaterInitParam { public bool useAsync = false; public Stream inputStream; public byte[] inputBytes; public int inputByteCount; public Uri inputbaseUri; public string inputUriStr; public XmlResolver inputUriResolver; public XmlParserContext inputContext; public TextReader inputTextReader; public InitInputType initType = InitInputType.Invalid; } private LaterInitParam _laterInitParam = null; private enum InitInputType { UriString, Stream, TextReader, Invalid } #endregion // XmlCharType instance private XmlCharType _xmlCharType = XmlCharType.Instance; // current parsing state (aka. scanner data) private ParsingState _ps; // parsing function = what to do in the next Read() (3-items-long stack, usually used just 2 level) private ParsingFunction _parsingFunction; private ParsingFunction _nextParsingFunction; private ParsingFunction _nextNextParsingFunction; // stack of nodes private NodeData[] _nodes; // current node private NodeData _curNode; // current index private int _index = 0; // attributes info private int _curAttrIndex = -1; private int _attrCount; private int _attrHashtable; private int _attrDuplWalkCount; private bool _attrNeedNamespaceLookup; private bool _fullAttrCleanup; private NodeData[] _attrDuplSortingArray; // name table private XmlNameTable _nameTable; private bool _nameTableFromSettings; // resolver private XmlResolver _xmlResolver; // this is only for constructors that takes url private readonly string _url = string.Empty; // settings private bool _normalize; private bool _supportNamespaces = true; private WhitespaceHandling _whitespaceHandling; private DtdProcessing _dtdProcessing = DtdProcessing.Parse; private EntityHandling _entityHandling; private readonly bool _ignorePIs; private readonly bool _ignoreComments; private readonly bool _checkCharacters; private readonly int _lineNumberOffset; private readonly int _linePositionOffset; private readonly bool _closeInput; private readonly long _maxCharactersInDocument; private readonly long _maxCharactersFromEntities; // this flag enables XmlTextReader backwards compatibility; // when false, the reader has been created via XmlReader.Create private readonly bool _v1Compat; // namespace handling private XmlNamespaceManager _namespaceManager; private string _lastPrefix = string.Empty; // xml context (xml:space, xml:lang, default namespace) private XmlContext _xmlContext; // stack of parsing states (=stack of entities) private ParsingState[] _parsingStatesStack; private int _parsingStatesStackTop = -1; // current node base uri and encoding private string _reportedBaseUri; private Encoding _reportedEncoding; // DTD private IDtdInfo _dtdInfo; // fragment parsing private XmlNodeType _fragmentType = XmlNodeType.Document; private XmlParserContext _fragmentParserContext; private bool _fragment; // incremental read private IncrementalReadDecoder _incReadDecoder; private IncrementalReadState _incReadState; private LineInfo _incReadLineInfo; private BinHexDecoder _binHexDecoder; private Base64Decoder _base64Decoder; private int _incReadDepth; private int _incReadLeftStartPos; private int _incReadLeftEndPos; private IncrementalReadCharsDecoder _readCharsDecoder; // ReadAttributeValue helpers private int _attributeValueBaseEntityId; private bool _emptyEntityInAttributeResolved; // Validation helpers private IValidationEventHandling _validationEventHandling; private OnDefaultAttributeUseDelegate _onDefaultAttributeUse; private bool _validatingReaderCompatFlag; // misc private bool _addDefaultAttributesAndNormalize; private readonly StringBuilder _stringBuilder; private bool _rootElementParsed; private bool _standalone; private int _nextEntityId = 1; private ParsingMode _parsingMode; private ReadState _readState = ReadState.Initial; private IDtdEntityInfo _lastEntity; private bool _afterResetState; private int _documentStartBytePos; private int _readValueOffset; // Counters for security settings private long _charactersInDocument; private long _charactersFromEntities; // All entities that are currently being processed private Dictionary<IDtdEntityInfo, IDtdEntityInfo> _currentEntities; // DOM helpers private bool _disableUndeclaredEntityCheck; // Outer XmlReader exposed to the user - either XmlTextReader or XmlTextReaderImpl (when created via XmlReader.Create). // Virtual methods called from within XmlTextReaderImpl must be called on the outer reader so in case the user overrides // some of the XmlTextReader methods we will call the overridden version. private XmlReader _outerReader; //indicate if the XmlResolver is explicit set private bool _xmlResolverIsSet; // // Atomized string constants // private readonly string _xml; private readonly string _xmlNs; // // Constants // private const int MaxBytesToMove = 128; private const int ApproxXmlDeclLength = 80; private const int NodesInitialSize = 8; private const int InitialParsingStatesDepth = 2; private const int MaxByteSequenceLen = 6; // max bytes per character private const int MaxAttrDuplWalkCount = 250; private const int MinWhitespaceLookahedCount = 4096; private const string XmlDeclarationBeginning = "<?xml"; // // Constructors // internal XmlTextReaderImpl() { _curNode = new NodeData(); _parsingFunction = ParsingFunction.NoData; } // Initializes a new instance of the XmlTextReaderImpl class with the specified XmlNameTable. // This constructor is used when creating XmlTextReaderImpl for V1 XmlTextReader internal XmlTextReaderImpl(XmlNameTable nt) { Debug.Assert(nt != null); _v1Compat = true; _outerReader = this; _nameTable = nt; nt.Add(string.Empty); _xmlResolver = null; _xml = nt.Add("xml"); _xmlNs = nt.Add("xmlns"); Debug.Assert(_index == 0); _nodes = new NodeData[NodesInitialSize]; _nodes[0] = new NodeData(); _curNode = _nodes[0]; _stringBuilder = new StringBuilder(); _xmlContext = new XmlContext(); _parsingFunction = ParsingFunction.SwitchToInteractiveXmlDecl; _nextParsingFunction = ParsingFunction.DocumentContent; _entityHandling = EntityHandling.ExpandCharEntities; _whitespaceHandling = WhitespaceHandling.All; _closeInput = true; _maxCharactersInDocument = 0; // Breaking change: entity expansion is enabled, but limit it to 10,000,000 chars (like XLinq) _maxCharactersFromEntities = (long)1e7; _charactersInDocument = 0; _charactersFromEntities = 0; _ps.lineNo = 1; _ps.lineStartPos = -1; } // This constructor is used when creating XmlTextReaderImpl reader via "XmlReader.Create(..)" private XmlTextReaderImpl(XmlResolver resolver, XmlReaderSettings settings, XmlParserContext context) { _useAsync = settings.Async; _v1Compat = false; _outerReader = this; _xmlContext = new XmlContext(); // create or get nametable and namespace manager from XmlParserContext XmlNameTable nt = settings.NameTable; if (context == null) { if (nt == null) { nt = new NameTable(); Debug.Assert(_nameTableFromSettings == false); } else { _nameTableFromSettings = true; } _nameTable = nt; _namespaceManager = new XmlNamespaceManager(nt); } else { SetupFromParserContext(context, settings); nt = _nameTable; } nt.Add(string.Empty); _xml = nt.Add("xml"); _xmlNs = nt.Add("xmlns"); _xmlResolver = resolver; Debug.Assert(_index == 0); _nodes = new NodeData[NodesInitialSize]; _nodes[0] = new NodeData(); _curNode = _nodes[0]; _stringBuilder = new StringBuilder(); // Needed only for XmlTextReader (reporting of entities) _entityHandling = EntityHandling.ExpandEntities; _xmlResolverIsSet = settings.IsXmlResolverSet; _whitespaceHandling = (settings.IgnoreWhitespace) ? WhitespaceHandling.Significant : WhitespaceHandling.All; _normalize = true; _ignorePIs = settings.IgnoreProcessingInstructions; _ignoreComments = settings.IgnoreComments; _checkCharacters = settings.CheckCharacters; _lineNumberOffset = settings.LineNumberOffset; _linePositionOffset = settings.LinePositionOffset; _ps.lineNo = _lineNumberOffset + 1; _ps.lineStartPos = -_linePositionOffset - 1; _curNode.SetLineInfo(_ps.LineNo - 1, _ps.LinePos - 1); _dtdProcessing = settings.DtdProcessing; _maxCharactersInDocument = settings.MaxCharactersInDocument; _maxCharactersFromEntities = settings.MaxCharactersFromEntities; _charactersInDocument = 0; _charactersFromEntities = 0; _fragmentParserContext = context; _parsingFunction = ParsingFunction.SwitchToInteractiveXmlDecl; _nextParsingFunction = ParsingFunction.DocumentContent; switch (settings.ConformanceLevel) { case ConformanceLevel.Auto: _fragmentType = XmlNodeType.None; _fragment = true; break; case ConformanceLevel.Fragment: _fragmentType = XmlNodeType.Element; _fragment = true; break; case ConformanceLevel.Document: _fragmentType = XmlNodeType.Document; break; default: Debug.Fail($"Unexpected conformance level {settings.ConformanceLevel}"); goto case ConformanceLevel.Document; } } // Initializes a new instance of the XmlTextReaderImpl class with the specified stream, baseUri and nametable // This constructor is used when creating XmlTextReaderImpl for V1 XmlTextReader internal XmlTextReaderImpl(Stream input) : this(string.Empty, input, new NameTable()) { } internal XmlTextReaderImpl(Stream input, XmlNameTable nt) : this(string.Empty, input, nt) { } internal XmlTextReaderImpl(string url, Stream input) : this(url, input, new NameTable()) { } internal XmlTextReaderImpl(string url, Stream input, XmlNameTable nt) : this(nt) { ConvertAbsoluteUnixPathToAbsoluteUri(ref url, resolver: null); _namespaceManager = new XmlNamespaceManager(nt); if (url == null || url.Length == 0) { InitStreamInput(input, null); } else { InitStreamInput(url, input, null); } _reportedBaseUri = _ps.baseUriStr; _reportedEncoding = _ps.encoding; } // Initializes a new instance of the XmlTextReaderImpl class with the specified TextReader, baseUri and XmlNameTable. // This constructor is used when creating XmlTextReaderImpl for V1 XmlTextReader internal XmlTextReaderImpl(TextReader input) : this(string.Empty, input, new NameTable()) { } internal XmlTextReaderImpl(TextReader input, XmlNameTable nt) : this(string.Empty, input, nt) { } internal XmlTextReaderImpl(string url, TextReader input) : this(url, input, new NameTable()) { } internal XmlTextReaderImpl(string url, TextReader input, XmlNameTable nt) : this(nt) { ConvertAbsoluteUnixPathToAbsoluteUri(ref url, resolver: null); _namespaceManager = new XmlNamespaceManager(nt); _reportedBaseUri = (url != null) ? url : string.Empty; InitTextReaderInput(_reportedBaseUri, input); _reportedEncoding = _ps.encoding; } // Initializes a new instance of XmlTextReaderImpl class for parsing fragments with the specified stream, fragment type and parser context // This constructor is used when creating XmlTextReaderImpl for V1 XmlTextReader // SxS: The method resolves URI but does not expose the resolved value up the stack hence Resource Exposure scope is None. internal XmlTextReaderImpl(Stream xmlFragment, XmlNodeType fragType, XmlParserContext context) : this((context != null && context.NameTable != null) ? context.NameTable : new NameTable()) { Encoding enc = (context != null) ? context.Encoding : null; if (context == null || context.BaseURI == null || context.BaseURI.Length == 0) { InitStreamInput(xmlFragment, enc); } else { // It is important to have valid resolver here to resolve the Xml url file path. // it is safe as this resolver will not be used to resolve DTD url's InitStreamInput(GetTempResolver().ResolveUri(null, context.BaseURI), xmlFragment, enc); } InitFragmentReader(fragType, context, false); _reportedBaseUri = _ps.baseUriStr; _reportedEncoding = _ps.encoding; } // Initializes a new instance of XmlTextRreaderImpl class for parsing fragments with the specified string, fragment type and parser context // This constructor is used when creating XmlTextReaderImpl for V1 XmlTextReader internal XmlTextReaderImpl(string xmlFragment, XmlNodeType fragType, XmlParserContext context) : this(null == context || null == context.NameTable ? new NameTable() : context.NameTable) { if (xmlFragment == null) { xmlFragment = string.Empty; } if (context == null) { InitStringInput(string.Empty, Encoding.Unicode, xmlFragment); } else { _reportedBaseUri = context.BaseURI; InitStringInput(context.BaseURI, Encoding.Unicode, xmlFragment); } InitFragmentReader(fragType, context, false); _reportedEncoding = _ps.encoding; } // Following constructor assumes that the fragment node type == XmlDecl // We handle this node type separately because there is not real way to determine what the // "innerXml" of an XmlDecl is. This internal function is required by DOM. When(if) we handle/allow // all nodetypes in InnerXml then we should support them as part of fragment constructor as well. // Until then, this internal function will have to do. internal XmlTextReaderImpl(string xmlFragment, XmlParserContext context) : this(null == context || null == context.NameTable ? new NameTable() : context.NameTable) { InitStringInput((context == null) ? string.Empty : context.BaseURI, Encoding.Unicode, string.Concat("<?xml ", xmlFragment, "?>")); InitFragmentReader(XmlNodeType.XmlDeclaration, context, true); } // Initializes a new instance of the XmlTextReaderImpl class with the specified url and XmlNameTable. // This constructor is used when creating XmlTextReaderImpl for V1 XmlTextReader public XmlTextReaderImpl(string url) : this(url, new NameTable()) { } public XmlTextReaderImpl(string url, XmlNameTable nt) : this(nt) { if (url == null) { throw new ArgumentNullException(nameof(url)); } if (url.Length == 0) { throw new ArgumentException(SR.Xml_EmptyUrl, nameof(url)); } _namespaceManager = new XmlNamespaceManager(nt); _url = url; // It is important to have valid resolver here to resolve the Xml url file path. // it is safe as this resolver will not be used to resolve DTD url's _ps.baseUri = GetTempResolver().ResolveUri(null, url); _ps.baseUriStr = _ps.baseUri.ToString(); _reportedBaseUri = _ps.baseUriStr; _parsingFunction = ParsingFunction.OpenUrl; } // Initializes a new instance of the XmlTextReaderImpl class with the specified arguments. // This constructor is used when creating XmlTextReaderImpl via XmlReader.Create internal XmlTextReaderImpl(string uriStr, XmlReaderSettings settings, XmlParserContext context, XmlResolver uriResolver) : this(settings.GetXmlResolver(), settings, context) { Uri baseUri = uriResolver.ResolveUri(null, uriStr); string baseUriStr = baseUri.ToString(); // get BaseUri from XmlParserContext if (context != null) { if (context.BaseURI != null && context.BaseURI.Length > 0 && !UriEqual(baseUri, baseUriStr, context.BaseURI, settings.GetXmlResolver())) { if (baseUriStr.Length > 0) { Throw(SR.Xml_DoubleBaseUri); } Debug.Assert(baseUri == null); baseUriStr = context.BaseURI; } } _reportedBaseUri = baseUriStr; _closeInput = true; _laterInitParam = new LaterInitParam(); _laterInitParam.inputUriStr = uriStr; _laterInitParam.inputbaseUri = baseUri; _laterInitParam.inputContext = context; _laterInitParam.inputUriResolver = uriResolver; _laterInitParam.initType = InitInputType.UriString; if (!settings.Async) { //if not set Async flag, finish the init in create stage. FinishInitUriString(); } else { _laterInitParam.useAsync = true; } } private void FinishInitUriString() { Stream stream = null; if (_laterInitParam.useAsync) { //this will be hit when user create a XmlReader by setting Async, but the first call is Read() instead of ReadAsync(), //then we still should create an async stream here. And wait for the method finish. Task<object> t = _laterInitParam.inputUriResolver.GetEntityAsync(_laterInitParam.inputbaseUri, string.Empty, typeof(Stream)); stream = (Stream)t.GetAwaiter().GetResult(); } else { stream = (Stream)_laterInitParam.inputUriResolver.GetEntity(_laterInitParam.inputbaseUri, string.Empty, typeof(Stream)); } if (stream == null) { throw new XmlException(SR.Xml_CannotResolveUrl, _laterInitParam.inputUriStr); } Encoding enc = null; // get Encoding from XmlParserContext if (_laterInitParam.inputContext != null) { enc = _laterInitParam.inputContext.Encoding; } try { // init ParsingState InitStreamInput(_laterInitParam.inputbaseUri, _reportedBaseUri, stream, null, 0, enc); _reportedEncoding = _ps.encoding; // parse DTD if (_laterInitParam.inputContext != null && _laterInitParam.inputContext.HasDtdInfo) { ProcessDtdFromParserContext(_laterInitParam.inputContext); } } catch { stream.Dispose(); throw; } _laterInitParam = null; } // Initializes a new instance of the XmlTextReaderImpl class with the specified arguments. // This constructor is used when creating XmlTextReaderImpl via XmlReader.Create internal XmlTextReaderImpl(Stream stream, byte[] bytes, int byteCount, XmlReaderSettings settings, Uri baseUri, string baseUriStr, XmlParserContext context, bool closeInput) : this(settings.GetXmlResolver(), settings, context) { ConvertAbsoluteUnixPathToAbsoluteUri(ref baseUriStr, settings.GetXmlResolver()); // get BaseUri from XmlParserContext if (context != null) { if (context.BaseURI != null && context.BaseURI.Length > 0 && !UriEqual(baseUri, baseUriStr, context.BaseURI, settings.GetXmlResolver())) { if (baseUriStr.Length > 0) { Throw(SR.Xml_DoubleBaseUri); } Debug.Assert(baseUri == null); baseUriStr = context.BaseURI; } } _reportedBaseUri = baseUriStr; _closeInput = closeInput; _laterInitParam = new LaterInitParam(); _laterInitParam.inputStream = stream; _laterInitParam.inputBytes = bytes; _laterInitParam.inputByteCount = byteCount; _laterInitParam.inputbaseUri = baseUri; _laterInitParam.inputContext = context; _laterInitParam.initType = InitInputType.Stream; if (!settings.Async) { //if not set Async flag, finish the init in create stage. FinishInitStream(); } else { _laterInitParam.useAsync = true; } } private void FinishInitStream() { Encoding enc = null; // get Encoding from XmlParserContext if (_laterInitParam.inputContext != null) { enc = _laterInitParam.inputContext.Encoding; } // init ParsingState InitStreamInput(_laterInitParam.inputbaseUri, _reportedBaseUri, _laterInitParam.inputStream, _laterInitParam.inputBytes, _laterInitParam.inputByteCount, enc); _reportedEncoding = _ps.encoding; // parse DTD if (_laterInitParam.inputContext != null && _laterInitParam.inputContext.HasDtdInfo) { ProcessDtdFromParserContext(_laterInitParam.inputContext); } _laterInitParam = null; } // Initializes a new instance of the XmlTextReaderImpl class with the specified arguments. // This constructor is used when creating XmlTextReaderImpl via XmlReader.Create internal XmlTextReaderImpl(TextReader input, XmlReaderSettings settings, string baseUriStr, XmlParserContext context) : this(settings.GetXmlResolver(), settings, context) { ConvertAbsoluteUnixPathToAbsoluteUri(ref baseUriStr, settings.GetXmlResolver()); // get BaseUri from XmlParserContext if (context != null) { Debug.Assert(baseUriStr == string.Empty, "BaseURI can come either from XmlParserContext or from the constructor argument, not from both"); if (context.BaseURI != null) { baseUriStr = context.BaseURI; } } _reportedBaseUri = baseUriStr; _closeInput = settings.CloseInput; _laterInitParam = new LaterInitParam(); _laterInitParam.inputTextReader = input; _laterInitParam.inputContext = context; _laterInitParam.initType = InitInputType.TextReader; if (!settings.Async) { //if not set Async flag, finish the init in create stage. FinishInitTextReader(); } else { _laterInitParam.useAsync = true; } } private void FinishInitTextReader() { // init ParsingState InitTextReaderInput(_reportedBaseUri, _laterInitParam.inputTextReader); _reportedEncoding = _ps.encoding; // parse DTD if (_laterInitParam.inputContext != null && _laterInitParam.inputContext.HasDtdInfo) { ProcessDtdFromParserContext(_laterInitParam.inputContext); } _laterInitParam = null; } // Initializes a new instance of the XmlTextReaderImpl class for fragment parsing. // This constructor is used by XmlBinaryReader for nested text XML internal XmlTextReaderImpl(string xmlFragment, XmlParserContext context, XmlReaderSettings settings) : this(null, settings, context) { Debug.Assert(xmlFragment != null); InitStringInput(string.Empty, Encoding.Unicode, xmlFragment); _reportedBaseUri = _ps.baseUriStr; _reportedEncoding = _ps.encoding; } // // XmlReader members // // Returns the current settings of the reader public override XmlReaderSettings Settings { get { XmlReaderSettings settings = new XmlReaderSettings(); if (_nameTableFromSettings) { settings.NameTable = _nameTable; } switch (_fragmentType) { case XmlNodeType.None: settings.ConformanceLevel = ConformanceLevel.Auto; break; case XmlNodeType.Element: settings.ConformanceLevel = ConformanceLevel.Fragment; break; case XmlNodeType.Document: settings.ConformanceLevel = ConformanceLevel.Document; break; default: Debug.Fail($"Unexpected fragment type {_fragmentType}"); goto case XmlNodeType.None; } settings.CheckCharacters = _checkCharacters; settings.LineNumberOffset = _lineNumberOffset; settings.LinePositionOffset = _linePositionOffset; settings.IgnoreWhitespace = (_whitespaceHandling == WhitespaceHandling.Significant); settings.IgnoreProcessingInstructions = _ignorePIs; settings.IgnoreComments = _ignoreComments; settings.DtdProcessing = _dtdProcessing; settings.MaxCharactersInDocument = _maxCharactersInDocument; settings.MaxCharactersFromEntities = _maxCharactersFromEntities; settings.XmlResolver = _xmlResolver; settings.ReadOnly = true; return settings; } } // Returns the type of the current node. public override XmlNodeType NodeType { get { return _curNode.type; } } // Returns the name of the current node, including prefix. public override string Name { get { return _curNode.GetNameWPrefix(_nameTable); } } // Returns local name of the current node (without prefix) public override string LocalName { get { return _curNode.localName; } } // Returns namespace name of the current node. public override string NamespaceURI { get { return _curNode.ns; } } // Returns prefix associated with the current node. public override string Prefix { get { return _curNode.prefix; } } // Returns the text value of the current node. public override string Value { get { if (_parsingFunction >= ParsingFunction.PartialTextValue) { if (_parsingFunction == ParsingFunction.PartialTextValue) { FinishPartialValue(); _parsingFunction = _nextParsingFunction; } else { FinishOtherValueIterator(); } } return _curNode.StringValue; } } // Returns the depth of the current node in the XML element stack public override int Depth { get { return _curNode.depth; } } // Returns the base URI of the current node. public override string BaseURI { get { return _reportedBaseUri; } } // Returns true if the current node is an empty element (for example, <MyElement/>). public override bool IsEmptyElement { get { return _curNode.IsEmptyElement; } } // Returns true of the current node is a default attribute declared in DTD. public override bool IsDefault { get { return _curNode.IsDefaultAttribute; } } // Returns the quote character used in the current attribute declaration public override char QuoteChar { get { return _curNode.type == XmlNodeType.Attribute ? _curNode.quoteChar : '"'; } } // Returns the current xml:space scope. public override XmlSpace XmlSpace { get { return _xmlContext.xmlSpace; } } // Returns the current xml:lang scope.</para> public override string XmlLang { get { return _xmlContext.xmlLang; } } // Returns the current read state of the reader public override ReadState ReadState { get { return _readState; } } // Returns true if the reader reached end of the input data public override bool EOF { get { return _parsingFunction == ParsingFunction.Eof; } } // Returns the XmlNameTable associated with this XmlReader public override XmlNameTable NameTable { get { return _nameTable; } } // Returns true if the XmlReader knows how to resolve general entities public override bool CanResolveEntity { get { return true; } } // Returns the number of attributes on the current node. public override int AttributeCount { get { return _attrCount; } } // Returns value of an attribute with the specified Name public override string GetAttribute(string name) { int i; if (!name.Contains(':')) { i = GetIndexOfAttributeWithoutPrefix(name); } else { i = GetIndexOfAttributeWithPrefix(name); } return (i >= 0) ? _nodes[i].StringValue : null; } // Returns value of an attribute with the specified LocalName and NamespaceURI public override string GetAttribute(string localName, string namespaceURI) { namespaceURI = (namespaceURI == null) ? string.Empty : _nameTable.Get(namespaceURI); localName = _nameTable.Get(localName); for (int i = _index + 1; i < _index + _attrCount + 1; i++) { if (Ref.Equal(_nodes[i].localName, localName) && Ref.Equal(_nodes[i].ns, namespaceURI)) { return _nodes[i].StringValue; } } return null; } // Returns value of an attribute at the specified index (position) public override string GetAttribute(int i) { if (i < 0 || i >= _attrCount) { throw new ArgumentOutOfRangeException(nameof(i)); } return _nodes[_index + i + 1].StringValue; } // Moves to an attribute with the specified Name public override bool MoveToAttribute(string name) { int i; if (!name.Contains(':')) { i = GetIndexOfAttributeWithoutPrefix(name); } else { i = GetIndexOfAttributeWithPrefix(name); } if (i >= 0) { if (InAttributeValueIterator) { FinishAttributeValueIterator(); } _curAttrIndex = i - _index - 1; _curNode = _nodes[i]; return true; } else { return false; } } // Moves to an attribute with the specified LocalName and NamespceURI public override bool MoveToAttribute(string localName, string namespaceURI) { namespaceURI = (namespaceURI == null) ? string.Empty : _nameTable.Get(namespaceURI); localName = _nameTable.Get(localName); for (int i = _index + 1; i < _index + _attrCount + 1; i++) { if (Ref.Equal(_nodes[i].localName, localName) && Ref.Equal(_nodes[i].ns, namespaceURI)) { _curAttrIndex = i - _index - 1; _curNode = _nodes[i]; if (InAttributeValueIterator) { FinishAttributeValueIterator(); } return true; } } return false; } // Moves to an attribute at the specified index (position) public override void MoveToAttribute(int i) { if (i < 0 || i >= _attrCount) { throw new ArgumentOutOfRangeException(nameof(i)); } if (InAttributeValueIterator) { FinishAttributeValueIterator(); } _curAttrIndex = i; _curNode = _nodes[_index + 1 + _curAttrIndex]; } // Moves to the first attribute of the current node public override bool MoveToFirstAttribute() { if (_attrCount == 0) { return false; } if (InAttributeValueIterator) { FinishAttributeValueIterator(); } _curAttrIndex = 0; _curNode = _nodes[_index + 1]; return true; } // Moves to the next attribute of the current node public override bool MoveToNextAttribute() { if (_curAttrIndex + 1 < _attrCount) { if (InAttributeValueIterator) { FinishAttributeValueIterator(); } _curNode = _nodes[_index + 1 + ++_curAttrIndex]; return true; } return false; } // If on attribute, moves to the element that contains the attribute node public override bool MoveToElement() { if (InAttributeValueIterator) { FinishAttributeValueIterator(); } else if (_curNode.type != XmlNodeType.Attribute) { return false; } _curAttrIndex = -1; _curNode = _nodes[_index]; return true; } private void FinishInit() { switch (_laterInitParam.initType) { case InitInputType.UriString: FinishInitUriString(); break; case InitInputType.Stream: FinishInitStream(); break; case InitInputType.TextReader: FinishInitTextReader(); break; default: //should never hit here Debug.Fail("Invalid InitInputType"); break; } } // Reads next node from the input data public override bool Read() { if (_laterInitParam != null) { FinishInit(); } while (true) { switch (_parsingFunction) { case ParsingFunction.ElementContent: return ParseElementContent(); case ParsingFunction.DocumentContent: return ParseDocumentContent(); case ParsingFunction.OpenUrl: OpenUrl(); Debug.Assert(_nextParsingFunction == ParsingFunction.DocumentContent); goto case ParsingFunction.SwitchToInteractiveXmlDecl; case ParsingFunction.SwitchToInteractive: Debug.Assert(!_ps.appendMode); _readState = ReadState.Interactive; _parsingFunction = _nextParsingFunction; continue; case ParsingFunction.SwitchToInteractiveXmlDecl: _readState = ReadState.Interactive; _parsingFunction = _nextParsingFunction; if (ParseXmlDeclaration(false)) { _reportedEncoding = _ps.encoding; return true; } _reportedEncoding = _ps.encoding; continue; case ParsingFunction.ResetAttributesRootLevel: ResetAttributes(); _curNode = _nodes[_index]; _parsingFunction = (_index == 0) ? ParsingFunction.DocumentContent : ParsingFunction.ElementContent; continue; case ParsingFunction.MoveToElementContent: ResetAttributes(); _index++; _curNode = AddNode(_index, _index); _parsingFunction = ParsingFunction.ElementContent; continue; case ParsingFunction.PopElementContext: PopElementContext(); _parsingFunction = _nextParsingFunction; Debug.Assert(_parsingFunction == ParsingFunction.ElementContent || _parsingFunction == ParsingFunction.DocumentContent); continue; case ParsingFunction.PopEmptyElementContext: _curNode = _nodes[_index]; Debug.Assert(_curNode.type == XmlNodeType.Element); _curNode.IsEmptyElement = false; ResetAttributes(); PopElementContext(); _parsingFunction = _nextParsingFunction; continue; case ParsingFunction.EntityReference: _parsingFunction = _nextParsingFunction; ParseEntityReference(); return true; case ParsingFunction.ReportEndEntity: SetupEndEntityNodeInContent(); _parsingFunction = _nextParsingFunction; return true; case ParsingFunction.AfterResolveEntityInContent: _curNode = AddNode(_index, _index); _reportedEncoding = _ps.encoding; _reportedBaseUri = _ps.baseUriStr; _parsingFunction = _nextParsingFunction; continue; case ParsingFunction.AfterResolveEmptyEntityInContent: _curNode = AddNode(_index, _index); _curNode.SetValueNode(XmlNodeType.Text, string.Empty); _curNode.SetLineInfo(_ps.lineNo, _ps.LinePos); _reportedEncoding = _ps.encoding; _reportedBaseUri = _ps.baseUriStr; _parsingFunction = _nextParsingFunction; return true; case ParsingFunction.InReadAttributeValue: FinishAttributeValueIterator(); _curNode = _nodes[_index]; continue; case ParsingFunction.InIncrementalRead: FinishIncrementalRead(); return true; case ParsingFunction.FragmentAttribute: return ParseFragmentAttribute(); case ParsingFunction.XmlDeclarationFragment: ParseXmlDeclarationFragment(); _parsingFunction = ParsingFunction.GoToEof; return true; case ParsingFunction.GoToEof: OnEof(); return false; case ParsingFunction.Error: case ParsingFunction.Eof: case ParsingFunction.ReaderClosed: return false; case ParsingFunction.NoData: ThrowWithoutLineInfo(SR.Xml_MissingRoot); return false; case ParsingFunction.PartialTextValue: SkipPartialTextValue(); continue; case ParsingFunction.InReadValueChunk: FinishReadValueChunk(); continue; case ParsingFunction.InReadContentAsBinary: FinishReadContentAsBinary(); continue; case ParsingFunction.InReadElementContentAsBinary: FinishReadElementContentAsBinary(); continue; default: Debug.Fail($"Unexpected parsing function {_parsingFunction}"); break; } } } // Closes the input stream ot TextReader, changes the ReadState to Closed and sets all properties to zero/string.Empty public override void Close() { Close(_closeInput); } // Skips the current node. If on element, skips to the end tag of the element. public override void Skip() { if (_readState != ReadState.Interactive) return; if (InAttributeValueIterator) { FinishAttributeValueIterator(); _curNode = _nodes[_index]; } else { switch (_parsingFunction) { case ParsingFunction.InReadAttributeValue: Debug.Fail($"Unexpected parsing function {_parsingFunction}"); break; case ParsingFunction.InIncrementalRead: FinishIncrementalRead(); break; case ParsingFunction.PartialTextValue: SkipPartialTextValue(); break; case ParsingFunction.InReadValueChunk: FinishReadValueChunk(); break; case ParsingFunction.InReadContentAsBinary: FinishReadContentAsBinary(); break; case ParsingFunction.InReadElementContentAsBinary: FinishReadElementContentAsBinary(); break; } } switch (_curNode.type) { // skip subtree case XmlNodeType.Element: if (_curNode.IsEmptyElement) { break; } int initialDepth = _index; _parsingMode = ParsingMode.SkipContent; // skip content while (_outerReader.Read() && _index > initialDepth) ; Debug.Assert(_curNode.type == XmlNodeType.EndElement); Debug.Assert(_parsingFunction != ParsingFunction.Eof); _parsingMode = ParsingMode.Full; break; case XmlNodeType.Attribute: _outerReader.MoveToElement(); goto case XmlNodeType.Element; } // move to following sibling node _outerReader.Read(); return; } // Returns NamespaceURI associated with the specified prefix in the current namespace scope. public override string LookupNamespace(string prefix) { if (!_supportNamespaces) { return null; } return _namespaceManager.LookupNamespace(prefix); } // Iterates through the current attribute value's text and entity references chunks. public override bool ReadAttributeValue() { if (_parsingFunction != ParsingFunction.InReadAttributeValue) { if (_curNode.type != XmlNodeType.Attribute) { return false; } if (_readState != ReadState.Interactive || _curAttrIndex < 0) { return false; } if (_parsingFunction == ParsingFunction.InReadValueChunk) { FinishReadValueChunk(); } if (_parsingFunction == ParsingFunction.InReadContentAsBinary) { FinishReadContentAsBinary(); } if (_curNode.nextAttrValueChunk == null || _entityHandling == EntityHandling.ExpandEntities) { NodeData simpleValueNode = AddNode(_index + _attrCount + 1, _curNode.depth + 1); simpleValueNode.SetValueNode(XmlNodeType.Text, _curNode.StringValue); simpleValueNode.lineInfo = _curNode.lineInfo2; simpleValueNode.depth = _curNode.depth + 1; _curNode = simpleValueNode; simpleValueNode.nextAttrValueChunk = null; } else { _curNode = _curNode.nextAttrValueChunk; // Place the current node at nodes[index + attrCount + 1]. If the node type // is be EntityReference and user calls ResolveEntity, the associated EndEntity // node will be constructed from the information stored there. // This will initialize the (index + attrCount + 1) place in nodes array AddNode(_index + _attrCount + 1, _index + 2); _nodes[_index + _attrCount + 1] = _curNode; _fullAttrCleanup = true; } _nextParsingFunction = _parsingFunction; _parsingFunction = ParsingFunction.InReadAttributeValue; _attributeValueBaseEntityId = _ps.entityId; return true; } else { if (_ps.entityId == _attributeValueBaseEntityId) { if (_curNode.nextAttrValueChunk != null) { _curNode = _curNode.nextAttrValueChunk; _nodes[_index + _attrCount + 1] = _curNode; // if curNode == EntityReference node, it will be picked from here by SetupEndEntityNodeInAttribute return true; } return false; } else { // expanded entity in attribute value return ParseAttributeValueChunk(); } } } // Resolves the current entity reference node public override void ResolveEntity() { if (_curNode.type != XmlNodeType.EntityReference) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } Debug.Assert(_parsingMode == ParsingMode.Full); // entity in attribute value if (_parsingFunction == ParsingFunction.InReadAttributeValue || _parsingFunction == ParsingFunction.FragmentAttribute) { switch (HandleGeneralEntityReference(_curNode.localName, true, true, _curNode.LinePos)) { case EntityType.ExpandedInAttribute: case EntityType.Expanded: if (_ps.charsUsed - _ps.charPos == 0) { // entity value == "" _emptyEntityInAttributeResolved = true; } break; case EntityType.FakeExpanded: _emptyEntityInAttributeResolved = true; break; default: Debug.Fail("Unexpected entity type"); throw new XmlException(SR.Xml_InternalError, string.Empty); } } // entity in element content else { switch (HandleGeneralEntityReference(_curNode.localName, false, true, _curNode.LinePos)) { case EntityType.ExpandedInAttribute: case EntityType.Expanded: _nextParsingFunction = _parsingFunction; if (_ps.charsUsed - _ps.charPos == 0 && !_ps.entity.IsExternal) { // empty internal entity value _parsingFunction = ParsingFunction.AfterResolveEmptyEntityInContent; } else { _parsingFunction = ParsingFunction.AfterResolveEntityInContent; } break; case EntityType.FakeExpanded: _nextParsingFunction = _parsingFunction; _parsingFunction = ParsingFunction.AfterResolveEmptyEntityInContent; break; default: Debug.Fail("Unexpected entity type"); throw new XmlException(SR.Xml_InternalError, string.Empty); } } _ps.entityResolvedManually = true; _index++; } internal XmlReader OuterReader { get { return _outerReader; } set { Debug.Assert(value is XmlTextReader); _outerReader = value; } } internal void MoveOffEntityReference() { if (_outerReader.NodeType == XmlNodeType.EntityReference && _parsingFunction == ParsingFunction.AfterResolveEntityInContent) { if (!_outerReader.Read()) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } } } public override string ReadString() { Debug.Assert(_outerReader is XmlTextReaderImpl); MoveOffEntityReference(); return base.ReadString(); } public override bool CanReadBinaryContent { get { return true; } } // Reads and concatenates content nodes, base64-decodes the results and copies the decoded bytes into the provided buffer public override int ReadContentAsBase64(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException(nameof(count)); } // if not the first call to ReadContentAsBase64 if (_parsingFunction == ParsingFunction.InReadContentAsBinary) { // and if we have a correct decoder if (_incReadDecoder == _base64Decoder) { // read more binary data return ReadContentAsBinary(buffer, index, count); } } // first call of ReadContentAsBase64 -> initialize (move to first text child (for elements) and initialize incremental read state) else { if (_readState != ReadState.Interactive) { return 0; } if (_parsingFunction == ParsingFunction.InReadElementContentAsBinary) { throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); } if (!XmlReader.CanReadContentAs(_curNode.type)) { throw CreateReadContentAsException(nameof(ReadContentAsBase64)); } if (!InitReadContentAsBinary()) { return 0; } } // setup base64 decoder InitBase64Decoder(); // read binary data return ReadContentAsBinary(buffer, index, count); } // Reads and concatenates content nodes, binhex-decodes the results and copies the decoded bytes into the provided buffer public override int ReadContentAsBinHex(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException(nameof(count)); } // if not the first call to ReadContentAsBinHex if (_parsingFunction == ParsingFunction.InReadContentAsBinary) { // and if we have a correct decoder if (_incReadDecoder == _binHexDecoder) { // read more binary data return ReadContentAsBinary(buffer, index, count); } } // first call of ReadContentAsBinHex -> initialize (move to first text child (for elements) and initialize incremental read state) else { if (_readState != ReadState.Interactive) { return 0; } if (_parsingFunction == ParsingFunction.InReadElementContentAsBinary) { throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); } if (!XmlReader.CanReadContentAs(_curNode.type)) { throw CreateReadContentAsException(nameof(ReadContentAsBinHex)); } if (!InitReadContentAsBinary()) { return 0; } } // setup binhex decoder (when in first ReadContentAsBinHex call or when mixed with ReadContentAsBase64) InitBinHexDecoder(); // read binary data return ReadContentAsBinary(buffer, index, count); } // Reads and concatenates content of an element, base64-decodes the results and copies the decoded bytes into the provided buffer public override int ReadElementContentAsBase64(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException(nameof(count)); } // if not the first call to ReadContentAsBase64 if (_parsingFunction == ParsingFunction.InReadElementContentAsBinary) { // and if we have a correct decoder if (_incReadDecoder == _base64Decoder) { // read more binary data return ReadElementContentAsBinary(buffer, index, count); } } // first call of ReadElementContentAsBase64 -> initialize else { if (_readState != ReadState.Interactive) { return 0; } if (_parsingFunction == ParsingFunction.InReadContentAsBinary) { throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); } if (_curNode.type != XmlNodeType.Element) { throw CreateReadElementContentAsException(nameof(ReadElementContentAsBinHex)); } if (!InitReadElementContentAsBinary()) { return 0; } } // setup base64 decoder InitBase64Decoder(); // read binary data return ReadElementContentAsBinary(buffer, index, count); } // Reads and concatenates content of an element, binhex-decodes the results and copies the decoded bytes into the provided buffer public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException(nameof(count)); } // if not the first call to ReadContentAsBinHex if (_parsingFunction == ParsingFunction.InReadElementContentAsBinary) { // and if we have a correct decoder if (_incReadDecoder == _binHexDecoder) { // read more binary data return ReadElementContentAsBinary(buffer, index, count); } } // first call of ReadContentAsBinHex -> initialize else { if (_readState != ReadState.Interactive) { return 0; } if (_parsingFunction == ParsingFunction.InReadContentAsBinary) { throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); } if (_curNode.type != XmlNodeType.Element) { throw CreateReadElementContentAsException(nameof(ReadElementContentAsBinHex)); } if (!InitReadElementContentAsBinary()) { return 0; } } // setup binhex decoder (when in first ReadContentAsBinHex call or when mixed with ReadContentAsBase64) InitBinHexDecoder(); // read binary data return ReadElementContentAsBinary(buffer, index, count); } // Returns true if ReadValue is supported public override bool CanReadValueChunk { get { return true; } } // Iterates over Value property and copies it into the provided buffer public override int ReadValueChunk(char[] buffer, int index, int count) { // throw on elements if (!XmlReader.HasValueInternal(_curNode.type)) { throw new InvalidOperationException(SR.Format(SR.Xml_InvalidReadValueChunk, _curNode.type)); } // check arguments if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException(nameof(count)); } // first call of ReadValueChunk -> initialize incremental read state if (_parsingFunction != ParsingFunction.InReadValueChunk) { if (_readState != ReadState.Interactive) { return 0; } if (_parsingFunction == ParsingFunction.PartialTextValue) { _incReadState = IncrementalReadState.ReadValueChunk_OnPartialValue; } else { _incReadState = IncrementalReadState.ReadValueChunk_OnCachedValue; _nextNextParsingFunction = _nextParsingFunction; _nextParsingFunction = _parsingFunction; } _parsingFunction = ParsingFunction.InReadValueChunk; _readValueOffset = 0; } if (count == 0) { return 0; } // read what is already cached in curNode int readCount = 0; int read = _curNode.CopyTo(_readValueOffset, buffer, index + readCount, count - readCount); readCount += read; _readValueOffset += read; if (readCount == count) { // take care of surrogate pairs spanning between buffers char ch = buffer[index + count - 1]; if (XmlCharType.IsHighSurrogate(ch)) { readCount--; _readValueOffset--; if (readCount == 0) { Throw(SR.Xml_NotEnoughSpaceForSurrogatePair); } } return readCount; } // if on partial value, read the rest of it if (_incReadState == IncrementalReadState.ReadValueChunk_OnPartialValue) { _curNode.SetValue(string.Empty); // read next chunk of text bool endOfValue = false; int startPos = 0; int endPos = 0; while (readCount < count && !endOfValue) { int orChars = 0; endOfValue = ParseText(out startPos, out endPos, ref orChars); int copyCount = count - readCount; if (copyCount > endPos - startPos) { copyCount = endPos - startPos; } BlockCopyChars(_ps.chars, startPos, buffer, (index + readCount), copyCount); readCount += copyCount; startPos += copyCount; } _incReadState = endOfValue ? IncrementalReadState.ReadValueChunk_OnCachedValue : IncrementalReadState.ReadValueChunk_OnPartialValue; if (readCount == count) { char ch = buffer[index + count - 1]; if (XmlCharType.IsHighSurrogate(ch)) { readCount--; startPos--; if (readCount == 0) { Throw(SR.Xml_NotEnoughSpaceForSurrogatePair); } } } _readValueOffset = 0; _curNode.SetValue(_ps.chars, startPos, endPos - startPos); } return readCount; } // // IXmlLineInfo members // public bool HasLineInfo() { return true; } // Returns the line number of the current node public int LineNumber { get { return _curNode.LineNo; } } // Returns the line position of the current node public int LinePosition { get { return _curNode.LinePos; } } // // IXmlNamespaceResolver members // IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope) { return this.GetNamespacesInScope(scope); } string IXmlNamespaceResolver.LookupNamespace(string prefix) { return this.LookupNamespace(prefix); } string IXmlNamespaceResolver.LookupPrefix(string namespaceName) { return this.LookupPrefix(namespaceName); } // Internal IXmlNamespaceResolver methods internal IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope) { return _namespaceManager.GetNamespacesInScope(scope); } // NOTE: there already is virtual method for "string LookupNamespace(string prefix)" internal string LookupPrefix(string namespaceName) { return _namespaceManager.LookupPrefix(namespaceName); } // // XmlTextReader members // // Disables or enables support of W3C XML 1.0 Namespaces internal bool Namespaces { get { return _supportNamespaces; } set { if (_readState != ReadState.Initial) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } _supportNamespaces = value; if (value) { if (_namespaceManager is NoNamespaceManager) { if (_fragment && _fragmentParserContext != null && _fragmentParserContext.NamespaceManager != null) { _namespaceManager = _fragmentParserContext.NamespaceManager; } else { _namespaceManager = new XmlNamespaceManager(_nameTable); } } _xmlContext.defaultNamespace = _namespaceManager.LookupNamespace(string.Empty); } else { if (!(_namespaceManager is NoNamespaceManager)) { _namespaceManager = new NoNamespaceManager(); } _xmlContext.defaultNamespace = string.Empty; } } } // Enables or disables XML 1.0 normalization (incl. end-of-line normalization and normalization of attributes) internal bool Normalization { get { Debug.Assert(_v1Compat, "XmlTextReaderImpl.Normalization property cannot be accessed on reader created via XmlReader.Create."); return _normalize; } set { Debug.Assert(_v1Compat, "XmlTextReaderImpl.Normalization property cannot be changed on reader created via XmlReader.Create."); if (_readState == ReadState.Closed) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } _normalize = value; if (_ps.entity == null || _ps.entity.IsExternal) { _ps.eolNormalized = !value; } } } // Returns the Encoding of the XML document internal Encoding Encoding { get { return (_readState == ReadState.Interactive) ? _reportedEncoding : null; } } // Spefifies whitespace handling of the XML document, i.e. whether return all namespaces, only significant ones or none internal WhitespaceHandling WhitespaceHandling { get { Debug.Assert(_v1Compat, "XmlTextReaderImpl.WhitespaceHandling property cannot be accessed on reader created via XmlReader.Create."); return _whitespaceHandling; } set { Debug.Assert(_v1Compat, "XmlTextReaderImpl.WhitespaceHandling property cannot be changed on reader created via XmlReader.Create."); if (_readState == ReadState.Closed) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } if ((uint)value > (uint)WhitespaceHandling.None) { throw new XmlException(SR.Xml_WhitespaceHandling, string.Empty); } _whitespaceHandling = value; } } // Specifies how the DTD is processed in the XML document. internal DtdProcessing DtdProcessing { get { Debug.Assert(_v1Compat, "XmlTextReaderImpl.DtdProcessing property cannot be accessed on reader created via XmlReader.Create."); return _dtdProcessing; } set { Debug.Assert(_v1Compat, "XmlTextReaderImpl.DtdProcessing property cannot be changed on reader created via XmlReader.Create."); if ((uint)value > (uint)DtdProcessing.Parse) { throw new ArgumentOutOfRangeException(nameof(value)); } _dtdProcessing = value; } } // Spefifies whether general entities should be automatically expanded or not internal EntityHandling EntityHandling { get { return _entityHandling; } set { if (value != EntityHandling.ExpandEntities && value != EntityHandling.ExpandCharEntities) { throw new XmlException(SR.Xml_EntityHandling, string.Empty); } _entityHandling = value; } } // Needed to check from the schema validation if the caller set the resolver so we'll not override it internal bool IsResolverSet { get { return _xmlResolverIsSet; } } // Specifies XmlResolver used for opening the XML document and other external references internal XmlResolver XmlResolver { set { _xmlResolver = value; _xmlResolverIsSet = true; // invalidate all baseUris on the stack _ps.baseUri = null; for (int i = 0; i <= _parsingStatesStackTop; i++) { _parsingStatesStack[i].baseUri = null; } } } // Reset the state of the reader so the reader is ready to parse another XML document from the same stream. internal void ResetState() { Debug.Assert(_v1Compat, "XmlTextReaderImpl.ResetState cannot be called on reader created via XmlReader.Create."); if (_fragment) { Throw(new InvalidOperationException(SR.Xml_InvalidResetStateCall)); } if (_readState == ReadState.Initial) { return; } // Clear ResetAttributes(); while (_namespaceManager.PopScope()) ; while (InEntity) { HandleEntityEnd(true); } // Init _readState = ReadState.Initial; _parsingFunction = ParsingFunction.SwitchToInteractiveXmlDecl; _nextParsingFunction = ParsingFunction.DocumentContent; _curNode = _nodes[0]; _curNode.Clear(XmlNodeType.None); _curNode.SetLineInfo(0, 0); _index = 0; _rootElementParsed = false; _charactersInDocument = 0; _charactersFromEntities = 0; _afterResetState = true; } // returns the remaining unparsed data as TextReader internal TextReader GetRemainder() { Debug.Assert(_v1Compat, "XmlTextReaderImpl.GetRemainder cannot be called on reader created via XmlReader.Create."); Debug.Assert(_stringBuilder.Length == 0); switch (_parsingFunction) { case ParsingFunction.Eof: case ParsingFunction.ReaderClosed: return new StringReader(string.Empty); case ParsingFunction.OpenUrl: OpenUrl(); break; case ParsingFunction.InIncrementalRead: if (!InEntity) { _stringBuilder.Append(_ps.chars, _incReadLeftStartPos, _incReadLeftEndPos - _incReadLeftStartPos); } break; } while (InEntity) { HandleEntityEnd(true); } _ps.appendMode = false; do { _stringBuilder.Append(_ps.chars, _ps.charPos, _ps.charsUsed - _ps.charPos); _ps.charPos = _ps.charsUsed; } while (ReadData() != 0); OnEof(); string remainer = _stringBuilder.ToString(); _stringBuilder.Length = 0; return new StringReader(remainer); } // Reads the contents of an element including markup into a character buffer. Wellformedness checks are limited. // This method is designed to read large streams of embedded text by calling it successively. internal int ReadChars(char[] buffer, int index, int count) { Debug.Assert(_v1Compat, "XmlTextReaderImpl.ReadChars cannot be called on reader created via XmlReader.Create."); Debug.Assert(_outerReader is XmlTextReader); if (_parsingFunction == ParsingFunction.InIncrementalRead) { if (_incReadDecoder != _readCharsDecoder) { // mixing ReadChars with ReadBase64 or ReadBinHex if (_readCharsDecoder == null) { _readCharsDecoder = new IncrementalReadCharsDecoder(); } _readCharsDecoder.Reset(); _incReadDecoder = _readCharsDecoder; } return IncrementalRead(buffer, index, count); } else { if (_curNode.type != XmlNodeType.Element) { return 0; } if (_curNode.IsEmptyElement) { _outerReader.Read(); return 0; } if (_readCharsDecoder == null) { _readCharsDecoder = new IncrementalReadCharsDecoder(); } InitIncrementalRead(_readCharsDecoder); return IncrementalRead(buffer, index, count); } } // Reads the contents of an element including markup and base64-decodes it into a byte buffer. Wellformedness checks are limited. // This method is designed to read base64-encoded large streams of bytes by calling it successively. internal int ReadBase64(byte[] array, int offset, int len) { Debug.Assert(_v1Compat, "XmlTextReaderImpl.ReadBase64 cannot be called on reader created via XmlReader.Create."); Debug.Assert(_outerReader is XmlTextReader); if (_parsingFunction == ParsingFunction.InIncrementalRead) { if (_incReadDecoder != _base64Decoder) { // mixing ReadBase64 with ReadChars or ReadBinHex InitBase64Decoder(); } return IncrementalRead(array, offset, len); } else { if (_curNode.type != XmlNodeType.Element) { return 0; } if (_curNode.IsEmptyElement) { _outerReader.Read(); return 0; } if (_base64Decoder == null) { _base64Decoder = new Base64Decoder(); } InitIncrementalRead(_base64Decoder); return IncrementalRead(array, offset, len); } } // Reads the contents of an element including markup and binhex-decodes it into a byte buffer. Wellformedness checks are limited. // This method is designed to read binhex-encoded large streams of bytes by calling it successively. internal int ReadBinHex(byte[] array, int offset, int len) { Debug.Assert(_v1Compat, "XmlTextReaderImpl.ReadBinHex cannot be called on reader created via XmlReader.Create."); Debug.Assert(_outerReader is XmlTextReader); if (_parsingFunction == ParsingFunction.InIncrementalRead) { if (_incReadDecoder != _binHexDecoder) { // mixing ReadBinHex with ReadChars or ReadBase64 InitBinHexDecoder(); } return IncrementalRead(array, offset, len); } else { if (_curNode.type != XmlNodeType.Element) { return 0; } if (_curNode.IsEmptyElement) { _outerReader.Read(); return 0; } if (_binHexDecoder == null) { _binHexDecoder = new BinHexDecoder(); } InitIncrementalRead(_binHexDecoder); return IncrementalRead(array, offset, len); } } // // Helpers for DtdParserProxy // internal XmlNameTable DtdParserProxy_NameTable { get { return _nameTable; } } internal IXmlNamespaceResolver DtdParserProxy_NamespaceResolver { get { return _namespaceManager; } } internal bool DtdParserProxy_DtdValidation { get { return DtdValidation; } } internal bool DtdParserProxy_Normalization { get { return _normalize; } } internal bool DtdParserProxy_Namespaces { get { return _supportNamespaces; } } internal bool DtdParserProxy_V1CompatibilityMode { get { return _v1Compat; } } internal Uri DtdParserProxy_BaseUri { // SxS: ps.baseUri may be initialized in the constructor (public XmlTextReaderImpl( string url, XmlNameTable nt )) based on // url provided by the user. Here the property returns ps.BaseUri - so it may expose a path. get { if (_ps.baseUriStr.Length > 0 && _ps.baseUri == null && _xmlResolver != null) { _ps.baseUri = _xmlResolver.ResolveUri(null, _ps.baseUriStr); } return _ps.baseUri; } } internal bool DtdParserProxy_IsEof { get { return _ps.isEof; } } internal char[] DtdParserProxy_ParsingBuffer { get { return _ps.chars; } } internal int DtdParserProxy_ParsingBufferLength { get { return _ps.charsUsed; } } internal int DtdParserProxy_CurrentPosition { get { return _ps.charPos; } set { Debug.Assert(value >= 0 && value <= _ps.charsUsed); _ps.charPos = value; } } internal int DtdParserProxy_EntityStackLength { get { return _parsingStatesStackTop + 1; } } internal bool DtdParserProxy_IsEntityEolNormalized { get { return _ps.eolNormalized; } } internal IValidationEventHandling DtdParserProxy_ValidationEventHandling { get { return _validationEventHandling; } set { _validationEventHandling = value; } } internal void DtdParserProxy_OnNewLine(int pos) { this.OnNewLine(pos); } internal int DtdParserProxy_LineNo { get { return _ps.LineNo; } } internal int DtdParserProxy_LineStartPosition { get { return _ps.lineStartPos; } } internal int DtdParserProxy_ReadData() { return this.ReadData(); } internal int DtdParserProxy_ParseNumericCharRef(StringBuilder internalSubsetBuilder) { EntityType entType; return this.ParseNumericCharRef(true, internalSubsetBuilder, out entType); } internal int DtdParserProxy_ParseNamedCharRef(bool expand, StringBuilder internalSubsetBuilder) { return this.ParseNamedCharRef(expand, internalSubsetBuilder); } internal void DtdParserProxy_ParsePI(StringBuilder sb) { if (sb == null) { ParsingMode pm = _parsingMode; _parsingMode = ParsingMode.SkipNode; ParsePI(null); _parsingMode = pm; } else { ParsePI(sb); } } internal void DtdParserProxy_ParseComment(StringBuilder sb) { Debug.Assert(_parsingMode == ParsingMode.Full); try { if (sb == null) { ParsingMode savedParsingMode = _parsingMode; _parsingMode = ParsingMode.SkipNode; ParseCDataOrComment(XmlNodeType.Comment); _parsingMode = savedParsingMode; } else { NodeData originalCurNode = _curNode; _curNode = AddNode(_index + _attrCount + 1, _index); ParseCDataOrComment(XmlNodeType.Comment); _curNode.CopyTo(0, sb); _curNode = originalCurNode; } } catch (XmlException e) { if (e.ResString == SR.Xml_UnexpectedEOF && _ps.entity != null) { SendValidationEvent(XmlSeverityType.Error, SR.Sch_ParEntityRefNesting, null, _ps.LineNo, _ps.LinePos); } else { throw; } } } private bool IsResolverNull { get { return _xmlResolver == null || !_xmlResolverIsSet; } } private XmlResolver GetTempResolver() { return _xmlResolver == null ? new XmlUrlResolver() : _xmlResolver; } internal bool DtdParserProxy_PushEntity(IDtdEntityInfo entity, out int entityId) { bool retValue; if (entity.IsExternal) { if (IsResolverNull) { entityId = -1; return false; } retValue = PushExternalEntity(entity); } else { PushInternalEntity(entity); retValue = true; } entityId = _ps.entityId; return retValue; } internal bool DtdParserProxy_PopEntity(out IDtdEntityInfo oldEntity, out int newEntityId) { if (_parsingStatesStackTop == -1) { oldEntity = null; newEntityId = -1; return false; } oldEntity = _ps.entity; PopEntity(); newEntityId = _ps.entityId; return true; } // SxS: The caller did not provide any SxS sensitive name or resource. No resource is being exposed either. // It is OK to suppress SxS warning. internal bool DtdParserProxy_PushExternalSubset(string systemId, string publicId) { Debug.Assert(_parsingStatesStackTop == -1); Debug.Assert((systemId != null && systemId.Length > 0) || (publicId != null && publicId.Length > 0)); if (IsResolverNull) { return false; } if (_ps.baseUri == null && !string.IsNullOrEmpty(_ps.baseUriStr)) { _ps.baseUri = _xmlResolver.ResolveUri(null, _ps.baseUriStr); } PushExternalEntityOrSubset(publicId, systemId, _ps.baseUri, null); _ps.entity = null; _ps.entityId = 0; Debug.Assert(_ps.appendMode); int initialPos = _ps.charPos; if (_v1Compat) { EatWhitespaces(null); } if (!ParseXmlDeclaration(true)) { _ps.charPos = initialPos; } return true; } internal void DtdParserProxy_PushInternalDtd(string baseUri, string internalDtd) { Debug.Assert(_parsingStatesStackTop == -1); Debug.Assert(internalDtd != null); PushParsingState(); RegisterConsumedCharacters(internalDtd.Length, false); InitStringInput(baseUri, Encoding.Unicode, internalDtd); _ps.entity = null; _ps.entityId = 0; _ps.eolNormalized = false; } internal void DtdParserProxy_Throw(Exception e) { this.Throw(e); } internal void DtdParserProxy_OnSystemId(string systemId, LineInfo keywordLineInfo, LineInfo systemLiteralLineInfo) { NodeData attr = AddAttributeNoChecks("SYSTEM", _index + 1); attr.SetValue(systemId); attr.lineInfo = keywordLineInfo; attr.lineInfo2 = systemLiteralLineInfo; } internal void DtdParserProxy_OnPublicId(string publicId, LineInfo keywordLineInfo, LineInfo publicLiteralLineInfo) { NodeData attr = AddAttributeNoChecks("PUBLIC", _index + 1); attr.SetValue(publicId); attr.lineInfo = keywordLineInfo; attr.lineInfo2 = publicLiteralLineInfo; } // // Throw methods: Sets the reader current position to pos, sets the error state and throws exception // private void Throw(int pos, string res, string arg) { _ps.charPos = pos; Throw(res, arg); } private void Throw(int pos, string res, string[] args) { _ps.charPos = pos; Throw(res, args); } private void Throw(int pos, string res) { _ps.charPos = pos; Throw(res, string.Empty); } private void Throw(string res) { Throw(res, string.Empty); } private void Throw(string res, int lineNo, int linePos) { Throw(new XmlException(res, string.Empty, lineNo, linePos, _ps.baseUriStr)); } private void Throw(string res, string arg) { Throw(new XmlException(res, arg, _ps.LineNo, _ps.LinePos, _ps.baseUriStr)); } private void Throw(string res, string arg, int lineNo, int linePos) { Throw(new XmlException(res, arg, lineNo, linePos, _ps.baseUriStr)); } private void Throw(string res, string[] args) { Throw(new XmlException(res, args, _ps.LineNo, _ps.LinePos, _ps.baseUriStr)); } private void Throw(string res, string arg, Exception innerException) { Throw(res, new string[] { arg }, innerException); } private void Throw(string res, string[] args, Exception innerException) { Throw(new XmlException(res, args, innerException, _ps.LineNo, _ps.LinePos, _ps.baseUriStr)); } private void Throw(Exception e) { SetErrorState(); XmlException xmlEx = e as XmlException; if (xmlEx != null) { _curNode.SetLineInfo(xmlEx.LineNumber, xmlEx.LinePosition); } throw e; } private void ReThrow(Exception e, int lineNo, int linePos) { Throw(new XmlException(e.Message, (Exception)null, lineNo, linePos, _ps.baseUriStr)); } private void ThrowWithoutLineInfo(string res) { Throw(new XmlException(res, string.Empty, _ps.baseUriStr)); } private void ThrowWithoutLineInfo(string res, string arg) { Throw(new XmlException(res, arg, _ps.baseUriStr)); } private void ThrowWithoutLineInfo(string res, string[] args, Exception innerException) { Throw(new XmlException(res, args, innerException, 0, 0, _ps.baseUriStr)); } private void ThrowInvalidChar(char[] data, int length, int invCharPos) { Throw(invCharPos, SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(data, length, invCharPos)); } private void SetErrorState() { _parsingFunction = ParsingFunction.Error; _readState = ReadState.Error; } private void SendValidationEvent(XmlSeverityType severity, string code, string arg, int lineNo, int linePos) { SendValidationEvent(severity, new XmlSchemaException(code, arg, _ps.baseUriStr, lineNo, linePos)); } private void SendValidationEvent(XmlSeverityType severity, XmlSchemaException exception) { if (_validationEventHandling != null) { _validationEventHandling.SendEvent(exception, severity); } } // // Private implementation methods & properties // private bool InAttributeValueIterator { get { return _attrCount > 0 && _parsingFunction >= ParsingFunction.InReadAttributeValue; } } private void FinishAttributeValueIterator() { Debug.Assert(InAttributeValueIterator); if (_parsingFunction == ParsingFunction.InReadValueChunk) { FinishReadValueChunk(); } else if (_parsingFunction == ParsingFunction.InReadContentAsBinary) { FinishReadContentAsBinary(); } if (_parsingFunction == ParsingFunction.InReadAttributeValue) { while (_ps.entityId != _attributeValueBaseEntityId) { HandleEntityEnd(false); } _emptyEntityInAttributeResolved = false; _parsingFunction = _nextParsingFunction; _nextParsingFunction = (_index > 0) ? ParsingFunction.ElementContent : ParsingFunction.DocumentContent; } } private bool DtdValidation { get { return _validationEventHandling != null; } } private void InitStreamInput(Stream stream, Encoding encoding) { InitStreamInput(null, string.Empty, stream, null, 0, encoding); } private void InitStreamInput(string baseUriStr, Stream stream, Encoding encoding) { Debug.Assert(baseUriStr != null); InitStreamInput(null, baseUriStr, stream, null, 0, encoding); } private void InitStreamInput(Uri baseUri, Stream stream, Encoding encoding) { Debug.Assert(baseUri != null); InitStreamInput(baseUri, baseUri.ToString(), stream, null, 0, encoding); } private void InitStreamInput(Uri baseUri, string baseUriStr, Stream stream, Encoding encoding) { InitStreamInput(baseUri, baseUriStr, stream, null, 0, encoding); } private void InitStreamInput(Uri baseUri, string baseUriStr, Stream stream, byte[] bytes, int byteCount, Encoding encoding) { Debug.Assert(_ps.charPos == 0 && _ps.charsUsed == 0 && _ps.textReader == null); Debug.Assert(baseUriStr != null); Debug.Assert(baseUri == null || (baseUri.ToString().Equals(baseUriStr))); _ps.stream = stream; _ps.baseUri = baseUri; _ps.baseUriStr = baseUriStr; // take over the byte buffer allocated in XmlReader.Create, if available int bufferSize; if (bytes != null) { _ps.bytes = bytes; _ps.bytesUsed = byteCount; bufferSize = _ps.bytes.Length; } else { // allocate the byte buffer if (_laterInitParam != null && _laterInitParam.useAsync) { bufferSize = AsyncBufferSize; } else { bufferSize = XmlReader.CalcBufferSize(stream); } if (_ps.bytes == null || _ps.bytes.Length < bufferSize) { _ps.bytes = new byte[bufferSize]; } } // allocate char buffer if (_ps.chars == null || _ps.chars.Length < bufferSize + 1) { _ps.chars = new char[bufferSize + 1]; } // make sure we have at least 4 bytes to detect the encoding (no preamble of System.Text supported encoding is longer than 4 bytes) _ps.bytePos = 0; while (_ps.bytesUsed < 4 && _ps.bytes.Length - _ps.bytesUsed > 0) { int read = stream.Read(_ps.bytes, _ps.bytesUsed, _ps.bytes.Length - _ps.bytesUsed); if (read == 0) { _ps.isStreamEof = true; break; } _ps.bytesUsed += read; } // detect & setup encoding if (encoding == null) { encoding = DetectEncoding(); } SetupEncoding(encoding); // eat preamble EatPreamble(); _documentStartBytePos = _ps.bytePos; _ps.eolNormalized = !_normalize; // decode first characters _ps.appendMode = true; ReadData(); } private void InitTextReaderInput(string baseUriStr, TextReader input) { InitTextReaderInput(baseUriStr, null, input); } private void InitTextReaderInput(string baseUriStr, Uri baseUri, TextReader input) { Debug.Assert(_ps.charPos == 0 && _ps.charsUsed == 0 && _ps.stream == null); Debug.Assert(baseUriStr != null); _ps.textReader = input; _ps.baseUriStr = baseUriStr; _ps.baseUri = baseUri; if (_ps.chars == null) { if (_laterInitParam != null && _laterInitParam.useAsync) { _ps.chars = new char[XmlReader.AsyncBufferSize + 1]; } else { _ps.chars = new char[XmlReader.DefaultBufferSize + 1]; } } _ps.encoding = Encoding.Unicode; _ps.eolNormalized = !_normalize; // read first characters _ps.appendMode = true; ReadData(); } private void InitStringInput(string baseUriStr, Encoding originalEncoding, string str) { Debug.Assert(_ps.stream == null && _ps.textReader == null); Debug.Assert(_ps.charPos == 0 && _ps.charsUsed == 0); Debug.Assert(baseUriStr != null); Debug.Assert(str != null); _ps.baseUriStr = baseUriStr; _ps.baseUri = null; int len = str.Length; _ps.chars = new char[len + 1]; str.CopyTo(0, _ps.chars, 0, str.Length); _ps.charsUsed = len; _ps.chars[len] = (char)0; _ps.encoding = originalEncoding; _ps.eolNormalized = !_normalize; _ps.isEof = true; } private void InitFragmentReader(XmlNodeType fragmentType, XmlParserContext parserContext, bool allowXmlDeclFragment) { _fragmentParserContext = parserContext; if (parserContext != null) { if (parserContext.NamespaceManager != null) { _namespaceManager = parserContext.NamespaceManager; _xmlContext.defaultNamespace = _namespaceManager.LookupNamespace(string.Empty); } else { _namespaceManager = new XmlNamespaceManager(_nameTable); } _ps.baseUriStr = parserContext.BaseURI; _ps.baseUri = null; _xmlContext.xmlLang = parserContext.XmlLang; _xmlContext.xmlSpace = parserContext.XmlSpace; } else { _namespaceManager = new XmlNamespaceManager(_nameTable); _ps.baseUriStr = string.Empty; _ps.baseUri = null; } _reportedBaseUri = _ps.baseUriStr; switch (fragmentType) { case XmlNodeType.Attribute: _ps.appendMode = false; _parsingFunction = ParsingFunction.SwitchToInteractive; _nextParsingFunction = ParsingFunction.FragmentAttribute; break; case XmlNodeType.Element: Debug.Assert(_parsingFunction == ParsingFunction.SwitchToInteractiveXmlDecl); _nextParsingFunction = ParsingFunction.DocumentContent; break; case XmlNodeType.Document: Debug.Assert(_parsingFunction == ParsingFunction.SwitchToInteractiveXmlDecl); Debug.Assert(_nextParsingFunction == ParsingFunction.DocumentContent); break; case XmlNodeType.XmlDeclaration: if (allowXmlDeclFragment) { _ps.appendMode = false; _parsingFunction = ParsingFunction.SwitchToInteractive; _nextParsingFunction = ParsingFunction.XmlDeclarationFragment; break; } else { goto default; } default: Throw(SR.Xml_PartialContentNodeTypeNotSupportedEx, fragmentType.ToString()); return; } _fragmentType = fragmentType; _fragment = true; } private void ProcessDtdFromParserContext(XmlParserContext context) { Debug.Assert(context != null && context.HasDtdInfo); switch (_dtdProcessing) { case DtdProcessing.Prohibit: ThrowWithoutLineInfo(SR.Xml_DtdIsProhibitedEx); break; case DtdProcessing.Ignore: // do nothing break; case DtdProcessing.Parse: ParseDtdFromParserContext(); break; default: Debug.Fail("Unhandled DtdProcessing enumeration value."); break; } } // SxS: This method resolve Uri but does not expose it to the caller. It's OK to suppress the warning. private void OpenUrl() { Debug.Assert(_url != null && _url.Length > 0); // It is safe to use the resolver here as we don't resolve or expose any DTD to the caller XmlResolver tmpResolver = GetTempResolver(); if (_ps.baseUri == null) { _ps.baseUri = tmpResolver.ResolveUri(null, _url); _ps.baseUriStr = _ps.baseUri.ToString(); } try { _ps.stream = (Stream)tmpResolver.GetEntity(_ps.baseUri, null, typeof(Stream)); } catch { SetErrorState(); throw; } if (_ps.stream == null) { ThrowWithoutLineInfo(SR.Xml_CannotResolveUrl, _ps.baseUriStr); } InitStreamInput(_ps.baseUri, _ps.baseUriStr, _ps.stream, null); _reportedEncoding = _ps.encoding; } // Stream input only: detect encoding from the first 4 bytes of the byte buffer starting at ps.bytes[ps.bytePos] private Encoding DetectEncoding() { Debug.Assert(_ps.bytes != null); Debug.Assert(_ps.bytePos == 0); if (_ps.bytesUsed < 2) { return null; } int first2Bytes = _ps.bytes[0] << 8 | _ps.bytes[1]; int next2Bytes = (_ps.bytesUsed >= 4) ? (_ps.bytes[2] << 8 | _ps.bytes[3]) : 0; switch (first2Bytes) { // Removing USC4 encoding case 0x0000: switch (next2Bytes) { case 0xFEFF: return Ucs4Encoding.UCS4_Bigendian; case 0x003C: return Ucs4Encoding.UCS4_Bigendian; case 0xFFFE: return Ucs4Encoding.UCS4_2143; case 0x3C00: return Ucs4Encoding.UCS4_2143; } break; case 0xFEFF: if (next2Bytes == 0x0000) { return Ucs4Encoding.UCS4_3412; } else { return Encoding.BigEndianUnicode; } case 0xFFFE: if (next2Bytes == 0x0000) { return Ucs4Encoding.UCS4_Littleendian; } else { return Encoding.Unicode; } case 0x3C00: if (next2Bytes == 0x0000) { return Ucs4Encoding.UCS4_Littleendian; } else { return Encoding.Unicode; } case 0x003C: if (next2Bytes == 0x0000) { return Ucs4Encoding.UCS4_3412; } else { return Encoding.BigEndianUnicode; } case 0x4C6F: if (next2Bytes == 0xA794) { Throw(SR.Xml_UnknownEncoding, "ebcdic"); } break; case 0xEFBB: if ((next2Bytes & 0xFF00) == 0xBF00) { return new UTF8Encoding(true, true); } break; } // Default encoding is ASCII (using SafeAsciiDecoder) until we read xml declaration. // If we set UTF8 encoding now, it will throw exceptions (=slow) when decoding non-UTF8-friendly // characters after the xml declaration, which may be perfectly valid in the encoding // specified in xml declaration. return null; } private void SetupEncoding(Encoding encoding) { if (encoding == null) { Debug.Assert(_ps.charPos == 0); _ps.encoding = Encoding.UTF8; _ps.decoder = new SafeAsciiDecoder(); } else { _ps.encoding = encoding; _ps.decoder = _ps.encoding.WebName switch // Encoding.Codepage is not supported in Silverlight { "utf-16" => new UTF16Decoder(false), "utf-16BE" => new UTF16Decoder(true), _ => encoding.GetDecoder(), }; } } private void EatPreamble() { ReadOnlySpan<byte> preamble = _ps.encoding.Preamble; int preambleLen = preamble.Length; int i; for (i = 0; i < preambleLen && i < _ps.bytesUsed; i++) { if (_ps.bytes[i] != preamble[i]) { break; } } if (i == preambleLen) { _ps.bytePos = preambleLen; } } // Switches the reader's encoding private void SwitchEncoding(Encoding newEncoding) { if ((newEncoding.WebName != _ps.encoding.WebName || _ps.decoder is SafeAsciiDecoder) && !_afterResetState) { Debug.Assert(_ps.stream != null); UnDecodeChars(); _ps.appendMode = false; SetupEncoding(newEncoding); ReadData(); } } // Returns the Encoding object for the given encoding name, if the reader's encoding can be switched to that encoding. // Performs checks whether switching from current encoding to specified encoding is allowed. private Encoding CheckEncoding(string newEncodingName) { // encoding can be switched on stream input only if (_ps.stream == null) { return _ps.encoding; } if (string.Equals(newEncodingName, "ucs-2", StringComparison.OrdinalIgnoreCase) || string.Equals(newEncodingName, "utf-16", StringComparison.OrdinalIgnoreCase) || string.Equals(newEncodingName, "iso-10646-ucs-2", StringComparison.OrdinalIgnoreCase) || string.Equals(newEncodingName, "ucs-4", StringComparison.OrdinalIgnoreCase)) { if (_ps.encoding.WebName != "utf-16BE" && _ps.encoding.WebName != "utf-16" && !string.Equals(newEncodingName, "ucs-4", StringComparison.OrdinalIgnoreCase)) { if (_afterResetState) { Throw(SR.Xml_EncodingSwitchAfterResetState, newEncodingName); } else { ThrowWithoutLineInfo(SR.Xml_MissingByteOrderMark); } } return _ps.encoding; } Encoding newEncoding = null; if (string.Equals(newEncodingName, "utf-8", StringComparison.OrdinalIgnoreCase)) { newEncoding = UTF8BomThrowing; } else { try { newEncoding = Encoding.GetEncoding(newEncodingName); } catch (NotSupportedException innerEx) { Throw(SR.Xml_UnknownEncoding, newEncodingName, innerEx); } catch (ArgumentException innerEx) { Throw(SR.Xml_UnknownEncoding, newEncodingName, innerEx); } Debug.Assert(newEncoding.EncodingName != "UTF-8"); } // check for invalid encoding switches after ResetState if (_afterResetState && _ps.encoding.WebName != newEncoding.WebName) { Throw(SR.Xml_EncodingSwitchAfterResetState, newEncodingName); } return newEncoding; } private void UnDecodeChars() { Debug.Assert(_ps.stream != null && _ps.decoder != null && _ps.bytes != null); Debug.Assert(_ps.appendMode, "UnDecodeChars cannot be called after ps.appendMode has been changed to false"); Debug.Assert(_ps.charsUsed >= _ps.charPos, "The current position must be in the valid character range."); if (_maxCharactersInDocument > 0) { // We're returning back in the input (potentially) so we need to fixup // the character counters to avoid counting some of them twice. // The following code effectively rolls-back all decoded characters // after the ps.charPos (which typically points to the first character // after the XML decl). Debug.Assert(_charactersInDocument >= _ps.charsUsed - _ps.charPos, "We didn't correctly count some of the decoded characters against the MaxCharactersInDocument."); _charactersInDocument -= _ps.charsUsed - _ps.charPos; } if (_maxCharactersFromEntities > 0) { if (InEntity) { Debug.Assert(_charactersFromEntities >= _ps.charsUsed - _ps.charPos, "We didn't correctly count some of the decoded characters against the MaxCharactersFromEntities."); _charactersFromEntities -= _ps.charsUsed - _ps.charPos; } } _ps.bytePos = _documentStartBytePos; // byte position after preamble if (_ps.charPos > 0) { _ps.bytePos += _ps.encoding.GetByteCount(_ps.chars, 0, _ps.charPos); } _ps.charsUsed = _ps.charPos; _ps.isEof = false; } private void SwitchEncodingToUTF8() { SwitchEncoding(UTF8BomThrowing); } // Reads more data to the character buffer, discarding already parsed chars / decoded bytes. private int ReadData() { // Append Mode: Append new bytes and characters to the buffers, do not rewrite them. Allocate new buffers // if the current ones are full // Rewrite Mode: Reuse the buffers. If there is less than half of the char buffer left for new data, move // the characters that has not been parsed yet to the front of the buffer. Same for bytes. if (_ps.isEof) { return 0; } int charsRead; if (_ps.appendMode) { // the character buffer is full -> allocate a new one if (_ps.charsUsed == _ps.chars.Length - 1) { // invalidate node values kept in buffer - applies to attribute values only for (int i = 0; i < _attrCount; i++) { _nodes[_index + i + 1].OnBufferInvalidated(); } char[] newChars = new char[_ps.chars.Length * 2]; BlockCopyChars(_ps.chars, 0, newChars, 0, _ps.chars.Length); _ps.chars = newChars; } if (_ps.stream != null) { // the byte buffer is full -> allocate a new one if (_ps.bytesUsed - _ps.bytePos < MaxByteSequenceLen) { if (_ps.bytes.Length - _ps.bytesUsed < MaxByteSequenceLen) { byte[] newBytes = new byte[_ps.bytes.Length * 2]; BlockCopy(_ps.bytes, 0, newBytes, 0, _ps.bytesUsed); _ps.bytes = newBytes; } } } charsRead = _ps.chars.Length - _ps.charsUsed - 1; if (charsRead > ApproxXmlDeclLength) { charsRead = ApproxXmlDeclLength; } } else { int charsLen = _ps.chars.Length; if (charsLen - _ps.charsUsed <= charsLen / 2) { // invalidate node values kept in buffer - applies to attribute values only for (int i = 0; i < _attrCount; i++) { _nodes[_index + i + 1].OnBufferInvalidated(); } // move unparsed characters to front, unless the whole buffer contains unparsed characters int copyCharsCount = _ps.charsUsed - _ps.charPos; if (copyCharsCount < charsLen - 1) { _ps.lineStartPos = _ps.lineStartPos - _ps.charPos; if (copyCharsCount > 0) { BlockCopyChars(_ps.chars, _ps.charPos, _ps.chars, 0, copyCharsCount); } _ps.charPos = 0; _ps.charsUsed = copyCharsCount; } else { char[] newChars = new char[_ps.chars.Length * 2]; BlockCopyChars(_ps.chars, 0, newChars, 0, _ps.chars.Length); _ps.chars = newChars; } } if (_ps.stream != null) { // move undecoded bytes to the front to make some space in the byte buffer int bytesLeft = _ps.bytesUsed - _ps.bytePos; if (bytesLeft <= MaxBytesToMove) { if (bytesLeft == 0) { _ps.bytesUsed = 0; } else { BlockCopy(_ps.bytes, _ps.bytePos, _ps.bytes, 0, bytesLeft); _ps.bytesUsed = bytesLeft; } _ps.bytePos = 0; } } charsRead = _ps.chars.Length - _ps.charsUsed - 1; } if (_ps.stream != null) { if (!_ps.isStreamEof) { // read new bytes if (_ps.bytePos == _ps.bytesUsed && _ps.bytes.Length - _ps.bytesUsed > 0) { int read = _ps.stream.Read(_ps.bytes, _ps.bytesUsed, _ps.bytes.Length - _ps.bytesUsed); if (read == 0) { _ps.isStreamEof = true; } _ps.bytesUsed += read; } } int originalBytePos = _ps.bytePos; // decode chars charsRead = GetChars(charsRead); if (charsRead == 0 && _ps.bytePos != originalBytePos) { // GetChars consumed some bytes but it was not enough bytes to form a character -> try again return ReadData(); } } else if (_ps.textReader != null) { // read chars charsRead = _ps.textReader.Read(_ps.chars, _ps.charsUsed, _ps.chars.Length - _ps.charsUsed - 1); _ps.charsUsed += charsRead; } else { charsRead = 0; } RegisterConsumedCharacters(charsRead, InEntity); if (charsRead == 0) { Debug.Assert(_ps.charsUsed < _ps.chars.Length); _ps.isEof = true; } _ps.chars[_ps.charsUsed] = (char)0; return charsRead; } // Stream input only: read bytes from stream and decodes them according to the current encoding private int GetChars(int maxCharsCount) { Debug.Assert(_ps.stream != null && _ps.decoder != null && _ps.bytes != null); Debug.Assert(maxCharsCount <= _ps.chars.Length - _ps.charsUsed - 1); // determine the maximum number of bytes we can pass to the decoder int bytesCount = _ps.bytesUsed - _ps.bytePos; if (bytesCount == 0) { return 0; } int charsCount; bool completed; try { // decode chars _ps.decoder.Convert(_ps.bytes, _ps.bytePos, bytesCount, _ps.chars, _ps.charsUsed, maxCharsCount, false, out bytesCount, out charsCount, out completed); } catch (ArgumentException) { InvalidCharRecovery(ref bytesCount, out charsCount); } // move pointers and return _ps.bytePos += bytesCount; _ps.charsUsed += charsCount; Debug.Assert(maxCharsCount >= charsCount); return charsCount; } private void InvalidCharRecovery(ref int bytesCount, out int charsCount) { int charsDecoded = 0; int bytesDecoded = 0; try { while (bytesDecoded < bytesCount) { int chDec; int bDec; bool completed; _ps.decoder.Convert(_ps.bytes, _ps.bytePos + bytesDecoded, 1, _ps.chars, _ps.charsUsed + charsDecoded, 2, false, out bDec, out chDec, out completed); charsDecoded += chDec; bytesDecoded += bDec; } Debug.Fail("We should get an exception again."); } catch (ArgumentException) { } if (charsDecoded == 0) { Throw(_ps.charsUsed, SR.Xml_InvalidCharInThisEncoding); } charsCount = charsDecoded; bytesCount = bytesDecoded; } internal void Close(bool closeInput) { if (_parsingFunction == ParsingFunction.ReaderClosed) { return; } while (InEntity) { PopParsingState(); } _ps.Close(closeInput); _curNode = NodeData.None; _parsingFunction = ParsingFunction.ReaderClosed; _reportedEncoding = null; _reportedBaseUri = string.Empty; _readState = ReadState.Closed; _fullAttrCleanup = false; ResetAttributes(); _laterInitParam = null; } private void ShiftBuffer(int sourcePos, int destPos, int count) { BlockCopyChars(_ps.chars, sourcePos, _ps.chars, destPos, count); } // Parses the xml or text declaration and switched encoding if needed private bool ParseXmlDeclaration(bool isTextDecl) { while (_ps.charsUsed - _ps.charPos < 6) { // minimum "<?xml " if (ReadData() == 0) { goto NoXmlDecl; } } if (!XmlConvert.StrEqual(_ps.chars, _ps.charPos, 5, XmlDeclarationBeginning) || _xmlCharType.IsNameSingleChar(_ps.chars[_ps.charPos + 5]) #if XML10_FIFTH_EDITION || xmlCharType.IsNCNameHighSurrogateChar( ps.chars[ps.charPos + 5] ) #endif ) { goto NoXmlDecl; } if (!isTextDecl) { _curNode.SetLineInfo(_ps.LineNo, _ps.LinePos + 2); _curNode.SetNamedNode(XmlNodeType.XmlDeclaration, _xml); } _ps.charPos += 5; // parsing of text declarations cannot change global stringBuidler or curNode as we may be in the middle of a text node Debug.Assert(_stringBuilder.Length == 0 || isTextDecl); StringBuilder sb = isTextDecl ? new StringBuilder() : _stringBuilder; // parse version, encoding & standalone attributes int xmlDeclState = 0; // <?xml (0) version='1.0' (1) encoding='__' (2) standalone='__' (3) ?> Encoding encoding = null; while (true) { int originalSbLen = sb.Length; int wsCount = EatWhitespaces(xmlDeclState == 0 ? null : sb); // end of xml declaration if (_ps.chars[_ps.charPos] == '?') { sb.Length = originalSbLen; if (_ps.chars[_ps.charPos + 1] == '>') { if (xmlDeclState == 0) { Throw(isTextDecl ? SR.Xml_InvalidTextDecl : SR.Xml_InvalidXmlDecl); } _ps.charPos += 2; if (!isTextDecl) { _curNode.SetValue(sb.ToString()); sb.Length = 0; _nextParsingFunction = _parsingFunction; _parsingFunction = ParsingFunction.ResetAttributesRootLevel; } // switch to encoding specified in xml declaration if (encoding == null) { if (isTextDecl) { Throw(SR.Xml_InvalidTextDecl); } if (_afterResetState) { // check for invalid encoding switches to default encoding string encodingName = _ps.encoding.WebName; if (encodingName != "utf-8" && encodingName != "utf-16" && encodingName != "utf-16BE" && !(_ps.encoding is Ucs4Encoding)) { Throw(SR.Xml_EncodingSwitchAfterResetState, (_ps.encoding.GetByteCount("A") == 1) ? "UTF-8" : "UTF-16"); } } if (_ps.decoder is SafeAsciiDecoder) { SwitchEncodingToUTF8(); } } else { SwitchEncoding(encoding); } _ps.appendMode = false; return true; } else if (_ps.charPos + 1 == _ps.charsUsed) { goto ReadData; } else { ThrowUnexpectedToken("'>'"); } } if (wsCount == 0 && xmlDeclState != 0) { ThrowUnexpectedToken("?>"); } // read attribute name int nameEndPos = ParseName(); NodeData attr = null; switch (_ps.chars[_ps.charPos]) { case 'v': if (XmlConvert.StrEqual(_ps.chars, _ps.charPos, nameEndPos - _ps.charPos, "version") && xmlDeclState == 0) { if (!isTextDecl) { attr = AddAttributeNoChecks("version", 1); } break; } goto default; case 'e': if (XmlConvert.StrEqual(_ps.chars, _ps.charPos, nameEndPos - _ps.charPos, "encoding") && (xmlDeclState == 1 || (isTextDecl && xmlDeclState == 0))) { if (!isTextDecl) { attr = AddAttributeNoChecks("encoding", 1); } xmlDeclState = 1; break; } goto default; case 's': if (XmlConvert.StrEqual(_ps.chars, _ps.charPos, nameEndPos - _ps.charPos, "standalone") && (xmlDeclState == 1 || xmlDeclState == 2) && !isTextDecl) { if (!isTextDecl) { attr = AddAttributeNoChecks("standalone", 1); } xmlDeclState = 2; break; } goto default; default: Throw(isTextDecl ? SR.Xml_InvalidTextDecl : SR.Xml_InvalidXmlDecl); break; } if (!isTextDecl) { attr.SetLineInfo(_ps.LineNo, _ps.LinePos); } sb.Append(_ps.chars, _ps.charPos, nameEndPos - _ps.charPos); _ps.charPos = nameEndPos; // parse equals and quote char; if (_ps.chars[_ps.charPos] != '=') { EatWhitespaces(sb); if (_ps.chars[_ps.charPos] != '=') { ThrowUnexpectedToken("="); } } sb.Append('='); _ps.charPos++; char quoteChar = _ps.chars[_ps.charPos]; if (quoteChar != '"' && quoteChar != '\'') { EatWhitespaces(sb); quoteChar = _ps.chars[_ps.charPos]; if (quoteChar != '"' && quoteChar != '\'') { ThrowUnexpectedToken("\"", "'"); } } sb.Append(quoteChar); _ps.charPos++; if (!isTextDecl) { attr.quoteChar = quoteChar; attr.SetLineInfo2(_ps.LineNo, _ps.LinePos); } // parse attribute value int pos = _ps.charPos; char[] chars; Continue: chars = _ps.chars; while (_xmlCharType.IsAttributeValueChar(chars[pos])) { pos++; } if (_ps.chars[pos] == quoteChar) { switch (xmlDeclState) { // version case 0: #if XML10_FIFTH_EDITION // VersionNum ::= '1.' [0-9]+ (starting with XML Fifth Edition) if (pos - ps.charPos >= 3 && ps.chars[ps.charPos] == '1' && ps.chars[ps.charPos + 1] == '.' && XmlCharType.IsOnlyDigits(ps.chars, ps.charPos + 2, pos - ps.charPos - 2)) { #else // VersionNum ::= '1.0' (XML Fourth Edition and earlier) if (XmlConvert.StrEqual(_ps.chars, _ps.charPos, pos - _ps.charPos, "1.0")) { #endif if (!isTextDecl) { attr.SetValue(_ps.chars, _ps.charPos, pos - _ps.charPos); } xmlDeclState = 1; } else { string badVersion = new string(_ps.chars, _ps.charPos, pos - _ps.charPos); Throw(SR.Xml_InvalidVersionNumber, badVersion); } break; case 1: string encName = new string(_ps.chars, _ps.charPos, pos - _ps.charPos); encoding = CheckEncoding(encName); if (!isTextDecl) { attr.SetValue(encName); } xmlDeclState = 2; break; case 2: if (XmlConvert.StrEqual(_ps.chars, _ps.charPos, pos - _ps.charPos, "yes")) { _standalone = true; } else if (XmlConvert.StrEqual(_ps.chars, _ps.charPos, pos - _ps.charPos, "no")) { _standalone = false; } else { Debug.Assert(!isTextDecl); Throw(SR.Xml_InvalidXmlDecl, _ps.LineNo, _ps.LinePos - 1); } if (!isTextDecl) { attr.SetValue(_ps.chars, _ps.charPos, pos - _ps.charPos); } xmlDeclState = 3; break; default: Debug.Fail($"Unexpected xmlDeclState {xmlDeclState}"); break; } sb.Append(chars, _ps.charPos, pos - _ps.charPos); sb.Append(quoteChar); _ps.charPos = pos + 1; continue; } else if (pos == _ps.charsUsed) { if (ReadData() != 0) { goto Continue; } else { Throw(SR.Xml_UnclosedQuote); } } else { Throw(isTextDecl ? SR.Xml_InvalidTextDecl : SR.Xml_InvalidXmlDecl); } ReadData: if (_ps.isEof || ReadData() == 0) { Throw(SR.Xml_UnexpectedEOF1); } } NoXmlDecl: // no xml declaration if (!isTextDecl) { _parsingFunction = _nextParsingFunction; } if (_afterResetState) { // check for invalid encoding switches to default encoding string encodingName = _ps.encoding.WebName; if (encodingName != "utf-8" && encodingName != "utf-16" && encodingName != "utf-16BE" && !(_ps.encoding is Ucs4Encoding)) { Throw(SR.Xml_EncodingSwitchAfterResetState, (_ps.encoding.GetByteCount("A") == 1) ? "UTF-8" : "UTF-16"); } } if (_ps.decoder is SafeAsciiDecoder) { SwitchEncodingToUTF8(); } _ps.appendMode = false; return false; } // Parses the document content private bool ParseDocumentContent() { bool mangoQuirks = false; #if FEATURE_LEGACYNETCF // In Mango the default XmlTextReader is instantiated // with v1Compat flag set to true. One of the effects // of this settings is to eat any trailing nulls in the // buffer and some apps depend on this behavior. if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) mangoQuirks = true; #endif while (true) { bool needMoreChars = false; int pos = _ps.charPos; char[] chars = _ps.chars; // some tag if (chars[pos] == '<') { needMoreChars = true; if (_ps.charsUsed - pos < 4) // minimum "<a/>" goto ReadData; pos++; switch (chars[pos]) { // processing instruction case '?': _ps.charPos = pos + 1; if (ParsePI()) { return true; } continue; case '!': pos++; if (_ps.charsUsed - pos < 2) // minimum characters expected "--" goto ReadData; // comment if (chars[pos] == '-') { if (chars[pos + 1] == '-') { _ps.charPos = pos + 2; if (ParseComment()) { return true; } continue; } else { ThrowUnexpectedToken(pos + 1, "-"); } } // CDATA section else if (chars[pos] == '[') { if (_fragmentType != XmlNodeType.Document) { pos++; if (_ps.charsUsed - pos < 6) { goto ReadData; } if (XmlConvert.StrEqual(chars, pos, 6, "CDATA[")) { _ps.charPos = pos + 6; ParseCData(); if (_fragmentType == XmlNodeType.None) { _fragmentType = XmlNodeType.Element; } return true; } else { ThrowUnexpectedToken(pos, "CDATA["); } } else { Throw(_ps.charPos, SR.Xml_InvalidRootData); } } // DOCTYPE declaration else { if (_fragmentType == XmlNodeType.Document || _fragmentType == XmlNodeType.None) { _fragmentType = XmlNodeType.Document; _ps.charPos = pos; if (ParseDoctypeDecl()) { return true; } continue; } else { if (ParseUnexpectedToken(pos) == "DOCTYPE") { Throw(SR.Xml_BadDTDLocation); } else { ThrowUnexpectedToken(pos, "<!--", "<[CDATA["); } } } break; case '/': Throw(pos + 1, SR.Xml_UnexpectedEndTag); break; // document element start tag default: if (_rootElementParsed) { if (_fragmentType == XmlNodeType.Document) { Throw(pos, SR.Xml_MultipleRoots); } if (_fragmentType == XmlNodeType.None) { _fragmentType = XmlNodeType.Element; } } _ps.charPos = pos; _rootElementParsed = true; ParseElement(); return true; } } else if (chars[pos] == '&') { if (_fragmentType == XmlNodeType.Document) { Throw(pos, SR.Xml_InvalidRootData); } else { if (_fragmentType == XmlNodeType.None) { _fragmentType = XmlNodeType.Element; } int i; switch (HandleEntityReference(false, EntityExpandType.OnlyGeneral, out i)) { case EntityType.Unexpanded: if (_parsingFunction == ParsingFunction.EntityReference) { _parsingFunction = _nextParsingFunction; } ParseEntityReference(); return true; case EntityType.CharacterDec: case EntityType.CharacterHex: case EntityType.CharacterNamed: if (ParseText()) { return true; } continue; default: chars = _ps.chars; pos = _ps.charPos; continue; } } } // end of buffer else if (pos == _ps.charsUsed || ((_v1Compat || mangoQuirks) && chars[pos] == 0x0)) { goto ReadData; } // something else -> root level whitespace else { if (_fragmentType == XmlNodeType.Document) { if (ParseRootLevelWhitespace()) { return true; } } else { if (ParseText()) { if (_fragmentType == XmlNodeType.None && _curNode.type == XmlNodeType.Text) { _fragmentType = XmlNodeType.Element; } return true; } } continue; } Debug.Assert(pos == _ps.charsUsed && !_ps.isEof); ReadData: // read new characters into the buffer if (ReadData() != 0) { pos = _ps.charPos; } else { if (needMoreChars) { Throw(SR.Xml_InvalidRootData); } if (InEntity) { if (HandleEntityEnd(true)) { SetupEndEntityNodeInContent(); return true; } continue; } Debug.Assert(_index == 0); if (!_rootElementParsed && _fragmentType == XmlNodeType.Document) { ThrowWithoutLineInfo(SR.Xml_MissingRoot); } if (_fragmentType == XmlNodeType.None) { _fragmentType = _rootElementParsed ? XmlNodeType.Document : XmlNodeType.Element; } OnEof(); return false; } pos = _ps.charPos; chars = _ps.chars; } } // Parses element content private bool ParseElementContent() { while (true) { int pos = _ps.charPos; char[] chars = _ps.chars; switch (chars[pos]) { // some tag case '<': switch (chars[pos + 1]) { // processing instruction case '?': _ps.charPos = pos + 2; if (ParsePI()) { return true; } continue; case '!': pos += 2; if (_ps.charsUsed - pos < 2) goto ReadData; // comment if (chars[pos] == '-') { if (chars[pos + 1] == '-') { _ps.charPos = pos + 2; if (ParseComment()) { return true; } continue; } else { ThrowUnexpectedToken(pos + 1, "-"); } } // CDATA section else if (chars[pos] == '[') { pos++; if (_ps.charsUsed - pos < 6) { goto ReadData; } if (XmlConvert.StrEqual(chars, pos, 6, "CDATA[")) { _ps.charPos = pos + 6; ParseCData(); return true; } else { ThrowUnexpectedToken(pos, "CDATA["); } } else { if (ParseUnexpectedToken(pos) == "DOCTYPE") { Throw(SR.Xml_BadDTDLocation); } else { ThrowUnexpectedToken(pos, "<!--", "<[CDATA["); } } break; // element end tag case '/': _ps.charPos = pos + 2; ParseEndElement(); return true; default: // end of buffer if (pos + 1 == _ps.charsUsed) { goto ReadData; } else { // element start tag _ps.charPos = pos + 1; ParseElement(); return true; } } break; case '&': if (ParseText()) { return true; } continue; default: // end of buffer if (pos == _ps.charsUsed) { goto ReadData; } else { // text node, whitespace or entity reference if (ParseText()) { return true; } continue; } } ReadData: // read new characters into the buffer if (ReadData() == 0) { if (_ps.charsUsed - _ps.charPos != 0) { ThrowUnclosedElements(); } if (!InEntity) { if (_index == 0 && _fragmentType != XmlNodeType.Document) { OnEof(); return false; } ThrowUnclosedElements(); } if (HandleEntityEnd(true)) { SetupEndEntityNodeInContent(); return true; } } } } private void ThrowUnclosedElements() { if (_index == 0 && _curNode.type != XmlNodeType.Element) { Throw(_ps.charsUsed, SR.Xml_UnexpectedEOF1); } else { int i = (_parsingFunction == ParsingFunction.InIncrementalRead) ? _index : _index - 1; _stringBuilder.Length = 0; for (; i >= 0; i--) { NodeData el = _nodes[i]; if (el.type != XmlNodeType.Element) { continue; } _stringBuilder.Append(el.GetNameWPrefix(_nameTable)); if (i > 0) { _stringBuilder.Append(", "); } else { _stringBuilder.Append('.'); } } Throw(_ps.charsUsed, SR.Xml_UnexpectedEOFInElementContent, _stringBuilder.ToString()); } } // Parses the element start tag private void ParseElement() { int pos = _ps.charPos; char[] chars = _ps.chars; int colonPos = -1; _curNode.SetLineInfo(_ps.LineNo, _ps.LinePos); // PERF: we intentionally don't call ParseQName here to parse the element name unless a special // case occurs (like end of buffer, invalid name char) ContinueStartName: // check element name start char if (_xmlCharType.IsStartNCNameSingleChar(chars[pos])) { pos++; } #if XML10_FIFTH_EDITION else if (pos + 1 < ps.charsUsed && xmlCharType.IsNCNameSurrogateChar(chars[pos + 1], chars[pos])) { pos += 2; } #endif else { goto ParseQNameSlow; } ContinueName: // parse element name while (true) { if (_xmlCharType.IsNCNameSingleChar(chars[pos])) { pos++; } #if XML10_FIFTH_EDITION else if (pos < ps.charsUsed && xmlCharType.IsNCNameSurrogateChar(chars[pos + 1], chars[pos])) { pos += 2; } #endif else { break; } } // colon -> save prefix end position and check next char if it's name start char if (chars[pos] == ':') { if (colonPos != -1) { if (_supportNamespaces) { Throw(pos, SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(':', '\0')); } else { pos++; goto ContinueName; } } else { colonPos = pos; pos++; goto ContinueStartName; } } else if (pos + 1 < _ps.charsUsed) { goto SetElement; } ParseQNameSlow: pos = ParseQName(out colonPos); chars = _ps.chars; SetElement: // push namespace context _namespaceManager.PushScope(); // init the NodeData class if (colonPos == -1 || !_supportNamespaces) { _curNode.SetNamedNode(XmlNodeType.Element, _nameTable.Add(chars, _ps.charPos, pos - _ps.charPos)); } else { int startPos = _ps.charPos; int prefixLen = colonPos - startPos; if (prefixLen == _lastPrefix.Length && XmlConvert.StrEqual(chars, startPos, prefixLen, _lastPrefix)) { _curNode.SetNamedNode(XmlNodeType.Element, _nameTable.Add(chars, colonPos + 1, pos - colonPos - 1), _lastPrefix, null); } else { _curNode.SetNamedNode(XmlNodeType.Element, _nameTable.Add(chars, colonPos + 1, pos - colonPos - 1), _nameTable.Add(chars, _ps.charPos, prefixLen), null); _lastPrefix = _curNode.prefix; } } char ch = chars[pos]; // whitespace after element name -> there are probably some attributes bool isWs = _xmlCharType.IsWhiteSpace(ch); if (isWs) { _ps.charPos = pos; ParseAttributes(); return; } // no attributes else { // non-empty element if (ch == '>') { _ps.charPos = pos + 1; _parsingFunction = ParsingFunction.MoveToElementContent; } // empty element else if (ch == '/') { if (pos + 1 == _ps.charsUsed) { _ps.charPos = pos; if (ReadData() == 0) { Throw(pos, SR.Xml_UnexpectedEOF, ">"); } pos = _ps.charPos; chars = _ps.chars; } if (chars[pos + 1] == '>') { _curNode.IsEmptyElement = true; _nextParsingFunction = _parsingFunction; _parsingFunction = ParsingFunction.PopEmptyElementContext; _ps.charPos = pos + 2; } else { ThrowUnexpectedToken(pos, ">"); } } // something else after the element name else { Throw(pos, SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(chars, _ps.charsUsed, pos)); } // add default attributes & strip spaces in attributes with type other than CDATA if (_addDefaultAttributesAndNormalize) { AddDefaultAttributesAndNormalize(); } // lookup element namespace ElementNamespaceLookup(); } } private void AddDefaultAttributesAndNormalize() { Debug.Assert(_curNode.type == XmlNodeType.Element); IDtdAttributeListInfo attlistInfo = _dtdInfo.LookupAttributeList(_curNode.localName, _curNode.prefix); if (attlistInfo == null) { return; } // fix non-CDATA attribute value if (_normalize && attlistInfo.HasNonCDataAttributes) { // go through the attributes and normalize it if not CDATA type for (int i = _index + 1; i < _index + 1 + _attrCount; i++) { NodeData attr = _nodes[i]; IDtdAttributeInfo attributeInfo = attlistInfo.LookupAttribute(attr.prefix, attr.localName); if (attributeInfo != null && attributeInfo.IsNonCDataType) { if (DtdValidation && _standalone && attributeInfo.IsDeclaredInExternal) { // VC constraint: // The standalone document declaration must have the value "no" if any external markup declarations // contain declarations of attributes with values subject to normalization, where the attribute appears in // the document with a value which will change as a result of normalization, string oldValue = attr.StringValue; attr.TrimSpacesInValue(); if (oldValue != attr.StringValue) { SendValidationEvent(XmlSeverityType.Error, SR.Sch_StandAloneNormalization, attr.GetNameWPrefix(_nameTable), attr.LineNo, attr.LinePos); } } else attr.TrimSpacesInValue(); } } } // add default attributes IEnumerable<IDtdDefaultAttributeInfo> defaultAttributes = attlistInfo.LookupDefaultAttributes(); if (defaultAttributes != null) { int originalAttrCount = _attrCount; NodeData[] nameSortedAttributes = null; if (_attrCount >= MaxAttrDuplWalkCount) { nameSortedAttributes = new NodeData[_attrCount]; Array.Copy(_nodes, _index + 1, nameSortedAttributes, 0, _attrCount); Array.Sort<object>(nameSortedAttributes, DtdDefaultAttributeInfoToNodeDataComparer.Instance); } foreach (IDtdDefaultAttributeInfo defaultAttributeInfo in defaultAttributes) { if (AddDefaultAttributeDtd(defaultAttributeInfo, true, nameSortedAttributes)) { if (DtdValidation && _standalone && defaultAttributeInfo.IsDeclaredInExternal) { string prefix = defaultAttributeInfo.Prefix; string qname = (prefix.Length == 0) ? defaultAttributeInfo.LocalName : (prefix + ':' + defaultAttributeInfo.LocalName); SendValidationEvent(XmlSeverityType.Error, SR.Sch_UnSpecifiedDefaultAttributeInExternalStandalone, qname, _curNode.LineNo, _curNode.LinePos); } } } if (originalAttrCount == 0 && _attrNeedNamespaceLookup) { AttributeNamespaceLookup(); _attrNeedNamespaceLookup = false; } } } // parses the element end tag private void ParseEndElement() { // check if the end tag name equals start tag name NodeData startTagNode = _nodes[_index - 1]; int prefLen = startTagNode.prefix.Length; int locLen = startTagNode.localName.Length; while (_ps.charsUsed - _ps.charPos < prefLen + locLen + 1) { if (ReadData() == 0) { break; } } int nameLen; char[] chars = _ps.chars; if (startTagNode.prefix.Length == 0) { if (!XmlConvert.StrEqual(chars, _ps.charPos, locLen, startTagNode.localName)) { ThrowTagMismatch(startTagNode); } nameLen = locLen; } else { int colonPos = _ps.charPos + prefLen; if (!XmlConvert.StrEqual(chars, _ps.charPos, prefLen, startTagNode.prefix) || chars[colonPos] != ':' || !XmlConvert.StrEqual(chars, colonPos + 1, locLen, startTagNode.localName)) { ThrowTagMismatch(startTagNode); } nameLen = locLen + prefLen + 1; } LineInfo endTagLineInfo = new LineInfo(_ps.lineNo, _ps.LinePos); int pos; while (true) { pos = _ps.charPos + nameLen; chars = _ps.chars; if (pos == _ps.charsUsed) { goto ReadData; } if (_xmlCharType.IsNCNameSingleChar(chars[pos]) || (chars[pos] == ':') #if XML10_FIFTH_EDITION || xmlCharType.IsNCNameHighSurrogateChar(chars[pos]) #endif ) { ThrowTagMismatch(startTagNode); } // eat whitespace if (chars[pos] != '>') { char tmpCh; while (_xmlCharType.IsWhiteSpace(tmpCh = chars[pos])) { pos++; switch (tmpCh) { case (char)0xA: OnNewLine(pos); continue; case (char)0xD: if (chars[pos] == (char)0xA) { pos++; } else if (pos == _ps.charsUsed && !_ps.isEof) { break; } OnNewLine(pos); continue; } } } if (chars[pos] == '>') { break; } else if (pos == _ps.charsUsed) { goto ReadData; } else { ThrowUnexpectedToken(pos, ">"); } Debug.Fail("We should never get to this point."); ReadData: if (ReadData() == 0) { ThrowUnclosedElements(); } } Debug.Assert(_index > 0); _index--; _curNode = _nodes[_index]; // set the element data Debug.Assert(_curNode == startTagNode); startTagNode.lineInfo = endTagLineInfo; startTagNode.type = XmlNodeType.EndElement; _ps.charPos = pos + 1; // set next parsing function _nextParsingFunction = (_index > 0) ? _parsingFunction : ParsingFunction.DocumentContent; _parsingFunction = ParsingFunction.PopElementContext; } private void ThrowTagMismatch(NodeData startTag) { if (startTag.type == XmlNodeType.Element) { // parse the bad name int colonPos; int endPos = ParseQName(out colonPos); string[] args = new string[4]; args[0] = startTag.GetNameWPrefix(_nameTable); args[1] = startTag.lineInfo.lineNo.ToString(CultureInfo.InvariantCulture); args[2] = startTag.lineInfo.linePos.ToString(CultureInfo.InvariantCulture); args[3] = new string(_ps.chars, _ps.charPos, endPos - _ps.charPos); Throw(SR.Xml_TagMismatchEx, args); } else { Debug.Assert(startTag.type == XmlNodeType.EntityReference); Throw(SR.Xml_UnexpectedEndTag); } } // Reads the attributes private void ParseAttributes() { int pos = _ps.charPos; char[] chars = _ps.chars; NodeData attr = null; Debug.Assert(_attrCount == 0); while (true) { // eat whitespace int lineNoDelta = 0; char tmpch0; while (_xmlCharType.IsWhiteSpace(tmpch0 = chars[pos])) { if (tmpch0 == (char)0xA) { OnNewLine(pos + 1); lineNoDelta++; } else if (tmpch0 == (char)0xD) { if (chars[pos + 1] == (char)0xA) { OnNewLine(pos + 2); lineNoDelta++; pos++; } else if (pos + 1 != _ps.charsUsed) { OnNewLine(pos + 1); lineNoDelta++; } else { _ps.charPos = pos; goto ReadData; } } pos++; } char tmpch1; int startNameCharSize = 0; if (_xmlCharType.IsStartNCNameSingleChar(tmpch1 = chars[pos])) { startNameCharSize = 1; } #if XML10_FIFTH_EDITION else if (pos + 1 < ps.charsUsed && xmlCharType.IsNCNameSurrogateChar(chars[pos + 1], tmpch1)) { startNameCharSize = 2; } #endif if (startNameCharSize == 0) { // element end if (tmpch1 == '>') { Debug.Assert(_curNode.type == XmlNodeType.Element); _ps.charPos = pos + 1; _parsingFunction = ParsingFunction.MoveToElementContent; goto End; } // empty element end else if (tmpch1 == '/') { Debug.Assert(_curNode.type == XmlNodeType.Element); if (pos + 1 == _ps.charsUsed) { goto ReadData; } if (chars[pos + 1] == '>') { _ps.charPos = pos + 2; _curNode.IsEmptyElement = true; _nextParsingFunction = _parsingFunction; _parsingFunction = ParsingFunction.PopEmptyElementContext; goto End; } else { ThrowUnexpectedToken(pos + 1, ">"); } } else if (pos == _ps.charsUsed) { goto ReadData; } else if (tmpch1 != ':' || _supportNamespaces) { Throw(pos, SR.Xml_BadStartNameChar, XmlException.BuildCharExceptionArgs(chars, _ps.charsUsed, pos)); } } if (pos == _ps.charPos) { ThrowExpectingWhitespace(pos); } _ps.charPos = pos; // save attribute name line position int attrNameLinePos = _ps.LinePos; #if DEBUG int attrNameLineNo = _ps.LineNo; #endif // parse attribute name int colonPos = -1; // PERF: we intentionally don't call ParseQName here to parse the element name unless a special // case occurs (like end of buffer, invalid name char) pos += startNameCharSize; // start name char has already been checked // parse attribute name ContinueParseName: char tmpch2; while (true) { if (_xmlCharType.IsNCNameSingleChar(tmpch2 = chars[pos])) { pos++; } #if XML10_FIFTH_EDITION else if (pos + 1 < ps.charsUsed && xmlCharType.IsNCNameSurrogateChar(chars[pos + 1], tmpch2)) { pos += 2; } #endif else { break; } } // colon -> save prefix end position and check next char if it's name start char if (tmpch2 == ':') { if (colonPos != -1) { if (_supportNamespaces) { Throw(pos, SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(':', '\0')); } else { pos++; goto ContinueParseName; } } else { colonPos = pos; pos++; if (_xmlCharType.IsStartNCNameSingleChar(chars[pos])) { pos++; goto ContinueParseName; } #if XML10_FIFTH_EDITION else if ( pos + 1 < ps.charsUsed && xmlCharType.IsNCNameSurrogateChar( chars[pos + 1], chars[pos] ) ) { pos += 2; goto ContinueParseName; } #endif // else fallback to full name parsing routine pos = ParseQName(out colonPos); chars = _ps.chars; } } else if (pos + 1 >= _ps.charsUsed) { pos = ParseQName(out colonPos); chars = _ps.chars; } attr = AddAttribute(pos, colonPos); attr.SetLineInfo(_ps.LineNo, attrNameLinePos); #if DEBUG Debug.Assert(attrNameLineNo == _ps.LineNo); #endif // parse equals and quote char; if (chars[pos] != '=') { _ps.charPos = pos; EatWhitespaces(null); pos = _ps.charPos; if (chars[pos] != '=') { ThrowUnexpectedToken("="); } } pos++; char quoteChar = chars[pos]; if (quoteChar != '"' && quoteChar != '\'') { _ps.charPos = pos; EatWhitespaces(null); pos = _ps.charPos; quoteChar = chars[pos]; if (quoteChar != '"' && quoteChar != '\'') { ThrowUnexpectedToken("\"", "'"); } } pos++; _ps.charPos = pos; attr.quoteChar = quoteChar; attr.SetLineInfo2(_ps.LineNo, _ps.LinePos); // parse attribute value char tmpch3; while (_xmlCharType.IsAttributeValueChar(tmpch3 = chars[pos])) { pos++; } if (tmpch3 == quoteChar) { #if DEBUG if (_normalize) { string val = new string(chars, _ps.charPos, pos - _ps.charPos); Debug.Assert(val == XmlComplianceUtil.CDataNormalize(val), "The attribute value is not CDATA normalized!"); } #endif attr.SetValue(chars, _ps.charPos, pos - _ps.charPos); pos++; _ps.charPos = pos; } else { ParseAttributeValueSlow(pos, quoteChar, attr); pos = _ps.charPos; chars = _ps.chars; } // handle special attributes: if (attr.prefix.Length == 0) { // default namespace declaration if (Ref.Equal(attr.localName, _xmlNs)) { OnDefaultNamespaceDecl(attr); } } else { // prefixed namespace declaration if (Ref.Equal(attr.prefix, _xmlNs)) { OnNamespaceDecl(attr); } // xml: attribute else if (Ref.Equal(attr.prefix, _xml)) { OnXmlReservedAttribute(attr); } } continue; ReadData: _ps.lineNo -= lineNoDelta; if (ReadData() != 0) { pos = _ps.charPos; chars = _ps.chars; } else { ThrowUnclosedElements(); } } End: if (_addDefaultAttributesAndNormalize) { AddDefaultAttributesAndNormalize(); } // lookup namespaces: element ElementNamespaceLookup(); // lookup namespaces: attributes if (_attrNeedNamespaceLookup) { AttributeNamespaceLookup(); _attrNeedNamespaceLookup = false; } // check duplicate attributes if (_attrDuplWalkCount >= MaxAttrDuplWalkCount) { AttributeDuplCheck(); } } private void ElementNamespaceLookup() { Debug.Assert(_curNode.type == XmlNodeType.Element); if (_curNode.prefix.Length == 0) { _curNode.ns = _xmlContext.defaultNamespace; } else { _curNode.ns = LookupNamespace(_curNode); } } private void AttributeNamespaceLookup() { for (int i = _index + 1; i < _index + _attrCount + 1; i++) { NodeData at = _nodes[i]; if (at.type == XmlNodeType.Attribute && at.prefix.Length > 0) { at.ns = LookupNamespace(at); } } } private void AttributeDuplCheck() { if (_attrCount < MaxAttrDuplWalkCount) { for (int i = _index + 1; i < _index + 1 + _attrCount; i++) { NodeData attr1 = _nodes[i]; for (int j = i + 1; j < _index + 1 + _attrCount; j++) { if (Ref.Equal(attr1.localName, _nodes[j].localName) && Ref.Equal(attr1.ns, _nodes[j].ns)) { Throw(SR.Xml_DupAttributeName, _nodes[j].GetNameWPrefix(_nameTable), _nodes[j].LineNo, _nodes[j].LinePos); } } } } else { if (_attrDuplSortingArray == null || _attrDuplSortingArray.Length < _attrCount) { _attrDuplSortingArray = new NodeData[_attrCount]; } Array.Copy(_nodes, _index + 1, _attrDuplSortingArray, 0, _attrCount); Array.Sort(_attrDuplSortingArray, 0, _attrCount); NodeData attr1 = _attrDuplSortingArray[0]; for (int i = 1; i < _attrCount; i++) { NodeData attr2 = _attrDuplSortingArray[i]; if (Ref.Equal(attr1.localName, attr2.localName) && Ref.Equal(attr1.ns, attr2.ns)) { Throw(SR.Xml_DupAttributeName, attr2.GetNameWPrefix(_nameTable), attr2.LineNo, attr2.LinePos); } attr1 = attr2; } } } private void OnDefaultNamespaceDecl(NodeData attr) { if (!_supportNamespaces) { return; } string ns = _nameTable.Add(attr.StringValue); attr.ns = _nameTable.Add(XmlReservedNs.NsXmlNs); if (!_curNode.xmlContextPushed) { PushXmlContext(); } _xmlContext.defaultNamespace = ns; AddNamespace(string.Empty, ns, attr); } private void OnNamespaceDecl(NodeData attr) { if (!_supportNamespaces) { return; } string ns = _nameTable.Add(attr.StringValue); if (ns.Length == 0) { Throw(SR.Xml_BadNamespaceDecl, attr.lineInfo2.lineNo, attr.lineInfo2.linePos - 1); } AddNamespace(attr.localName, ns, attr); } private void OnXmlReservedAttribute(NodeData attr) { switch (attr.localName) { // xml:space case "space": if (!_curNode.xmlContextPushed) { PushXmlContext(); } switch (XmlConvert.TrimString(attr.StringValue)) { case "preserve": _xmlContext.xmlSpace = XmlSpace.Preserve; break; case "default": _xmlContext.xmlSpace = XmlSpace.Default; break; default: Throw(SR.Xml_InvalidXmlSpace, attr.StringValue, attr.lineInfo.lineNo, attr.lineInfo.linePos); break; } break; // xml:lang case "lang": if (!_curNode.xmlContextPushed) { PushXmlContext(); } _xmlContext.xmlLang = attr.StringValue; break; } } private void ParseAttributeValueSlow(int curPos, char quoteChar, NodeData attr) { int pos = curPos; char[] chars = _ps.chars; int attributeBaseEntityId = _ps.entityId; int valueChunkStartPos = 0; LineInfo valueChunkLineInfo = new LineInfo(_ps.lineNo, _ps.LinePos); NodeData lastChunk = null; Debug.Assert(_stringBuilder.Length == 0); while (true) { // parse the rest of the attribute value while (_xmlCharType.IsAttributeValueChar(chars[pos])) { pos++; } if (pos - _ps.charPos > 0) { _stringBuilder.Append(chars, _ps.charPos, pos - _ps.charPos); _ps.charPos = pos; } if (chars[pos] == quoteChar && attributeBaseEntityId == _ps.entityId) { break; } else { switch (chars[pos]) { // eol case (char)0xA: pos++; OnNewLine(pos); if (_normalize) { _stringBuilder.Append((char)0x20); // CDATA normalization of 0xA _ps.charPos++; } continue; case (char)0xD: if (chars[pos + 1] == (char)0xA) { pos += 2; if (_normalize) { _stringBuilder.Append(_ps.eolNormalized ? "\u0020\u0020" : "\u0020"); // CDATA normalization of 0xD 0xA _ps.charPos = pos; } } else if (pos + 1 < _ps.charsUsed || _ps.isEof) { pos++; if (_normalize) { _stringBuilder.Append((char)0x20); // CDATA normalization of 0xD and 0xD 0xA _ps.charPos = pos; } } else { goto ReadData; } OnNewLine(pos); continue; // tab case (char)0x9: pos++; if (_normalize) { _stringBuilder.Append((char)0x20); // CDATA normalization of 0x9 _ps.charPos++; } continue; case '"': case '\'': case '>': pos++; continue; // attribute values cannot contain '<' case '<': Throw(pos, SR.Xml_BadAttributeChar, XmlException.BuildCharExceptionArgs('<', '\0')); break; // entity referece case '&': if (pos - _ps.charPos > 0) { _stringBuilder.Append(chars, _ps.charPos, pos - _ps.charPos); } _ps.charPos = pos; int enclosingEntityId = _ps.entityId; LineInfo entityLineInfo = new LineInfo(_ps.lineNo, _ps.LinePos + 1); switch (HandleEntityReference(true, EntityExpandType.All, out pos)) { case EntityType.CharacterDec: case EntityType.CharacterHex: case EntityType.CharacterNamed: break; case EntityType.Unexpanded: if (_parsingMode == ParsingMode.Full && _ps.entityId == attributeBaseEntityId) { // construct text value chunk int valueChunkLen = _stringBuilder.Length - valueChunkStartPos; if (valueChunkLen > 0) { NodeData textChunk = new NodeData(); textChunk.lineInfo = valueChunkLineInfo; textChunk.depth = attr.depth + 1; textChunk.SetValueNode(XmlNodeType.Text, _stringBuilder.ToString(valueChunkStartPos, valueChunkLen)); AddAttributeChunkToList(attr, textChunk, ref lastChunk); } // parse entity name _ps.charPos++; string entityName = ParseEntityName(); // construct entity reference chunk NodeData entityChunk = new NodeData(); entityChunk.lineInfo = entityLineInfo; entityChunk.depth = attr.depth + 1; entityChunk.SetNamedNode(XmlNodeType.EntityReference, entityName); AddAttributeChunkToList(attr, entityChunk, ref lastChunk); // append entity ref to the attribute value _stringBuilder.Append('&'); _stringBuilder.Append(entityName); _stringBuilder.Append(';'); // update info for the next attribute value chunk valueChunkStartPos = _stringBuilder.Length; valueChunkLineInfo.Set(_ps.LineNo, _ps.LinePos); _fullAttrCleanup = true; } else { _ps.charPos++; ParseEntityName(); } pos = _ps.charPos; break; case EntityType.ExpandedInAttribute: if (_parsingMode == ParsingMode.Full && enclosingEntityId == attributeBaseEntityId) { // construct text value chunk int valueChunkLen = _stringBuilder.Length - valueChunkStartPos; if (valueChunkLen > 0) { NodeData textChunk = new NodeData(); textChunk.lineInfo = valueChunkLineInfo; textChunk.depth = attr.depth + 1; textChunk.SetValueNode(XmlNodeType.Text, _stringBuilder.ToString(valueChunkStartPos, valueChunkLen)); AddAttributeChunkToList(attr, textChunk, ref lastChunk); } // construct entity reference chunk NodeData entityChunk = new NodeData(); entityChunk.lineInfo = entityLineInfo; entityChunk.depth = attr.depth + 1; entityChunk.SetNamedNode(XmlNodeType.EntityReference, _ps.entity.Name); AddAttributeChunkToList(attr, entityChunk, ref lastChunk); _fullAttrCleanup = true; // Note: info for the next attribute value chunk will be updated once we // get out of the expanded entity } pos = _ps.charPos; break; default: pos = _ps.charPos; break; } chars = _ps.chars; continue; default: // end of buffer if (pos == _ps.charsUsed) { goto ReadData; } // surrogate chars else { char ch = chars[pos]; if (XmlCharType.IsHighSurrogate(ch)) { if (pos + 1 == _ps.charsUsed) { goto ReadData; } pos++; if (XmlCharType.IsLowSurrogate(chars[pos])) { pos++; continue; } } ThrowInvalidChar(chars, _ps.charsUsed, pos); break; } } } ReadData: // read new characters into the buffer if (ReadData() == 0) { if (_ps.charsUsed - _ps.charPos > 0) { if (_ps.chars[_ps.charPos] != (char)0xD) { Debug.Fail("We should never get to this point."); Throw(SR.Xml_UnexpectedEOF1); } Debug.Assert(_ps.isEof); } else { if (!InEntity) { if (_fragmentType == XmlNodeType.Attribute) { if (attributeBaseEntityId != _ps.entityId) { Throw(SR.Xml_EntityRefNesting); } break; } Throw(SR.Xml_UnclosedQuote); } if (HandleEntityEnd(true)) { Debug.Fail("no EndEntity reporting while parsing attributes"); Throw(SR.Xml_InternalError); } // update info for the next attribute value chunk if (attributeBaseEntityId == _ps.entityId) { valueChunkStartPos = _stringBuilder.Length; valueChunkLineInfo.Set(_ps.LineNo, _ps.LinePos); } } } pos = _ps.charPos; chars = _ps.chars; } if (attr.nextAttrValueChunk != null) { // construct last text value chunk int valueChunkLen = _stringBuilder.Length - valueChunkStartPos; if (valueChunkLen > 0) { NodeData textChunk = new NodeData(); textChunk.lineInfo = valueChunkLineInfo; textChunk.depth = attr.depth + 1; textChunk.SetValueNode(XmlNodeType.Text, _stringBuilder.ToString(valueChunkStartPos, valueChunkLen)); AddAttributeChunkToList(attr, textChunk, ref lastChunk); } } _ps.charPos = pos + 1; attr.SetValue(_stringBuilder.ToString()); _stringBuilder.Length = 0; } private void AddAttributeChunkToList(NodeData attr, NodeData chunk, ref NodeData lastChunk) { if (lastChunk == null) { Debug.Assert(attr.nextAttrValueChunk == null); lastChunk = chunk; attr.nextAttrValueChunk = chunk; } else { lastChunk.nextAttrValueChunk = chunk; lastChunk = chunk; } } // Parses text or whitespace node. // Returns true if a node has been parsed and its data set to curNode. // Returns false when a whitespace has been parsed and ignored (according to current whitespace handling) or when parsing mode is not Full. // Also returns false if there is no text to be parsed. private bool ParseText() { int startPos; int endPos; int orChars = 0; // skip over the text if not in full parsing mode if (_parsingMode != ParsingMode.Full) { while (!ParseText(out startPos, out endPos, ref orChars)); goto IgnoredNode; } _curNode.SetLineInfo(_ps.LineNo, _ps.LinePos); Debug.Assert(_stringBuilder.Length == 0); // the whole value is in buffer if (ParseText(out startPos, out endPos, ref orChars)) { if (endPos - startPos == 0) { goto IgnoredNode; } XmlNodeType nodeType = GetTextNodeType(orChars); if (nodeType == XmlNodeType.None) { goto IgnoredNode; } Debug.Assert(endPos - startPos > 0); _curNode.SetValueNode(nodeType, _ps.chars, startPos, endPos - startPos); return true; } // only piece of the value was returned else { // V1 compatibility mode -> cache the whole value if (_v1Compat) { do { if (endPos - startPos > 0) { _stringBuilder.Append(_ps.chars, startPos, endPos - startPos); } } while (!ParseText(out startPos, out endPos, ref orChars)); if (endPos - startPos > 0) { _stringBuilder.Append(_ps.chars, startPos, endPos - startPos); } Debug.Assert(_stringBuilder.Length > 0); XmlNodeType nodeType = GetTextNodeType(orChars); if (nodeType == XmlNodeType.None) { _stringBuilder.Length = 0; goto IgnoredNode; } _curNode.SetValueNode(nodeType, _stringBuilder.ToString()); _stringBuilder.Length = 0; return true; } // V2 reader -> do not cache the whole value yet, read only up to 4kB to decide whether the value is a whitespace else { bool fullValue = false; // if it's a partial text value, not a whitespace -> return if (orChars > 0x20) { Debug.Assert(endPos - startPos > 0); _curNode.SetValueNode(XmlNodeType.Text, _ps.chars, startPos, endPos - startPos); _nextParsingFunction = _parsingFunction; _parsingFunction = ParsingFunction.PartialTextValue; return true; } // partial whitespace -> read more data (up to 4kB) to decide if it is a whitespace or a text node if (endPos - startPos > 0) { _stringBuilder.Append(_ps.chars, startPos, endPos - startPos); } do { fullValue = ParseText(out startPos, out endPos, ref orChars); if (endPos - startPos > 0) { _stringBuilder.Append(_ps.chars, startPos, endPos - startPos); } } while (!fullValue && orChars <= 0x20 && _stringBuilder.Length < MinWhitespaceLookahedCount); // determine the value node type XmlNodeType nodeType = (_stringBuilder.Length < MinWhitespaceLookahedCount) ? GetTextNodeType(orChars) : XmlNodeType.Text; if (nodeType == XmlNodeType.None) { // ignored whitespace -> skip over the rest of the value unless we already read it all _stringBuilder.Length = 0; if (!fullValue) { while (!ParseText(out startPos, out endPos, ref orChars)); } goto IgnoredNode; } // set value to curNode _curNode.SetValueNode(nodeType, _stringBuilder.ToString()); _stringBuilder.Length = 0; // change parsing state if the full value was not parsed if (!fullValue) { _nextParsingFunction = _parsingFunction; _parsingFunction = ParsingFunction.PartialTextValue; } return true; } } IgnoredNode: // ignored whitespace at the end of manually resolved entity if (_parsingFunction == ParsingFunction.ReportEndEntity) { SetupEndEntityNodeInContent(); _parsingFunction = _nextParsingFunction; return true; } else if (_parsingFunction == ParsingFunction.EntityReference) { _parsingFunction = _nextNextParsingFunction; ParseEntityReference(); return true; } return false; } // Parses a chunk of text starting at ps.charPos. // startPos .... start position of the text chunk that has been parsed (can differ from ps.charPos before the call) // endPos ...... end position of the text chunk that has been parsed (can differ from ps.charPos after the call) // ourOrChars .. all parsed character bigger or equal to 0x20 or-ed (|) into a single int. It can be used for whitespace detection // (the text has a non-whitespace character if outOrChars > 0x20). // Returns true when the whole value has been parsed. Return false when it needs to be called again to get a next chunk of value. private bool ParseText(out int startPos, out int endPos, ref int outOrChars) { char[] chars = _ps.chars; int pos = _ps.charPos; int rcount = 0; int rpos = -1; int orChars = outOrChars; char c; while (true) { // parse text content while (_xmlCharType.IsTextChar(c = chars[pos])) { orChars |= (int)c; pos++; } switch (c) { case (char)0x9: pos++; continue; // eol case (char)0xA: pos++; OnNewLine(pos); continue; case (char)0xD: if (chars[pos + 1] == (char)0xA) { if (!_ps.eolNormalized && _parsingMode == ParsingMode.Full) { if (pos - _ps.charPos > 0) { if (rcount == 0) { rcount = 1; rpos = pos; } else { ShiftBuffer(rpos + rcount, rpos, pos - rpos - rcount); rpos = pos - rcount; rcount++; } } else { _ps.charPos++; } } pos += 2; } else if (pos + 1 < _ps.charsUsed || _ps.isEof) { if (!_ps.eolNormalized) { chars[pos] = (char)0xA; // EOL normalization of 0xD } pos++; } else { goto ReadData; } OnNewLine(pos); continue; // some tag case '<': goto ReturnPartialValue; // entity reference case '&': // try to parse char entity inline int charRefEndPos, charCount; EntityType entityType; if ((charRefEndPos = ParseCharRefInline(pos, out charCount, out entityType)) > 0) { if (rcount > 0) { ShiftBuffer(rpos + rcount, rpos, pos - rpos - rcount); } rpos = pos - rcount; rcount += (charRefEndPos - pos - charCount); pos = charRefEndPos; if (!_xmlCharType.IsWhiteSpace(chars[charRefEndPos - charCount]) || (_v1Compat && entityType == EntityType.CharacterDec)) { orChars |= 0xFF; } } else { if (pos > _ps.charPos) { goto ReturnPartialValue; } switch (HandleEntityReference(false, EntityExpandType.All, out pos)) { case EntityType.Unexpanded: // make sure we will report EntityReference after the text node _nextParsingFunction = _parsingFunction; _parsingFunction = ParsingFunction.EntityReference; // end the value (returns nothing) goto NoValue; case EntityType.CharacterDec: if (!_v1Compat) { goto case EntityType.CharacterHex; } orChars |= 0xFF; break; case EntityType.CharacterHex: case EntityType.CharacterNamed: if (!_xmlCharType.IsWhiteSpace(_ps.chars[pos - 1])) { orChars |= 0xFF; } break; default: pos = _ps.charPos; break; } chars = _ps.chars; } continue; case ']': if (_ps.charsUsed - pos < 3 && !_ps.isEof) { goto ReadData; } if (chars[pos + 1] == ']' && chars[pos + 2] == '>') { Throw(pos, SR.Xml_CDATAEndInText); } orChars |= ']'; pos++; continue; default: // end of buffer if (pos == _ps.charsUsed) { goto ReadData; } // surrogate chars else { char ch = chars[pos]; if (XmlCharType.IsHighSurrogate(ch)) { if (pos + 1 == _ps.charsUsed) { goto ReadData; } pos++; if (XmlCharType.IsLowSurrogate(chars[pos])) { pos++; orChars |= ch; continue; } } int offset = pos - _ps.charPos; if (ZeroEndingStream(pos)) { chars = _ps.chars; pos = _ps.charPos + offset; goto ReturnPartialValue; } else { ThrowInvalidChar(_ps.chars, _ps.charsUsed, _ps.charPos + offset); } break; } } ReadData: if (pos > _ps.charPos) { goto ReturnPartialValue; } // read new characters into the buffer if (ReadData() == 0) { if (_ps.charsUsed - _ps.charPos > 0) { if (_ps.chars[_ps.charPos] != (char)0xD && _ps.chars[_ps.charPos] != ']') { Throw(SR.Xml_UnexpectedEOF1); } Debug.Assert(_ps.isEof); } else { if (!InEntity) { // end the value (returns nothing) goto NoValue; } if (HandleEntityEnd(true)) { // report EndEntity after the text node _nextParsingFunction = _parsingFunction; _parsingFunction = ParsingFunction.ReportEndEntity; // end the value (returns nothing) goto NoValue; } } } pos = _ps.charPos; chars = _ps.chars; continue; } NoValue: startPos = endPos = pos; return true; ReturnPartialValue: if (_parsingMode == ParsingMode.Full && rcount > 0) { ShiftBuffer(rpos + rcount, rpos, pos - rpos - rcount); } startPos = _ps.charPos; endPos = pos - rcount; _ps.charPos = pos; outOrChars = orChars; return c == '<'; } // When in ParsingState.PartialTextValue, this method parses and caches the rest of the value and stores it in curNode. private void FinishPartialValue() { Debug.Assert(_stringBuilder.Length == 0); Debug.Assert(_parsingFunction == ParsingFunction.PartialTextValue || (_parsingFunction == ParsingFunction.InReadValueChunk && _incReadState == IncrementalReadState.ReadValueChunk_OnPartialValue)); _curNode.CopyTo(_readValueOffset, _stringBuilder); int startPos; int endPos; int orChars = 0; while (!ParseText(out startPos, out endPos, ref orChars)) { _stringBuilder.Append(_ps.chars, startPos, endPos - startPos); } _stringBuilder.Append(_ps.chars, startPos, endPos - startPos); Debug.Assert(_stringBuilder.Length > 0); _curNode.SetValue(_stringBuilder.ToString()); _stringBuilder.Length = 0; } private void FinishOtherValueIterator() { switch (_parsingFunction) { case ParsingFunction.InReadAttributeValue: // do nothing, correct value is already in curNode break; case ParsingFunction.InReadValueChunk: if (_incReadState == IncrementalReadState.ReadValueChunk_OnPartialValue) { FinishPartialValue(); _incReadState = IncrementalReadState.ReadValueChunk_OnCachedValue; } else { if (_readValueOffset > 0) { _curNode.SetValue(_curNode.StringValue.Substring(_readValueOffset)); _readValueOffset = 0; } } break; case ParsingFunction.InReadContentAsBinary: case ParsingFunction.InReadElementContentAsBinary: switch (_incReadState) { case IncrementalReadState.ReadContentAsBinary_OnPartialValue: FinishPartialValue(); _incReadState = IncrementalReadState.ReadContentAsBinary_OnCachedValue; break; case IncrementalReadState.ReadContentAsBinary_OnCachedValue: if (_readValueOffset > 0) { _curNode.SetValue(_curNode.StringValue.Substring(_readValueOffset)); _readValueOffset = 0; } break; case IncrementalReadState.ReadContentAsBinary_End: _curNode.SetValue(string.Empty); break; } break; } } // When in ParsingState.PartialTextValue, this method skips over the rest of the partial value. [MethodImplAttribute(MethodImplOptions.NoInlining)] private void SkipPartialTextValue() { Debug.Assert(_parsingFunction == ParsingFunction.PartialTextValue || _parsingFunction == ParsingFunction.InReadValueChunk || _parsingFunction == ParsingFunction.InReadContentAsBinary || _parsingFunction == ParsingFunction.InReadElementContentAsBinary); int startPos; int endPos; int orChars = 0; _parsingFunction = _nextParsingFunction; while (!ParseText(out startPos, out endPos, ref orChars)); } private void FinishReadValueChunk() { Debug.Assert(_parsingFunction == ParsingFunction.InReadValueChunk); _readValueOffset = 0; if (_incReadState == IncrementalReadState.ReadValueChunk_OnPartialValue) { Debug.Assert((_index > 0) ? _nextParsingFunction == ParsingFunction.ElementContent : _nextParsingFunction == ParsingFunction.DocumentContent); SkipPartialTextValue(); } else { _parsingFunction = _nextParsingFunction; _nextParsingFunction = _nextNextParsingFunction; } } private void FinishReadContentAsBinary() { Debug.Assert(_parsingFunction == ParsingFunction.InReadContentAsBinary || _parsingFunction == ParsingFunction.InReadElementContentAsBinary); _readValueOffset = 0; if (_incReadState == IncrementalReadState.ReadContentAsBinary_OnPartialValue) { Debug.Assert((_index > 0) ? _nextParsingFunction == ParsingFunction.ElementContent : _nextParsingFunction == ParsingFunction.DocumentContent); SkipPartialTextValue(); } else { _parsingFunction = _nextParsingFunction; _nextParsingFunction = _nextNextParsingFunction; } if (_incReadState != IncrementalReadState.ReadContentAsBinary_End) { while (MoveToNextContentNode(true)); } } private void FinishReadElementContentAsBinary() { FinishReadContentAsBinary(); if (_curNode.type != XmlNodeType.EndElement) { Throw(SR.Xml_InvalidNodeType, _curNode.type.ToString()); } // move off the end element _outerReader.Read(); } private bool ParseRootLevelWhitespace() { Debug.Assert(_stringBuilder.Length == 0); XmlNodeType nodeType = GetWhitespaceType(); if (nodeType == XmlNodeType.None) { EatWhitespaces(null); if (_ps.chars[_ps.charPos] == '<' || _ps.charsUsed - _ps.charPos == 0 || ZeroEndingStream(_ps.charPos)) { return false; } } else { _curNode.SetLineInfo(_ps.LineNo, _ps.LinePos); EatWhitespaces(_stringBuilder); if (_ps.chars[_ps.charPos] == '<' || _ps.charsUsed - _ps.charPos == 0 || ZeroEndingStream(_ps.charPos)) { if (_stringBuilder.Length > 0) { _curNode.SetValueNode(nodeType, _stringBuilder.ToString()); _stringBuilder.Length = 0; return true; } return false; } } if (_xmlCharType.IsCharData(_ps.chars[_ps.charPos])) { Throw(SR.Xml_InvalidRootData); } else { ThrowInvalidChar(_ps.chars, _ps.charsUsed, _ps.charPos); } return false; } private void ParseEntityReference() { Debug.Assert(_ps.chars[_ps.charPos] == '&'); _ps.charPos++; _curNode.SetLineInfo(_ps.LineNo, _ps.LinePos); _curNode.SetNamedNode(XmlNodeType.EntityReference, ParseEntityName()); } private EntityType HandleEntityReference(bool isInAttributeValue, EntityExpandType expandType, out int charRefEndPos) { Debug.Assert(_ps.chars[_ps.charPos] == '&'); if (_ps.charPos + 1 == _ps.charsUsed) { if (ReadData() == 0) { Throw(SR.Xml_UnexpectedEOF1); } } // numeric characters reference if (_ps.chars[_ps.charPos + 1] == '#') { EntityType entityType; charRefEndPos = ParseNumericCharRef(expandType != EntityExpandType.OnlyGeneral, null, out entityType); Debug.Assert(entityType == EntityType.CharacterDec || entityType == EntityType.CharacterHex); return entityType; } // named reference else { // named character reference charRefEndPos = ParseNamedCharRef(expandType != EntityExpandType.OnlyGeneral, null); if (charRefEndPos >= 0) { return EntityType.CharacterNamed; } // general entity reference // NOTE: XmlValidatingReader compatibility mode: expand all entities in attribute values // general entity reference if (expandType == EntityExpandType.OnlyCharacter || (_entityHandling != EntityHandling.ExpandEntities && (!isInAttributeValue || !_validatingReaderCompatFlag))) { return EntityType.Unexpanded; } int endPos; _ps.charPos++; int savedLinePos = _ps.LinePos; try { endPos = ParseName(); } catch (XmlException) { Throw(SR.Xml_ErrorParsingEntityName, _ps.LineNo, savedLinePos); return EntityType.Skipped; } // check ';' if (_ps.chars[endPos] != ';') { ThrowUnexpectedToken(endPos, ";"); } int entityLinePos = _ps.LinePos; string entityName = _nameTable.Add(_ps.chars, _ps.charPos, endPos - _ps.charPos); _ps.charPos = endPos + 1; charRefEndPos = -1; EntityType entType = HandleGeneralEntityReference(entityName, isInAttributeValue, false, entityLinePos); _reportedBaseUri = _ps.baseUriStr; _reportedEncoding = _ps.encoding; return entType; } } // returns true == continue parsing // return false == unexpanded external entity, stop parsing and return private EntityType HandleGeneralEntityReference(string name, bool isInAttributeValue, bool pushFakeEntityIfNullResolver, int entityStartLinePos) { IDtdEntityInfo entity = null; if (_dtdInfo == null && _fragmentParserContext != null && _fragmentParserContext.HasDtdInfo && _dtdProcessing == DtdProcessing.Parse) { ParseDtdFromParserContext(); } if (_dtdInfo == null || ((entity = _dtdInfo.LookupEntity(name)) == null)) { if (_disableUndeclaredEntityCheck) { SchemaEntity schemaEntity = new SchemaEntity(new XmlQualifiedName(name), false); schemaEntity.Text = string.Empty; entity = schemaEntity; } else Throw(SR.Xml_UndeclaredEntity, name, _ps.LineNo, entityStartLinePos); } if (entity.IsUnparsedEntity) { if (_disableUndeclaredEntityCheck) { SchemaEntity schemaEntity = new SchemaEntity(new XmlQualifiedName(name), false); schemaEntity.Text = string.Empty; entity = schemaEntity; } else Throw(SR.Xml_UnparsedEntityRef, name, _ps.LineNo, entityStartLinePos); } if (_standalone && entity.IsDeclaredInExternal) { Throw(SR.Xml_ExternalEntityInStandAloneDocument, entity.Name, _ps.LineNo, entityStartLinePos); } if (entity.IsExternal) { if (isInAttributeValue) { Throw(SR.Xml_ExternalEntityInAttValue, name, _ps.LineNo, entityStartLinePos); return EntityType.Skipped; } if (_parsingMode == ParsingMode.SkipContent) { return EntityType.Skipped; } if (IsResolverNull) { if (pushFakeEntityIfNullResolver) { PushExternalEntity(entity); _curNode.entityId = _ps.entityId; return EntityType.FakeExpanded; } return EntityType.Skipped; } else { PushExternalEntity(entity); _curNode.entityId = _ps.entityId; return (isInAttributeValue && _validatingReaderCompatFlag) ? EntityType.ExpandedInAttribute : EntityType.Expanded; } } else { if (_parsingMode == ParsingMode.SkipContent) { return EntityType.Skipped; } PushInternalEntity(entity); _curNode.entityId = _ps.entityId; return (isInAttributeValue && _validatingReaderCompatFlag) ? EntityType.ExpandedInAttribute : EntityType.Expanded; } } private bool InEntity { get { return _parsingStatesStackTop >= 0; } } // return true if EndEntity node should be reported. The entity is stored in lastEntity. private bool HandleEntityEnd(bool checkEntityNesting) { if (_parsingStatesStackTop == -1) { Debug.Fail($"Unexpected parsing states stack top {_parsingStatesStackTop}"); Throw(SR.Xml_InternalError); } if (_ps.entityResolvedManually) { _index--; if (checkEntityNesting) { if (_ps.entityId != _nodes[_index].entityId) { Throw(SR.Xml_IncompleteEntity); } } _lastEntity = _ps.entity; // save last entity for the EndEntity node PopEntity(); return true; } else { if (checkEntityNesting) { if (_ps.entityId != _nodes[_index].entityId) { Throw(SR.Xml_IncompleteEntity); } } PopEntity(); _reportedEncoding = _ps.encoding; _reportedBaseUri = _ps.baseUriStr; return false; } } private void SetupEndEntityNodeInContent() { Debug.Assert(_lastEntity != null); _reportedEncoding = _ps.encoding; _reportedBaseUri = _ps.baseUriStr; _curNode = _nodes[_index]; Debug.Assert(_curNode.depth == _index); _curNode.SetNamedNode(XmlNodeType.EndEntity, _lastEntity.Name); _curNode.lineInfo.Set(_ps.lineNo, _ps.LinePos - 1); if (_index == 0 && _parsingFunction == ParsingFunction.ElementContent) { _parsingFunction = ParsingFunction.DocumentContent; } } private void SetupEndEntityNodeInAttribute() { _curNode = _nodes[_index + _attrCount + 1]; Debug.Assert(_curNode.type == XmlNodeType.EntityReference); Debug.Assert(Ref.Equal(_lastEntity.Name, _curNode.localName)); _curNode.lineInfo.linePos += _curNode.localName.Length; _curNode.type = XmlNodeType.EndEntity; } private bool ParsePI() { return ParsePI(null); } // Parses processing instruction; if piInDtdStringBuilder != null, the processing instruction is in DTD and // it will be saved in the passed string builder (target, whitespace & value). private bool ParsePI(StringBuilder piInDtdStringBuilder) { if (_parsingMode == ParsingMode.Full) { _curNode.SetLineInfo(_ps.LineNo, _ps.LinePos); } Debug.Assert(_stringBuilder.Length == 0); // parse target name int nameEndPos = ParseName(); string target = _nameTable.Add(_ps.chars, _ps.charPos, nameEndPos - _ps.charPos); if (string.Equals(target, "xml", StringComparison.OrdinalIgnoreCase)) { Throw(target.Equals("xml") ? SR.Xml_XmlDeclNotFirst : SR.Xml_InvalidPIName, target); } _ps.charPos = nameEndPos; if (piInDtdStringBuilder == null) { if (!_ignorePIs && _parsingMode == ParsingMode.Full) { _curNode.SetNamedNode(XmlNodeType.ProcessingInstruction, target); } } else { piInDtdStringBuilder.Append(target); } // check mandatory whitespace char ch = _ps.chars[_ps.charPos]; Debug.Assert(_ps.charPos < _ps.charsUsed); if (EatWhitespaces(piInDtdStringBuilder) == 0) { if (_ps.charsUsed - _ps.charPos < 2) { ReadData(); } if (ch != '?' || _ps.chars[_ps.charPos + 1] != '>') { Throw(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(_ps.chars, _ps.charsUsed, _ps.charPos)); } } // scan processing instruction value int startPos, endPos; if (ParsePIValue(out startPos, out endPos)) { if (piInDtdStringBuilder == null) { if (_ignorePIs) { return false; } if (_parsingMode == ParsingMode.Full) { _curNode.SetValue(_ps.chars, startPos, endPos - startPos); } } else { piInDtdStringBuilder.Append(_ps.chars, startPos, endPos - startPos); } } else { StringBuilder sb; if (piInDtdStringBuilder == null) { if (_ignorePIs || _parsingMode != ParsingMode.Full) { while (!ParsePIValue(out startPos, out endPos)); return false; } sb = _stringBuilder; Debug.Assert(_stringBuilder.Length == 0); } else { sb = piInDtdStringBuilder; } do { sb.Append(_ps.chars, startPos, endPos - startPos); } while (!ParsePIValue(out startPos, out endPos)); sb.Append(_ps.chars, startPos, endPos - startPos); if (piInDtdStringBuilder == null) { _curNode.SetValue(_stringBuilder.ToString()); _stringBuilder.Length = 0; } } return true; } private bool ParsePIValue(out int outStartPos, out int outEndPos) { // read new characters into the buffer if (_ps.charsUsed - _ps.charPos < 2) { if (ReadData() == 0) { Throw(_ps.charsUsed, SR.Xml_UnexpectedEOF, "PI"); } } int pos = _ps.charPos; char[] chars = _ps.chars; int rcount = 0; int rpos = -1; while (true) { char tmpch; while (_xmlCharType.IsTextChar(tmpch = chars[pos]) && tmpch != '?') { pos++; } switch (chars[pos]) { // possibly end of PI case '?': if (chars[pos + 1] == '>') { if (rcount > 0) { Debug.Assert(!_ps.eolNormalized); ShiftBuffer(rpos + rcount, rpos, pos - rpos - rcount); outEndPos = pos - rcount; } else { outEndPos = pos; } outStartPos = _ps.charPos; _ps.charPos = pos + 2; return true; } else if (pos + 1 == _ps.charsUsed) { goto ReturnPartial; } else { pos++; continue; } // eol case (char)0xA: pos++; OnNewLine(pos); continue; case (char)0xD: if (chars[pos + 1] == (char)0xA) { if (!_ps.eolNormalized && _parsingMode == ParsingMode.Full) { // EOL normalization of 0xD 0xA if (pos - _ps.charPos > 0) { if (rcount == 0) { rcount = 1; rpos = pos; } else { ShiftBuffer(rpos + rcount, rpos, pos - rpos - rcount); rpos = pos - rcount; rcount++; } } else { _ps.charPos++; } } pos += 2; } else if (pos + 1 < _ps.charsUsed || _ps.isEof) { if (!_ps.eolNormalized) { chars[pos] = (char)0xA; // EOL normalization of 0xD } pos++; } else { goto ReturnPartial; } OnNewLine(pos); continue; case '<': case '&': case ']': case (char)0x9: pos++; continue; default: // end of buffer if (pos == _ps.charsUsed) { goto ReturnPartial; } // surrogate characters else { char ch = chars[pos]; if (XmlCharType.IsHighSurrogate(ch)) { if (pos + 1 == _ps.charsUsed) { goto ReturnPartial; } pos++; if (XmlCharType.IsLowSurrogate(chars[pos])) { pos++; continue; } } ThrowInvalidChar(chars, _ps.charsUsed, pos); break; } } } ReturnPartial: if (rcount > 0) { ShiftBuffer(rpos + rcount, rpos, pos - rpos - rcount); outEndPos = pos - rcount; } else { outEndPos = pos; } outStartPos = _ps.charPos; _ps.charPos = pos; return false; } private bool ParseComment() { if (_ignoreComments) { ParsingMode oldParsingMode = _parsingMode; _parsingMode = ParsingMode.SkipNode; ParseCDataOrComment(XmlNodeType.Comment); _parsingMode = oldParsingMode; return false; } else { ParseCDataOrComment(XmlNodeType.Comment); return true; } } private void ParseCData() { ParseCDataOrComment(XmlNodeType.CDATA); } // Parses CDATA section or comment private void ParseCDataOrComment(XmlNodeType type) { int startPos, endPos; if (_parsingMode == ParsingMode.Full) { _curNode.SetLineInfo(_ps.LineNo, _ps.LinePos); Debug.Assert(_stringBuilder.Length == 0); if (ParseCDataOrComment(type, out startPos, out endPos)) { _curNode.SetValueNode(type, _ps.chars, startPos, endPos - startPos); } else { do { _stringBuilder.Append(_ps.chars, startPos, endPos - startPos); } while (!ParseCDataOrComment(type, out startPos, out endPos)); _stringBuilder.Append(_ps.chars, startPos, endPos - startPos); _curNode.SetValueNode(type, _stringBuilder.ToString()); _stringBuilder.Length = 0; } } else { while (!ParseCDataOrComment(type, out startPos, out endPos)); } } // Parses a chunk of CDATA section or comment. Returns true when the end of CDATA or comment was reached. private bool ParseCDataOrComment(XmlNodeType type, out int outStartPos, out int outEndPos) { if (_ps.charsUsed - _ps.charPos < 3) { // read new characters into the buffer if (ReadData() == 0) { Throw(SR.Xml_UnexpectedEOF, (type == XmlNodeType.Comment) ? "Comment" : "CDATA"); } } int pos = _ps.charPos; char[] chars = _ps.chars; int rcount = 0; int rpos = -1; char stopChar = (type == XmlNodeType.Comment) ? '-' : ']'; while (true) { char tmpch; while (_xmlCharType.IsTextChar(tmpch = chars[pos]) && tmpch != stopChar) { pos++; } // possibly end of comment or cdata section if (chars[pos] == stopChar) { if (chars[pos + 1] == stopChar) { if (chars[pos + 2] == '>') { if (rcount > 0) { Debug.Assert(!_ps.eolNormalized); ShiftBuffer(rpos + rcount, rpos, pos - rpos - rcount); outEndPos = pos - rcount; } else { outEndPos = pos; } outStartPos = _ps.charPos; _ps.charPos = pos + 3; return true; } else if (pos + 2 == _ps.charsUsed) { goto ReturnPartial; } else if (type == XmlNodeType.Comment) { Throw(pos, SR.Xml_InvalidCommentChars); } } else if (pos + 1 == _ps.charsUsed) { goto ReturnPartial; } pos++; continue; } else { switch (chars[pos]) { // eol case (char)0xA: pos++; OnNewLine(pos); continue; case (char)0xD: if (chars[pos + 1] == (char)0xA) { // EOL normalization of 0xD 0xA - shift the buffer if (!_ps.eolNormalized && _parsingMode == ParsingMode.Full) { if (pos - _ps.charPos > 0) { if (rcount == 0) { rcount = 1; rpos = pos; } else { ShiftBuffer(rpos + rcount, rpos, pos - rpos - rcount); rpos = pos - rcount; rcount++; } } else { _ps.charPos++; } } pos += 2; } else if (pos + 1 < _ps.charsUsed || _ps.isEof) { if (!_ps.eolNormalized) { chars[pos] = (char)0xA; // EOL normalization of 0xD } pos++; } else { goto ReturnPartial; } OnNewLine(pos); continue; case '<': case '&': case ']': case (char)0x9: pos++; continue; default: // end of buffer if (pos == _ps.charsUsed) { goto ReturnPartial; } // surrogate characters char ch = chars[pos]; if (XmlCharType.IsHighSurrogate(ch)) { if (pos + 1 == _ps.charsUsed) { goto ReturnPartial; } pos++; if (XmlCharType.IsLowSurrogate(chars[pos])) { pos++; continue; } } ThrowInvalidChar(chars, _ps.charsUsed, pos); break; } } ReturnPartial: if (rcount > 0) { ShiftBuffer(rpos + rcount, rpos, pos - rpos - rcount); outEndPos = pos - rcount; } else { outEndPos = pos; } outStartPos = _ps.charPos; _ps.charPos = pos; return false; // false == parsing of comment or CData section is not finished yet, must be called again } } // Parses DOCTYPE declaration private bool ParseDoctypeDecl() { if (_dtdProcessing == DtdProcessing.Prohibit) { ThrowWithoutLineInfo(_v1Compat ? SR.Xml_DtdIsProhibited : SR.Xml_DtdIsProhibitedEx); } // parse 'DOCTYPE' while (_ps.charsUsed - _ps.charPos < 8) { if (ReadData() == 0) { Throw(SR.Xml_UnexpectedEOF, "DOCTYPE"); } } if (!XmlConvert.StrEqual(_ps.chars, _ps.charPos, 7, "DOCTYPE")) { ThrowUnexpectedToken((!_rootElementParsed && _dtdInfo == null) ? "DOCTYPE" : "<!--"); } if (!_xmlCharType.IsWhiteSpace(_ps.chars[_ps.charPos + 7])) { ThrowExpectingWhitespace(_ps.charPos + 7); } if (_dtdInfo != null) { Throw(_ps.charPos - 2, SR.Xml_MultipleDTDsProvided); // position just before <!DOCTYPE } if (_rootElementParsed) { Throw(_ps.charPos - 2, SR.Xml_DtdAfterRootElement); } _ps.charPos += 8; EatWhitespaces(null); if (_dtdProcessing == DtdProcessing.Parse) { _curNode.SetLineInfo(_ps.LineNo, _ps.LinePos); ParseDtd(); _nextParsingFunction = _parsingFunction; _parsingFunction = ParsingFunction.ResetAttributesRootLevel; return true; } // Skip DTD else { Debug.Assert(_dtdProcessing == DtdProcessing.Ignore); SkipDtd(); return false; } } private void ParseDtd() { IDtdParser dtdParser = DtdParser.Create(); _dtdInfo = dtdParser.ParseInternalDtd(new DtdParserProxy(this), true); if ((_validatingReaderCompatFlag || !_v1Compat) && (_dtdInfo.HasDefaultAttributes || _dtdInfo.HasNonCDataAttributes)) { _addDefaultAttributesAndNormalize = true; } _curNode.SetNamedNode(XmlNodeType.DocumentType, _dtdInfo.Name.ToString(), string.Empty, null); _curNode.SetValue(_dtdInfo.InternalDtdSubset); } private void SkipDtd() { int colonPos; // parse dtd name int pos = ParseQName(out colonPos); _ps.charPos = pos; // check whitespace EatWhitespaces(null); // PUBLIC Id if (_ps.chars[_ps.charPos] == 'P') { // make sure we have enough characters while (_ps.charsUsed - _ps.charPos < 6) { if (ReadData() == 0) { Throw(SR.Xml_UnexpectedEOF1); } } // check 'PUBLIC' if (!XmlConvert.StrEqual(_ps.chars, _ps.charPos, 6, "PUBLIC")) { ThrowUnexpectedToken("PUBLIC"); } _ps.charPos += 6; // check whitespace if (EatWhitespaces(null) == 0) { ThrowExpectingWhitespace(_ps.charPos); } // parse PUBLIC value SkipPublicOrSystemIdLiteral(); // check whitespace if (EatWhitespaces(null) == 0) { ThrowExpectingWhitespace(_ps.charPos); } // parse SYSTEM value SkipPublicOrSystemIdLiteral(); EatWhitespaces(null); } else if (_ps.chars[_ps.charPos] == 'S') { // make sure we have enough characters while (_ps.charsUsed - _ps.charPos < 6) { if (ReadData() == 0) { Throw(SR.Xml_UnexpectedEOF1); } } // check 'SYSTEM' if (!XmlConvert.StrEqual(_ps.chars, _ps.charPos, 6, "SYSTEM")) { ThrowUnexpectedToken("SYSTEM"); } _ps.charPos += 6; // check whitespace if (EatWhitespaces(null) == 0) { ThrowExpectingWhitespace(_ps.charPos); } // parse SYSTEM value SkipPublicOrSystemIdLiteral(); EatWhitespaces(null); } else if (_ps.chars[_ps.charPos] != '[' && _ps.chars[_ps.charPos] != '>') { Throw(SR.Xml_ExpectExternalOrClose); } // internal DTD if (_ps.chars[_ps.charPos] == '[') { _ps.charPos++; SkipUntil(']', true); EatWhitespaces(null); if (_ps.chars[_ps.charPos] != '>') { ThrowUnexpectedToken(">"); } } else if (_ps.chars[_ps.charPos] == '>') { _curNode.SetValue(string.Empty); } else { Throw(SR.Xml_ExpectSubOrClose); } _ps.charPos++; } private void SkipPublicOrSystemIdLiteral() { // check quote char char quoteChar = _ps.chars[_ps.charPos]; if (quoteChar != '"' && quoteChar != '\'') { ThrowUnexpectedToken("\"", "'"); } _ps.charPos++; SkipUntil(quoteChar, false); } private void SkipUntil(char stopChar, bool recognizeLiterals) { bool inLiteral = false; bool inComment = false; bool inPI = false; char literalQuote = '"'; char[] chars = _ps.chars; int pos = _ps.charPos; while (true) { char ch; while (_xmlCharType.IsAttributeValueChar(ch = chars[pos]) && chars[pos] != stopChar && ch != '-' && ch != '?') { pos++; } // closing stopChar outside of literal and ignore/include sections -> save value & return if (ch == stopChar && !inLiteral) { _ps.charPos = pos + 1; return; } // handle the special character _ps.charPos = pos; switch (ch) { // eol case (char)0xA: pos++; OnNewLine(pos); continue; case (char)0xD: if (chars[pos + 1] == (char)0xA) { pos += 2; } else if (pos + 1 < _ps.charsUsed || _ps.isEof) { pos++; } else { goto ReadData; } OnNewLine(pos); continue; // comment, PI case '<': // processing instruction if (chars[pos + 1] == '?') { if (recognizeLiterals && !inLiteral && !inComment) { inPI = true; pos += 2; continue; } } // comment else if (chars[pos + 1] == '!') { if (pos + 3 >= _ps.charsUsed && !_ps.isEof) { goto ReadData; } if (chars[pos + 2] == '-' && chars[pos + 3] == '-') { if (recognizeLiterals && !inLiteral && !inPI) { inComment = true; pos += 4; continue; } } } // need more data else if (pos + 1 >= _ps.charsUsed && !_ps.isEof) { goto ReadData; } pos++; continue; case '-': // end of comment if (inComment) { if (pos + 2 >= _ps.charsUsed && !_ps.isEof) { goto ReadData; } if (chars[pos + 1] == '-' && chars[pos + 2] == '>') { inComment = false; pos += 2; continue; } } pos++; continue; case '?': // end of processing instruction if (inPI) { if (pos + 1 >= _ps.charsUsed && !_ps.isEof) { goto ReadData; } if (chars[pos + 1] == '>') { inPI = false; pos += 1; continue; } } pos++; continue; case (char)0x9: case '>': case ']': case '&': pos++; continue; case '"': case '\'': if (inLiteral) { if (literalQuote == ch) { inLiteral = false; } } else { if (recognizeLiterals && !inComment && !inPI) { inLiteral = true; literalQuote = ch; } } pos++; continue; default: // end of buffer if (pos == _ps.charsUsed) { goto ReadData; } // surrogate chars else { char tmpCh = chars[pos]; if (XmlCharType.IsHighSurrogate(tmpCh)) { if (pos + 1 == _ps.charsUsed) { goto ReadData; } pos++; if (XmlCharType.IsLowSurrogate(chars[pos])) { pos++; continue; } } ThrowInvalidChar(chars, _ps.charsUsed, pos); break; } } ReadData: // read new characters into the buffer if (ReadData() == 0) { if (_ps.charsUsed - _ps.charPos > 0) { if (_ps.chars[_ps.charPos] != (char)0xD) { Debug.Fail("We should never get to this point."); Throw(SR.Xml_UnexpectedEOF1); } Debug.Assert(_ps.isEof); } else { Throw(SR.Xml_UnexpectedEOF1); } } chars = _ps.chars; pos = _ps.charPos; } } private int EatWhitespaces(StringBuilder sb) { int pos = _ps.charPos; int wsCount = 0; char[] chars = _ps.chars; while (true) { while (true) { switch (chars[pos]) { case (char)0xA: pos++; OnNewLine(pos); continue; case (char)0xD: if (chars[pos + 1] == (char)0xA) { int tmp1 = pos - _ps.charPos; if (sb != null && !_ps.eolNormalized) { if (tmp1 > 0) { sb.Append(chars, _ps.charPos, tmp1); wsCount += tmp1; } _ps.charPos = pos + 1; } pos += 2; } else if (pos + 1 < _ps.charsUsed || _ps.isEof) { if (!_ps.eolNormalized) { chars[pos] = (char)0xA; // EOL normalization of 0xD } pos++; } else { goto ReadData; } OnNewLine(pos); continue; case (char)0x9: case (char)0x20: pos++; continue; default: if (pos == _ps.charsUsed) { goto ReadData; } else { int tmp2 = pos - _ps.charPos; if (tmp2 > 0) { if (sb != null) { sb.Append(_ps.chars, _ps.charPos, tmp2); } _ps.charPos = pos; wsCount += tmp2; } return wsCount; } } } ReadData: int tmp3 = pos - _ps.charPos; if (tmp3 > 0) { if (sb != null) { sb.Append(_ps.chars, _ps.charPos, tmp3); } _ps.charPos = pos; wsCount += tmp3; } if (ReadData() == 0) { if (_ps.charsUsed - _ps.charPos == 0) { return wsCount; } if (_ps.chars[_ps.charPos] != (char)0xD) { Debug.Fail("We should never get to this point."); Throw(SR.Xml_UnexpectedEOF1); } Debug.Assert(_ps.isEof); } pos = _ps.charPos; chars = _ps.chars; } } private int ParseCharRefInline(int startPos, out int charCount, out EntityType entityType) { Debug.Assert(_ps.chars[startPos] == '&'); if (_ps.chars[startPos + 1] == '#') { return ParseNumericCharRefInline(startPos, true, null, out charCount, out entityType); } else { charCount = 1; entityType = EntityType.CharacterNamed; return ParseNamedCharRefInline(startPos, true, null); } } // Parses numeric character entity reference (e.g. &#32; &#x20;). // - replaces the last one or two character of the entity reference (';' and the character before) with the referenced // character or surrogates pair (if expand == true) // - returns position of the end of the character reference, that is of the character next to the original ';' // - if (expand == true) then ps.charPos is changed to point to the replaced character private int ParseNumericCharRef(bool expand, StringBuilder internalSubsetBuilder, out EntityType entityType) { while (true) { int newPos; int charCount; switch (newPos = ParseNumericCharRefInline(_ps.charPos, expand, internalSubsetBuilder, out charCount, out entityType)) { case -2: // read new characters in the buffer if (ReadData() == 0) { Throw(SR.Xml_UnexpectedEOF); } Debug.Assert(_ps.chars[_ps.charPos] == '&'); continue; default: if (expand) { _ps.charPos = newPos - charCount; } return newPos; } } } // Parses numeric character entity reference (e.g. &#32; &#x20;). // Returns -2 if more data is needed in the buffer // Otherwise // - replaces the last one or two character of the entity reference (';' and the character before) with the referenced // character or surrogates pair (if expand == true) // - returns position of the end of the character reference, that is of the character next to the original ';' private int ParseNumericCharRefInline(int startPos, bool expand, StringBuilder internalSubsetBuilder, out int charCount, out EntityType entityType) { Debug.Assert(_ps.chars[startPos] == '&' && _ps.chars[startPos + 1] == '#'); int val; int pos; char[] chars; val = 0; string badDigitExceptionString = null; chars = _ps.chars; pos = startPos + 2; charCount = 0; int digitPos = 0; try { if (chars[pos] == 'x') { pos++; digitPos = pos; badDigitExceptionString = SR.Xml_BadHexEntity; while (true) { char ch = chars[pos]; if (ch >= '0' && ch <= '9') val = checked(val * 16 + ch - '0'); else if (ch >= 'a' && ch <= 'f') val = checked(val * 16 + 10 + ch - 'a'); else if (ch >= 'A' && ch <= 'F') val = checked(val * 16 + 10 + ch - 'A'); else break; pos++; } entityType = EntityType.CharacterHex; } else if (pos < _ps.charsUsed) { digitPos = pos; badDigitExceptionString = SR.Xml_BadDecimalEntity; while (chars[pos] >= '0' && chars[pos] <= '9') { val = checked(val * 10 + chars[pos] - '0'); pos++; } entityType = EntityType.CharacterDec; } else { // need more data in the buffer entityType = EntityType.Skipped; return -2; } } catch (OverflowException e) { _ps.charPos = pos; entityType = EntityType.Skipped; Throw(SR.Xml_CharEntityOverflow, (string)null, e); } if (chars[pos] != ';' || digitPos == pos) { if (pos == _ps.charsUsed) { // need more data in the buffer return -2; } else { Throw(pos, badDigitExceptionString); } } // simple character if (val <= char.MaxValue) { char ch = (char)val; if (!_xmlCharType.IsCharData(ch) && ((_v1Compat && _normalize) || (!_v1Compat && _checkCharacters))) { Throw((_ps.chars[startPos + 2] == 'x') ? startPos + 3 : startPos + 2, SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(ch, '\0')); } if (expand) { if (internalSubsetBuilder != null) { internalSubsetBuilder.Append(_ps.chars, _ps.charPos, pos - _ps.charPos + 1); } chars[pos] = ch; } charCount = 1; return pos + 1; } // surrogate else { char low, high; XmlCharType.SplitSurrogateChar(val, out low, out high); if (_normalize) { if (XmlCharType.IsHighSurrogate(high)) { if (XmlCharType.IsLowSurrogate(low)) { goto Return; } } Throw((_ps.chars[startPos + 2] == 'x') ? startPos + 3 : startPos + 2, SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(high, low)); } Return: Debug.Assert(pos > 0); if (expand) { if (internalSubsetBuilder != null) { internalSubsetBuilder.Append(_ps.chars, _ps.charPos, pos - _ps.charPos + 1); } chars[pos - 1] = (char)high; chars[pos] = (char)low; } charCount = 2; return pos + 1; } } // Parses named character entity reference (&amp; &apos; &lt; &gt; &quot;). // Returns -1 if the reference is not a character entity reference. // Otherwise // - replaces the last character of the entity reference (';') with the referenced character (if expand == true) // - returns position of the end of the character reference, that is of the character next to the original ';' // - if (expand == true) then ps.charPos is changed to point to the replaced character private int ParseNamedCharRef(bool expand, StringBuilder internalSubsetBuilder) { while (true) { int newPos; switch (newPos = ParseNamedCharRefInline(_ps.charPos, expand, internalSubsetBuilder)) { case -1: return -1; case -2: // read new characters in the buffer if (ReadData() == 0) { return -1; } Debug.Assert(_ps.chars[_ps.charPos] == '&'); continue; default: if (expand) { _ps.charPos = newPos - 1; } return newPos; } } } // Parses named character entity reference (&amp; &apos; &lt; &gt; &quot;). // Returns -1 if the reference is not a character entity reference. // Returns -2 if more data is needed in the buffer // Otherwise // - replaces the last character of the entity reference (';') with the referenced character (if expand == true) // - returns position of the end of the character reference, that is of the character next to the original ';' private int ParseNamedCharRefInline(int startPos, bool expand, StringBuilder internalSubsetBuilder) { Debug.Assert(startPos < _ps.charsUsed); Debug.Assert(_ps.chars[startPos] == '&'); Debug.Assert(_ps.chars[startPos + 1] != '#'); int pos = startPos + 1; char[] chars = _ps.chars; char ch; switch (chars[pos]) { // &apos; or &amp; case 'a': pos++; // &amp; if (chars[pos] == 'm') { if (_ps.charsUsed - pos >= 3) { if (chars[pos + 1] == 'p' && chars[pos + 2] == ';') { pos += 3; ch = '&'; goto FoundCharRef; } else { return -1; } } } // &apos; else if (chars[pos] == 'p') { if (_ps.charsUsed - pos >= 4) { if (chars[pos + 1] == 'o' && chars[pos + 2] == 's' && chars[pos + 3] == ';') { pos += 4; ch = '\''; goto FoundCharRef; } else { return -1; } } } else if (pos < _ps.charsUsed) { return -1; } break; // &guot; case 'q': if (_ps.charsUsed - pos >= 5) { if (chars[pos + 1] == 'u' && chars[pos + 2] == 'o' && chars[pos + 3] == 't' && chars[pos + 4] == ';') { pos += 5; ch = '"'; goto FoundCharRef; } else { return -1; } } break; // &lt; case 'l': if (_ps.charsUsed - pos >= 3) { if (chars[pos + 1] == 't' && chars[pos + 2] == ';') { pos += 3; ch = '<'; goto FoundCharRef; } else { return -1; } } break; // &gt; case 'g': if (_ps.charsUsed - pos >= 3) { if (chars[pos + 1] == 't' && chars[pos + 2] == ';') { pos += 3; ch = '>'; goto FoundCharRef; } else { return -1; } } break; default: return -1; } // need more data in the buffer return -2; FoundCharRef: Debug.Assert(pos > 0); if (expand) { if (internalSubsetBuilder != null) { internalSubsetBuilder.Append(_ps.chars, _ps.charPos, pos - _ps.charPos); } _ps.chars[pos - 1] = ch; } return pos; } private int ParseName() { int colonPos; return ParseQName(false, 0, out colonPos); } private int ParseQName(out int colonPos) { return ParseQName(true, 0, out colonPos); } private int ParseQName(bool isQName, int startOffset, out int colonPos) { int colonOffset = -1; int pos = _ps.charPos + startOffset; ContinueStartName: char[] chars = _ps.chars; // start name char if (_xmlCharType.IsStartNCNameSingleChar(chars[pos])) { pos++; } #if XML10_FIFTH_EDITION else if (pos + 1 < ps.charsUsed && xmlCharType.IsNCNameSurrogateChar(chars[pos + 1], chars[pos])) { pos += 2; } #endif else { if (pos + 1 >= _ps.charsUsed) { if (ReadDataInName(ref pos)) { goto ContinueStartName; } Throw(pos, SR.Xml_UnexpectedEOF, "Name"); } if (chars[pos] != ':' || _supportNamespaces) { Throw(pos, SR.Xml_BadStartNameChar, XmlException.BuildCharExceptionArgs(chars, _ps.charsUsed, pos)); } } ContinueName: // parse name while (true) { if (_xmlCharType.IsNCNameSingleChar(chars[pos])) { pos++; } #if XML10_FIFTH_EDITION else if ( pos + 1 < ps.charsUsed && xmlCharType.IsNCNameSurrogateChar( chars[pos + 1], chars[pos] ) ) { pos += 2; } #endif else { break; } } // colon if (chars[pos] == ':') { if (_supportNamespaces) { if (colonOffset != -1 || !isQName) { Throw(pos, SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(':', '\0')); } colonOffset = pos - _ps.charPos; pos++; goto ContinueStartName; } else { colonOffset = pos - _ps.charPos; pos++; goto ContinueName; } } // end of buffer else if (pos == _ps.charsUsed #if XML10_FIFTH_EDITION || ( pos + 1 == ps.charsUsed && xmlCharType.IsNCNameHighSurrogateChar( chars[pos] ) ) #endif ) { if (ReadDataInName(ref pos)) { chars = _ps.chars; goto ContinueName; } Throw(pos, SR.Xml_UnexpectedEOF, "Name"); } // end of name colonPos = (colonOffset == -1) ? -1 : _ps.charPos + colonOffset; return pos; } private bool ReadDataInName(ref int pos) { int offset = pos - _ps.charPos; bool newDataRead = (ReadData() != 0); pos = _ps.charPos + offset; return newDataRead; } private string ParseEntityName() { int endPos; try { endPos = ParseName(); } catch (XmlException) { Throw(SR.Xml_ErrorParsingEntityName); return null; } // check ';' if (_ps.chars[endPos] != ';') { Throw(SR.Xml_ErrorParsingEntityName); } string entityName = _nameTable.Add(_ps.chars, _ps.charPos, endPos - _ps.charPos); _ps.charPos = endPos + 1; return entityName; } private NodeData AddNode(int nodeIndex, int nodeDepth) { Debug.Assert(nodeIndex < _nodes.Length); Debug.Assert(_nodes[_nodes.Length - 1] == null); NodeData n = _nodes[nodeIndex]; if (n != null) { n.depth = nodeDepth; return n; } return AllocNode(nodeIndex, nodeDepth); } private NodeData AllocNode(int nodeIndex, int nodeDepth) { Debug.Assert(nodeIndex < _nodes.Length); if (nodeIndex >= _nodes.Length - 1) { NodeData[] newNodes = new NodeData[_nodes.Length * 2]; Array.Copy(_nodes, newNodes, _nodes.Length); _nodes = newNodes; } Debug.Assert(nodeIndex < _nodes.Length); NodeData node = _nodes[nodeIndex]; if (node == null) { node = new NodeData(); _nodes[nodeIndex] = node; } node.depth = nodeDepth; return node; } private NodeData AddAttributeNoChecks(string name, int attrDepth) { NodeData newAttr = AddNode(_index + _attrCount + 1, attrDepth); newAttr.SetNamedNode(XmlNodeType.Attribute, _nameTable.Add(name)); _attrCount++; return newAttr; } private NodeData AddAttribute(int endNamePos, int colonPos) { // setup attribute name if (colonPos == -1 || !_supportNamespaces) { string localName = _nameTable.Add(_ps.chars, _ps.charPos, endNamePos - _ps.charPos); return AddAttribute(localName, string.Empty, localName); } else { _attrNeedNamespaceLookup = true; int startPos = _ps.charPos; int prefixLen = colonPos - startPos; if (prefixLen == _lastPrefix.Length && XmlConvert.StrEqual(_ps.chars, startPos, prefixLen, _lastPrefix)) { return AddAttribute(_nameTable.Add(_ps.chars, colonPos + 1, endNamePos - colonPos - 1), _lastPrefix, null); } else { string prefix = _nameTable.Add(_ps.chars, startPos, prefixLen); _lastPrefix = prefix; return AddAttribute(_nameTable.Add(_ps.chars, colonPos + 1, endNamePos - colonPos - 1), prefix, null); } } } private NodeData AddAttribute(string localName, string prefix, string nameWPrefix) { NodeData newAttr = AddNode(_index + _attrCount + 1, _index + 1); // set attribute name newAttr.SetNamedNode(XmlNodeType.Attribute, localName, prefix, nameWPrefix); // pre-check attribute for duplicate: hash by first local name char int attrHash = 1 << (localName[0] & 0x1F); if ((_attrHashtable & attrHash) == 0) { _attrHashtable |= attrHash; } else { // there are probably 2 attributes beginning with the same letter -> check all previous // attributes if (_attrDuplWalkCount < MaxAttrDuplWalkCount) { _attrDuplWalkCount++; for (int i = _index + 1; i < _index + _attrCount + 1; i++) { NodeData attr = _nodes[i]; Debug.Assert(attr.type == XmlNodeType.Attribute); if (Ref.Equal(attr.localName, newAttr.localName)) { _attrDuplWalkCount = MaxAttrDuplWalkCount; break; } } } } _attrCount++; return newAttr; } private void PopElementContext() { // pop namespace context _namespaceManager.PopScope(); // pop xml context if (_curNode.xmlContextPushed) { PopXmlContext(); } } private void OnNewLine(int pos) { _ps.lineNo++; _ps.lineStartPos = pos - 1; } private void OnEof() { Debug.Assert(_ps.isEof); _curNode = _nodes[0]; _curNode.Clear(XmlNodeType.None); _curNode.SetLineInfo(_ps.LineNo, _ps.LinePos); _parsingFunction = ParsingFunction.Eof; _readState = ReadState.EndOfFile; _reportedEncoding = null; } private string LookupNamespace(NodeData node) { string ns = _namespaceManager.LookupNamespace(node.prefix); if (ns != null) { return ns; } else { Throw(SR.Xml_UnknownNs, node.prefix, node.LineNo, node.LinePos); return null; } } private void AddNamespace(string prefix, string uri, NodeData attr) { if (uri == XmlReservedNs.NsXmlNs) { if (Ref.Equal(prefix, _xmlNs)) { Throw(SR.Xml_XmlnsPrefix, (int)attr.lineInfo2.lineNo, (int)attr.lineInfo2.linePos); } else { Throw(SR.Xml_NamespaceDeclXmlXmlns, prefix, (int)attr.lineInfo2.lineNo, (int)attr.lineInfo2.linePos); } } else if (uri == XmlReservedNs.NsXml) { if (!Ref.Equal(prefix, _xml) && !_v1Compat) { Throw(SR.Xml_NamespaceDeclXmlXmlns, prefix, (int)attr.lineInfo2.lineNo, (int)attr.lineInfo2.linePos); } } if (uri.Length == 0 && prefix.Length > 0) { Throw(SR.Xml_BadNamespaceDecl, (int)attr.lineInfo.lineNo, (int)attr.lineInfo.linePos); } try { _namespaceManager.AddNamespace(prefix, uri); } catch (ArgumentException e) { ReThrow(e, (int)attr.lineInfo.lineNo, (int)attr.lineInfo.linePos); } #if DEBUG if (prefix.Length == 0) { Debug.Assert(_xmlContext.defaultNamespace == uri); } #endif } private void ResetAttributes() { if (_fullAttrCleanup) { FullAttributeCleanup(); } _curAttrIndex = -1; _attrCount = 0; _attrHashtable = 0; _attrDuplWalkCount = 0; } private void FullAttributeCleanup() { for (int i = _index + 1; i < _index + _attrCount + 1; i++) { NodeData attr = _nodes[i]; attr.nextAttrValueChunk = null; attr.IsDefaultAttribute = false; } _fullAttrCleanup = false; } private void PushXmlContext() { _xmlContext = new XmlContext(_xmlContext); _curNode.xmlContextPushed = true; } private void PopXmlContext() { Debug.Assert(_curNode.xmlContextPushed); _xmlContext = _xmlContext.previousContext; _curNode.xmlContextPushed = false; } // Returns the whitespace node type according to the current whitespaceHandling setting and xml:space private XmlNodeType GetWhitespaceType() { if (_whitespaceHandling != WhitespaceHandling.None) { if (_xmlContext.xmlSpace == XmlSpace.Preserve) { return XmlNodeType.SignificantWhitespace; } if (_whitespaceHandling == WhitespaceHandling.All) { return XmlNodeType.Whitespace; } } return XmlNodeType.None; } private XmlNodeType GetTextNodeType(int orChars) { if (orChars > 0x20) { return XmlNodeType.Text; } else { return GetWhitespaceType(); } } // This method resolves and opens an external DTD subset or an external entity based on its SYSTEM or PUBLIC ID. // SxS: This method may expose a name if a resource in baseUri (ref) parameter. private void PushExternalEntityOrSubset(string publicId, string systemId, Uri baseUri, string entityName) { Uri uri; // First try opening the external reference by PUBLIC Id if (!string.IsNullOrEmpty(publicId)) { try { uri = _xmlResolver.ResolveUri(baseUri, publicId); if (OpenAndPush(uri)) { return; } } catch (Exception) { // Intentionally empty - catch all exception related to PUBLIC ID and try opening the entity via the SYSTEM ID } } // Then try SYSTEM Id uri = _xmlResolver.ResolveUri(baseUri, systemId); try { if (OpenAndPush(uri)) { return; } // resolver returned null, throw exception outside this try-catch } catch (Exception e) { if (_v1Compat) { throw; } string innerMessage = e.Message; Throw(new XmlException(entityName == null ? SR.Xml_ErrorOpeningExternalDtd : SR.Xml_ErrorOpeningExternalEntity, new string[] { uri.ToString(), innerMessage }, e, 0, 0)); } if (entityName == null) { ThrowWithoutLineInfo(SR.Xml_CannotResolveExternalSubset, new string[] { (publicId != null ? publicId : string.Empty), systemId }, null); } else { Throw(_dtdProcessing == DtdProcessing.Ignore ? SR.Xml_CannotResolveEntityDtdIgnored : SR.Xml_CannotResolveEntity, entityName); } } // This method opens the URI as a TextReader or Stream, pushes new ParsingStateState on the stack and calls InitStreamInput or InitTextReaderInput. // Returns: // - true when everything went ok. // - false when XmlResolver.GetEntity returned null // Propagates any exceptions from the XmlResolver indicating when the URI cannot be opened. private bool OpenAndPush(Uri uri) { Debug.Assert(_xmlResolver != null); // First try to get the data as a TextReader if (_xmlResolver.SupportsType(uri, typeof(TextReader))) { TextReader textReader = (TextReader)_xmlResolver.GetEntity(uri, null, typeof(TextReader)); if (textReader == null) { return false; } PushParsingState(); InitTextReaderInput(uri.ToString(), uri, textReader); } else { // Then try get it as a Stream Debug.Assert(_xmlResolver.SupportsType(uri, typeof(Stream)), "Stream must always be a supported type in XmlResolver"); Stream stream = (Stream)_xmlResolver.GetEntity(uri, null, typeof(Stream)); if (stream == null) { return false; } PushParsingState(); InitStreamInput(uri, stream, null); } return true; } // returns true if real entity has been pushed, false if fake entity (=empty content entity) // SxS: The method neither takes any name of resource directly nor it exposes any resource to the caller. // Entity info was created based on source document. It's OK to suppress the SxS warning private bool PushExternalEntity(IDtdEntityInfo entity) { Debug.Assert(entity.IsExternal); if (!IsResolverNull) { Uri entityBaseUri = null; if (!string.IsNullOrEmpty(entity.BaseUriString)) { entityBaseUri = _xmlResolver.ResolveUri(null, entity.BaseUriString); } PushExternalEntityOrSubset(entity.PublicId, entity.SystemId, entityBaseUri, entity.Name); RegisterEntity(entity); Debug.Assert(_ps.appendMode); int initialPos = _ps.charPos; if (_v1Compat) { EatWhitespaces(null); } if (!ParseXmlDeclaration(true)) { _ps.charPos = initialPos; } return true; } else { Encoding enc = _ps.encoding; PushParsingState(); InitStringInput(entity.SystemId, enc, string.Empty); RegisterEntity(entity); RegisterConsumedCharacters(0, true); return false; } } private void PushInternalEntity(IDtdEntityInfo entity) { Debug.Assert(!entity.IsExternal); Encoding enc = _ps.encoding; PushParsingState(); InitStringInput((entity.DeclaredUriString != null) ? entity.DeclaredUriString : string.Empty, enc, entity.Text ?? string.Empty); RegisterEntity(entity); _ps.lineNo = entity.LineNumber; _ps.lineStartPos = -entity.LinePosition - 1; _ps.eolNormalized = true; RegisterConsumedCharacters(entity.Text.Length, true); } private void PopEntity() { if (_ps.stream != null) { _ps.stream.Dispose(); } UnregisterEntity(); PopParsingState(); _curNode.entityId = _ps.entityId; } private void RegisterEntity(IDtdEntityInfo entity) { // check entity recursion if (_currentEntities != null) { if (_currentEntities.ContainsKey(entity)) { Throw(entity.IsParameterEntity ? SR.Xml_RecursiveParEntity : SR.Xml_RecursiveGenEntity, entity.Name, _parsingStatesStack[_parsingStatesStackTop].LineNo, _parsingStatesStack[_parsingStatesStackTop].LinePos); } } // save the entity to parsing state & assign it an ID _ps.entity = entity; _ps.entityId = _nextEntityId++; // register entity for recursion checkes if (entity != null) { if (_currentEntities == null) { _currentEntities = new Dictionary<IDtdEntityInfo, IDtdEntityInfo>(); } _currentEntities.Add(entity, entity); } } private void UnregisterEntity() { // remove from recursion check registry if (_ps.entity != null) { _currentEntities.Remove(_ps.entity); } } private void PushParsingState() { if (_parsingStatesStack == null) { _parsingStatesStack = new ParsingState[InitialParsingStatesDepth]; Debug.Assert(_parsingStatesStackTop == -1); } else if (_parsingStatesStackTop + 1 == _parsingStatesStack.Length) { ParsingState[] newParsingStateStack = new ParsingState[_parsingStatesStack.Length * 2]; Array.Copy(_parsingStatesStack, newParsingStateStack, _parsingStatesStack.Length); _parsingStatesStack = newParsingStateStack; } _parsingStatesStackTop++; _parsingStatesStack[_parsingStatesStackTop] = _ps; _ps.Clear(); } private void PopParsingState() { Debug.Assert(_parsingStatesStackTop >= 0); _ps.Close(true); _ps = _parsingStatesStack[_parsingStatesStackTop--]; } private void InitIncrementalRead(IncrementalReadDecoder decoder) { ResetAttributes(); decoder.Reset(); _incReadDecoder = decoder; _incReadState = IncrementalReadState.Text; _incReadDepth = 1; _incReadLeftStartPos = _ps.charPos; _incReadLeftEndPos = _ps.charPos; _incReadLineInfo.Set(_ps.LineNo, _ps.LinePos); _parsingFunction = ParsingFunction.InIncrementalRead; } private int IncrementalRead(Array array, int index, int count) { if (array == null) { throw new ArgumentNullException((_incReadDecoder is IncrementalReadCharsDecoder) ? "buffer" : nameof(array)); } if (count < 0) { throw new ArgumentOutOfRangeException((_incReadDecoder is IncrementalReadCharsDecoder) ? nameof(count) : "len"); } if (index < 0) { throw new ArgumentOutOfRangeException((_incReadDecoder is IncrementalReadCharsDecoder) ? nameof(index) : "offset"); } if (array.Length - index < count) { throw new ArgumentException((_incReadDecoder is IncrementalReadCharsDecoder) ? nameof(count) : "len"); } if (count == 0) { return 0; } _curNode.lineInfo = _incReadLineInfo; _incReadDecoder.SetNextOutputBuffer(array, index, count); IncrementalRead(); return _incReadDecoder.DecodedCount; } private int IncrementalRead() { int charsDecoded = 0; OuterContinue: int charsLeft = _incReadLeftEndPos - _incReadLeftStartPos; if (charsLeft > 0) { int count; try { count = _incReadDecoder.Decode(_ps.chars, _incReadLeftStartPos, charsLeft); } catch (XmlException e) { ReThrow(e, (int)_incReadLineInfo.lineNo, (int)_incReadLineInfo.linePos); return 0; } if (count < charsLeft) { _incReadLeftStartPos += count; _incReadLineInfo.linePos += count; // we have never more then 1 line cached return count; } else { _incReadLeftStartPos = 0; _incReadLeftEndPos = 0; _incReadLineInfo.linePos += count; if (_incReadDecoder.IsFull) { return count; } } } int startPos = 0; int pos = 0; while (true) { switch (_incReadState) { case IncrementalReadState.Text: case IncrementalReadState.Attributes: case IncrementalReadState.AttributeValue: break; case IncrementalReadState.PI: if (ParsePIValue(out startPos, out pos)) { Debug.Assert(XmlConvert.StrEqual(_ps.chars, _ps.charPos - 2, 2, "?>")); _ps.charPos -= 2; _incReadState = IncrementalReadState.Text; } goto Append; case IncrementalReadState.Comment: if (ParseCDataOrComment(XmlNodeType.Comment, out startPos, out pos)) { Debug.Assert(XmlConvert.StrEqual(_ps.chars, _ps.charPos - 3, 3, "-->")); _ps.charPos -= 3; _incReadState = IncrementalReadState.Text; } goto Append; case IncrementalReadState.CDATA: if (ParseCDataOrComment(XmlNodeType.CDATA, out startPos, out pos)) { Debug.Assert(XmlConvert.StrEqual(_ps.chars, _ps.charPos - 3, 3, "]]>")); _ps.charPos -= 3; _incReadState = IncrementalReadState.Text; } goto Append; case IncrementalReadState.EndElement: _parsingFunction = ParsingFunction.PopElementContext; _nextParsingFunction = (_index > 0 || _fragmentType != XmlNodeType.Document) ? ParsingFunction.ElementContent : ParsingFunction.DocumentContent; _outerReader.Read(); _incReadState = IncrementalReadState.End; goto case IncrementalReadState.End; case IncrementalReadState.End: return charsDecoded; case IncrementalReadState.ReadData: if (ReadData() == 0) { ThrowUnclosedElements(); } _incReadState = IncrementalReadState.Text; startPos = _ps.charPos; pos = startPos; break; default: Debug.Fail($"Unexpected read state {_incReadState}"); break; } Debug.Assert(_incReadState == IncrementalReadState.Text || _incReadState == IncrementalReadState.Attributes || _incReadState == IncrementalReadState.AttributeValue); char[] chars = _ps.chars; startPos = _ps.charPos; pos = startPos; while (true) { _incReadLineInfo.Set(_ps.LineNo, _ps.LinePos); char c; if (_incReadState == IncrementalReadState.Attributes) { while (_xmlCharType.IsAttributeValueChar(c = chars[pos]) && c != '/') { pos++; } } else { while (_xmlCharType.IsAttributeValueChar(c = chars[pos])) { pos++; } } if (chars[pos] == '&' || chars[pos] == (char)0x9) { pos++; continue; } if (pos - startPos > 0) { goto AppendAndUpdateCharPos; } switch (chars[pos]) { // eol case (char)0xA: pos++; OnNewLine(pos); continue; case (char)0xD: if (chars[pos + 1] == (char)0xA) { pos += 2; } else if (pos + 1 < _ps.charsUsed) { pos++; } else { goto ReadData; } OnNewLine(pos); continue; // some tag case '<': if (_incReadState != IncrementalReadState.Text) { pos++; continue; } if (_ps.charsUsed - pos < 2) { goto ReadData; } switch (chars[pos + 1]) { // pi case '?': pos += 2; _incReadState = IncrementalReadState.PI; goto AppendAndUpdateCharPos; // comment case '!': if (_ps.charsUsed - pos < 4) { goto ReadData; } if (chars[pos + 2] == '-' && chars[pos + 3] == '-') { pos += 4; _incReadState = IncrementalReadState.Comment; goto AppendAndUpdateCharPos; } if (_ps.charsUsed - pos < 9) { goto ReadData; } if (XmlConvert.StrEqual(chars, pos + 2, 7, "[CDATA[")) { pos += 9; _incReadState = IncrementalReadState.CDATA; goto AppendAndUpdateCharPos; } else { ; //Throw( ); } break; // end tag case '/': { Debug.Assert(_ps.charPos - pos == 0); Debug.Assert(_ps.charPos - startPos == 0); int colonPos; // ParseQName can flush the buffer, so we need to update the startPos, pos and chars after calling it int endPos = ParseQName(true, 2, out colonPos); if (XmlConvert.StrEqual(chars, _ps.charPos + 2, endPos - _ps.charPos - 2, _curNode.GetNameWPrefix(_nameTable)) && (_ps.chars[endPos] == '>' || _xmlCharType.IsWhiteSpace(_ps.chars[endPos]))) { if (--_incReadDepth > 0) { pos = endPos + 1; continue; } _ps.charPos = endPos; if (_xmlCharType.IsWhiteSpace(_ps.chars[endPos])) { EatWhitespaces(null); } if (_ps.chars[_ps.charPos] != '>') { ThrowUnexpectedToken(">"); } _ps.charPos++; _incReadState = IncrementalReadState.EndElement; goto OuterContinue; } else { pos = endPos; startPos = _ps.charPos; chars = _ps.chars; continue; } } // start tag default: { Debug.Assert(_ps.charPos - pos == 0); Debug.Assert(_ps.charPos - startPos == 0); int colonPos; // ParseQName can flush the buffer, so we need to update the startPos, pos and chars after calling it int endPos = ParseQName(true, 1, out colonPos); if (XmlConvert.StrEqual(_ps.chars, _ps.charPos + 1, endPos - _ps.charPos - 1, _curNode.localName) && (_ps.chars[endPos] == '>' || _ps.chars[endPos] == '/' || _xmlCharType.IsWhiteSpace(_ps.chars[endPos]))) { _incReadDepth++; _incReadState = IncrementalReadState.Attributes; pos = endPos; goto AppendAndUpdateCharPos; } pos = endPos; startPos = _ps.charPos; chars = _ps.chars; continue; } } break; // end of start tag case '/': if (_incReadState == IncrementalReadState.Attributes) { if (_ps.charsUsed - pos < 2) { goto ReadData; } if (chars[pos + 1] == '>') { _incReadState = IncrementalReadState.Text; _incReadDepth--; } } pos++; continue; // end of start tag case '>': if (_incReadState == IncrementalReadState.Attributes) { _incReadState = IncrementalReadState.Text; } pos++; continue; case '"': case '\'': switch (_incReadState) { case IncrementalReadState.AttributeValue: if (chars[pos] == _curNode.quoteChar) { _incReadState = IncrementalReadState.Attributes; } break; case IncrementalReadState.Attributes: _curNode.quoteChar = chars[pos]; _incReadState = IncrementalReadState.AttributeValue; break; } pos++; continue; default: // end of buffer if (pos == _ps.charsUsed) { goto ReadData; } // surrogate chars or invalid chars are ignored else { pos++; continue; } } } ReadData: _incReadState = IncrementalReadState.ReadData; AppendAndUpdateCharPos: _ps.charPos = pos; Append: // decode characters int charsParsed = pos - startPos; if (charsParsed > 0) { int count; try { count = _incReadDecoder.Decode(_ps.chars, startPos, charsParsed); } catch (XmlException e) { ReThrow(e, (int)_incReadLineInfo.lineNo, (int)_incReadLineInfo.linePos); return 0; } Debug.Assert(count == charsParsed || _incReadDecoder.IsFull, "Check if decoded consumed all characters unless it's full."); charsDecoded += count; if (_incReadDecoder.IsFull) { _incReadLeftStartPos = startPos + count; _incReadLeftEndPos = pos; _incReadLineInfo.linePos += count; // we have never more than 1 line cached return charsDecoded; } } } } private void FinishIncrementalRead() { _incReadDecoder = new IncrementalReadDummyDecoder(); IncrementalRead(); Debug.Assert(IncrementalRead() == 0, "Previous call of IncrementalRead should eat up all characters!"); _incReadDecoder = null; } private bool ParseFragmentAttribute() { Debug.Assert(_fragmentType == XmlNodeType.Attribute); // if first call then parse the whole attribute value if (_curNode.type == XmlNodeType.None) { _curNode.type = XmlNodeType.Attribute; _curAttrIndex = 0; ParseAttributeValueSlow(_ps.charPos, ' ', _curNode); // The quote char is intentionally empty (space) because we need to parse ' and " into the attribute value } else { _parsingFunction = ParsingFunction.InReadAttributeValue; } // return attribute value chunk if (ReadAttributeValue()) { Debug.Assert(_parsingFunction == ParsingFunction.InReadAttributeValue); _parsingFunction = ParsingFunction.FragmentAttribute; return true; } else { OnEof(); return false; } } private bool ParseAttributeValueChunk() { char[] chars = _ps.chars; int pos = _ps.charPos; _curNode = AddNode(_index + _attrCount + 1, _index + 2); _curNode.SetLineInfo(_ps.LineNo, _ps.LinePos); if (_emptyEntityInAttributeResolved) { _curNode.SetValueNode(XmlNodeType.Text, string.Empty); _emptyEntityInAttributeResolved = false; return true; } Debug.Assert(_stringBuilder.Length == 0); while (true) { while (_xmlCharType.IsAttributeValueChar(chars[pos])) pos++; switch (chars[pos]) { // eol D case (char)0xD: Debug.Assert(_ps.eolNormalized, "Entity replacement text for attribute values should be EOL-normalized!"); pos++; continue; // eol A, tab case (char)0xA: case (char)0x9: if (_normalize) { chars[pos] = (char)0x20; // CDATA normalization of 0xA and 0x9 } pos++; continue; case '"': case '\'': case '>': pos++; continue; // attribute values cannot contain '<' case '<': Throw(pos, SR.Xml_BadAttributeChar, XmlException.BuildCharExceptionArgs('<', '\0')); break; // entity reference case '&': if (pos - _ps.charPos > 0) { _stringBuilder.Append(chars, _ps.charPos, pos - _ps.charPos); } _ps.charPos = pos; // expand char entities but not general entities switch (HandleEntityReference(true, EntityExpandType.OnlyCharacter, out pos)) { case EntityType.CharacterDec: case EntityType.CharacterHex: case EntityType.CharacterNamed: chars = _ps.chars; if (_normalize && _xmlCharType.IsWhiteSpace(chars[_ps.charPos]) && pos - _ps.charPos == 1) { chars[_ps.charPos] = (char)0x20; // CDATA normalization of character references in entities } break; case EntityType.Unexpanded: if (_stringBuilder.Length == 0) { _curNode.lineInfo.linePos++; _ps.charPos++; _curNode.SetNamedNode(XmlNodeType.EntityReference, ParseEntityName()); return true; } else { goto ReturnText; } default: Debug.Fail("We should never get to this point."); break; } chars = _ps.chars; continue; default: // end of buffer if (pos == _ps.charsUsed) { goto ReadData; } // surrogate chars else { char ch = chars[pos]; if (XmlCharType.IsHighSurrogate(ch)) { if (pos + 1 == _ps.charsUsed) { goto ReadData; } pos++; if (XmlCharType.IsLowSurrogate(chars[pos])) { pos++; continue; } } ThrowInvalidChar(chars, _ps.charsUsed, pos); break; } } ReadData: if (pos - _ps.charPos > 0) { _stringBuilder.Append(chars, _ps.charPos, pos - _ps.charPos); _ps.charPos = pos; } // read new characters into the buffer if (ReadData() == 0) { if (_stringBuilder.Length > 0) { goto ReturnText; } else { if (HandleEntityEnd(false)) { SetupEndEntityNodeInAttribute(); return true; } else { Debug.Fail("We should never get to this point."); } } } pos = _ps.charPos; chars = _ps.chars; } ReturnText: if (pos - _ps.charPos > 0) { _stringBuilder.Append(chars, _ps.charPos, pos - _ps.charPos); _ps.charPos = pos; } _curNode.SetValueNode(XmlNodeType.Text, _stringBuilder.ToString()); _stringBuilder.Length = 0; return true; } private void ParseXmlDeclarationFragment() { try { ParseXmlDeclaration(false); } catch (XmlException e) { ReThrow(e, e.LineNumber, e.LinePosition - 6); // 6 == strlen( "<?xml " ); } } private void ThrowUnexpectedToken(int pos, string expectedToken) { ThrowUnexpectedToken(pos, expectedToken, null); } private void ThrowUnexpectedToken(string expectedToken1) { ThrowUnexpectedToken(expectedToken1, null); } private void ThrowUnexpectedToken(int pos, string expectedToken1, string expectedToken2) { _ps.charPos = pos; ThrowUnexpectedToken(expectedToken1, expectedToken2); } private void ThrowUnexpectedToken(string expectedToken1, string expectedToken2) { string unexpectedToken = ParseUnexpectedToken(); if (unexpectedToken == null) { Throw(SR.Xml_UnexpectedEOF1); } if (expectedToken2 != null) { Throw(SR.Xml_UnexpectedTokens2, new string[3] { unexpectedToken, expectedToken1, expectedToken2 }); } else { Throw(SR.Xml_UnexpectedTokenEx, new string[2] { unexpectedToken, expectedToken1 }); } } private string ParseUnexpectedToken(int pos) { _ps.charPos = pos; return ParseUnexpectedToken(); } private string ParseUnexpectedToken() { if (_ps.charPos == _ps.charsUsed) { return null; } if (_xmlCharType.IsNCNameSingleChar(_ps.chars[_ps.charPos])) { int pos = _ps.charPos + 1; while (_xmlCharType.IsNCNameSingleChar(_ps.chars[pos])) { pos++; } return new string(_ps.chars, _ps.charPos, pos - _ps.charPos); } else { Debug.Assert(_ps.charPos < _ps.charsUsed); return new string(_ps.chars, _ps.charPos, 1); } } private void ThrowExpectingWhitespace(int pos) { string unexpectedToken = ParseUnexpectedToken(pos); if (unexpectedToken == null) { Throw(pos, SR.Xml_UnexpectedEOF1); } else { Throw(pos, SR.Xml_ExpectingWhiteSpace, unexpectedToken); } } private int GetIndexOfAttributeWithoutPrefix(string name) { name = _nameTable.Get(name); if (name == null) { return -1; } for (int i = _index + 1; i < _index + _attrCount + 1; i++) { if (Ref.Equal(_nodes[i].localName, name) && _nodes[i].prefix.Length == 0) { return i; } } return -1; } private int GetIndexOfAttributeWithPrefix(string name) { name = _nameTable.Add(name); if (name == null) { return -1; } for (int i = _index + 1; i < _index + _attrCount + 1; i++) { if (Ref.Equal(_nodes[i].GetNameWPrefix(_nameTable), name)) { return i; } } return -1; } // This method is used to enable parsing of zero-terminated streams. The old XmlTextReader implementation used // to parse such streams, we this one needs to do that as well. // If the last characters decoded from the stream is 0 and the stream is in EOF state, this method will remove // the character from the parsing buffer (decrements ps.charsUsed). // Note that this method calls ReadData() which may change the value of ps.chars and ps.charPos. private bool ZeroEndingStream(int pos) { if (_v1Compat && pos == _ps.charsUsed - 1 && _ps.chars[pos] == (char)0 && ReadData() == 0 && _ps.isStreamEof) { _ps.charsUsed--; return true; } return false; } private void ParseDtdFromParserContext() { Debug.Assert(_dtdInfo == null && _fragmentParserContext != null && _fragmentParserContext.HasDtdInfo); IDtdParser dtdParser = DtdParser.Create(); // Parse DTD _dtdInfo = dtdParser.ParseFreeFloatingDtd(_fragmentParserContext.BaseURI, _fragmentParserContext.DocTypeName, _fragmentParserContext.PublicId, _fragmentParserContext.SystemId, _fragmentParserContext.InternalSubset, new DtdParserProxy(this)); if ((_validatingReaderCompatFlag || !_v1Compat) && (_dtdInfo.HasDefaultAttributes || _dtdInfo.HasNonCDataAttributes)) { _addDefaultAttributesAndNormalize = true; } } private bool InitReadContentAsBinary() { Debug.Assert(_parsingFunction != ParsingFunction.InReadContentAsBinary); if (_parsingFunction == ParsingFunction.InReadValueChunk) { throw new InvalidOperationException(SR.Xml_MixingReadValueChunkWithBinary); } if (_parsingFunction == ParsingFunction.InIncrementalRead) { throw new InvalidOperationException(SR.Xml_MixingV1StreamingWithV2Binary); } if (!XmlReader.IsTextualNode(_curNode.type)) { if (!MoveToNextContentNode(false)) { return false; } } SetupReadContentAsBinaryState(ParsingFunction.InReadContentAsBinary); _incReadLineInfo.Set(_curNode.LineNo, _curNode.LinePos); return true; } private bool InitReadElementContentAsBinary() { Debug.Assert(_parsingFunction != ParsingFunction.InReadElementContentAsBinary); Debug.Assert(_curNode.type == XmlNodeType.Element); bool isEmpty = _curNode.IsEmptyElement; // move to content or off the empty element _outerReader.Read(); if (isEmpty) { return false; } // make sure we are on a content node if (!MoveToNextContentNode(false)) { if (_curNode.type != XmlNodeType.EndElement) { Throw(SR.Xml_InvalidNodeType, _curNode.type.ToString()); } // move off end element _outerReader.Read(); return false; } SetupReadContentAsBinaryState(ParsingFunction.InReadElementContentAsBinary); _incReadLineInfo.Set(_curNode.LineNo, _curNode.LinePos); return true; } private bool MoveToNextContentNode(bool moveIfOnContentNode) { do { switch (_curNode.type) { case XmlNodeType.Attribute: return !moveIfOnContentNode; case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.CDATA: if (!moveIfOnContentNode) { return true; } break; case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: case XmlNodeType.EndEntity: // skip comments, pis and end entity nodes break; case XmlNodeType.EntityReference: _outerReader.ResolveEntity(); break; default: return false; } moveIfOnContentNode = false; } while (_outerReader.Read()); return false; } private void SetupReadContentAsBinaryState(ParsingFunction inReadBinaryFunction) { if (_parsingFunction == ParsingFunction.PartialTextValue) { _incReadState = IncrementalReadState.ReadContentAsBinary_OnPartialValue; } else { _incReadState = IncrementalReadState.ReadContentAsBinary_OnCachedValue; _nextNextParsingFunction = _nextParsingFunction; _nextParsingFunction = _parsingFunction; } _readValueOffset = 0; _parsingFunction = inReadBinaryFunction; } private void SetupFromParserContext(XmlParserContext context, XmlReaderSettings settings) { Debug.Assert(context != null); // setup nameTable XmlNameTable nt = settings.NameTable; _nameTableFromSettings = (nt != null); // get name table from namespace manager in XmlParserContext, if available; if (context.NamespaceManager != null) { // must be the same as XmlReaderSettings.NameTable, or null if (nt != null && nt != context.NamespaceManager.NameTable) { throw new XmlException(SR.Xml_NametableMismatch); } // get the namespace manager from context _namespaceManager = context.NamespaceManager; _xmlContext.defaultNamespace = _namespaceManager.LookupNamespace(string.Empty); // get the nametable from ns manager nt = _namespaceManager.NameTable; Debug.Assert(nt != null); Debug.Assert(context.NameTable == null || context.NameTable == nt, "This check should have been done in XmlParserContext constructor."); } // get name table directly from XmlParserContext else if (context.NameTable != null) { // must be the same as XmlReaderSettings.NameTable, or null if (nt != null && nt != context.NameTable) { throw new XmlException(SR.Xml_NametableMismatch, string.Empty); } nt = context.NameTable; } // no nametable provided -> create a new one else if (nt == null) { nt = new NameTable(); Debug.Assert(_nameTableFromSettings == false); } _nameTable = nt; // make sure we have namespace manager if (_namespaceManager == null) { _namespaceManager = new XmlNamespaceManager(nt); } // copy xml:space and xml:lang _xmlContext.xmlSpace = context.XmlSpace; _xmlContext.xmlLang = context.XmlLang; } // // DtdInfo // internal override IDtdInfo DtdInfo { get { return _dtdInfo; } } internal void SetDtdInfo(IDtdInfo newDtdInfo) { Debug.Assert(_dtdInfo == null); _dtdInfo = newDtdInfo; if (_dtdInfo != null) { if ((_validatingReaderCompatFlag || !_v1Compat) && (_dtdInfo.HasDefaultAttributes || _dtdInfo.HasNonCDataAttributes)) { _addDefaultAttributesAndNormalize = true; } } } // // Validation support // internal IValidationEventHandling ValidationEventHandling { set { _validationEventHandling = value; } } internal OnDefaultAttributeUseDelegate OnDefaultAttributeUse { set { _onDefaultAttributeUse = value; } } // // Internal properties for XmlValidatingReader // internal bool XmlValidatingReaderCompatibilityMode { set { _validatingReaderCompatFlag = value; // Fix for VSWhidbey 516556; These namespaces must be added to the nametable for back compat reasons. if (value) { _nameTable.Add(XmlReservedNs.NsXs); // Note: this is equal to XmlReservedNs.NsXsd in Everett _nameTable.Add(XmlReservedNs.NsXsi); _nameTable.Add(XmlReservedNs.NsDataType); } } } internal XmlNodeType FragmentType { get { return _fragmentType; } } internal void ChangeCurrentNodeType(XmlNodeType newNodeType) { Debug.Assert(_curNode.type == XmlNodeType.Whitespace && newNodeType == XmlNodeType.SignificantWhitespace, "Incorrect node type change!"); _curNode.type = newNodeType; } internal XmlResolver GetResolver() { if (IsResolverNull) return null; else return _xmlResolver; } internal object InternalSchemaType { get { return _curNode.schemaType; } set { _curNode.schemaType = value; } } internal object InternalTypedValue { get { return _curNode.typedValue; } set { _curNode.typedValue = value; } } internal bool StandAlone { get { return _standalone; } } internal override XmlNamespaceManager NamespaceManager { get { return _namespaceManager; } } internal bool V1Compat { get { return _v1Compat; } } internal ConformanceLevel V1ComformanceLevel { get { return _fragmentType == XmlNodeType.Element ? ConformanceLevel.Fragment : ConformanceLevel.Document; } } private bool AddDefaultAttributeDtd(IDtdDefaultAttributeInfo defAttrInfo, bool definedInDtd, NodeData[] nameSortedNodeData) { if (defAttrInfo.Prefix.Length > 0) { _attrNeedNamespaceLookup = true; } string localName = defAttrInfo.LocalName; string prefix = defAttrInfo.Prefix; // check for duplicates if (nameSortedNodeData != null) { if (Array.BinarySearch<object>(nameSortedNodeData, defAttrInfo, DtdDefaultAttributeInfoToNodeDataComparer.Instance) >= 0) { return false; } } else { for (int i = _index + 1; i < _index + 1 + _attrCount; i++) { if ((object)_nodes[i].localName == (object)localName && (object)_nodes[i].prefix == (object)prefix) { return false; } } } NodeData attr = AddDefaultAttributeInternal(defAttrInfo.LocalName, null, defAttrInfo.Prefix, defAttrInfo.DefaultValueExpanded, defAttrInfo.LineNumber, defAttrInfo.LinePosition, defAttrInfo.ValueLineNumber, defAttrInfo.ValueLinePosition, defAttrInfo.IsXmlAttribute); Debug.Assert(attr != null); if (DtdValidation) { if (_onDefaultAttributeUse != null) { _onDefaultAttributeUse(defAttrInfo, this); } attr.typedValue = defAttrInfo.DefaultValueTyped; } return attr != null; } internal bool AddDefaultAttributeNonDtd(SchemaAttDef attrDef) { // atomize names - Xsd Validator does not need to have the same nametable string localName = _nameTable.Add(attrDef.Name.Name); string prefix = _nameTable.Add(attrDef.Prefix); string ns = _nameTable.Add(attrDef.Name.Namespace); // atomize namespace - Xsd Validator does not need to have the same nametable if (prefix.Length == 0 && ns.Length > 0) { prefix = _namespaceManager.LookupPrefix(ns); Debug.Assert(prefix != null); if (prefix == null) { prefix = string.Empty; } } // find out if the attribute is already there for (int i = _index + 1; i < _index + 1 + _attrCount; i++) { if ((object)_nodes[i].localName == (object)localName && (((object)_nodes[i].prefix == (object)prefix) || ((object)_nodes[i].ns == (object)ns && ns != null))) { return false; } } // attribute does not exist -> we need to add it NodeData attr = AddDefaultAttributeInternal(localName, ns, prefix, attrDef.DefaultValueExpanded, attrDef.LineNumber, attrDef.LinePosition, attrDef.ValueLineNumber, attrDef.ValueLinePosition, attrDef.Reserved != SchemaAttDef.Reserve.None); Debug.Assert(attr != null); attr.schemaType = (attrDef.SchemaType == null) ? (object)attrDef.Datatype : (object)attrDef.SchemaType; attr.typedValue = attrDef.DefaultValueTyped; return true; } private NodeData AddDefaultAttributeInternal(string localName, string ns, string prefix, string value, int lineNo, int linePos, int valueLineNo, int valueLinePos, bool isXmlAttribute) { // setup the attribute NodeData attr = AddAttribute(localName, prefix, prefix.Length > 0 ? null : localName); if (ns != null) { attr.ns = ns; } attr.SetValue(value); attr.IsDefaultAttribute = true; attr.lineInfo.Set(lineNo, linePos); attr.lineInfo2.Set(valueLineNo, valueLinePos); // handle special attributes: if (attr.prefix.Length == 0) { // default namespace declaration if (Ref.Equal(attr.localName, _xmlNs)) { OnDefaultNamespaceDecl(attr); if (!_attrNeedNamespaceLookup) { // change element default namespace Debug.Assert(_nodes[_index].type == XmlNodeType.Element); if (_nodes[_index].prefix.Length == 0) { _nodes[_index].ns = _xmlContext.defaultNamespace; } } } } else { // prefixed namespace declaration if (Ref.Equal(attr.prefix, _xmlNs)) { OnNamespaceDecl(attr); if (!_attrNeedNamespaceLookup) { // change namespace of current element and attributes string pref = attr.localName; Debug.Assert(_nodes[_index].type == XmlNodeType.Element); for (int i = _index; i < _index + _attrCount + 1; i++) { if (_nodes[i].prefix.Equals(pref)) { _nodes[i].ns = _namespaceManager.LookupNamespace(pref); } } } } // xml: attribute else { if (isXmlAttribute) { OnXmlReservedAttribute(attr); } } } _fullAttrCleanup = true; return attr; } internal bool DisableUndeclaredEntityCheck { set { _disableUndeclaredEntityCheck = value; } } private int ReadContentAsBinary(byte[] buffer, int index, int count) { Debug.Assert(_incReadDecoder != null); if (_incReadState == IncrementalReadState.ReadContentAsBinary_End) { return 0; } _incReadDecoder.SetNextOutputBuffer(buffer, index, count); while (true) { // read what is already cached in curNode int charsRead = 0; try { charsRead = _curNode.CopyToBinary(_incReadDecoder, _readValueOffset); } // add line info to the exception catch (XmlException e) { _curNode.AdjustLineInfo(_readValueOffset, _ps.eolNormalized, ref _incReadLineInfo); ReThrow(e, _incReadLineInfo.lineNo, _incReadLineInfo.linePos); } _readValueOffset += charsRead; if (_incReadDecoder.IsFull) { return _incReadDecoder.DecodedCount; } // if on partial value, read the rest of it if (_incReadState == IncrementalReadState.ReadContentAsBinary_OnPartialValue) { _curNode.SetValue(string.Empty); // read next chunk of text bool endOfValue = false; int startPos = 0; int endPos = 0; while (!_incReadDecoder.IsFull && !endOfValue) { int orChars = 0; // store current line info and parse more text _incReadLineInfo.Set(_ps.LineNo, _ps.LinePos); endOfValue = ParseText(out startPos, out endPos, ref orChars); try { charsRead = _incReadDecoder.Decode(_ps.chars, startPos, endPos - startPos); } // add line info to the exception catch (XmlException e) { ReThrow(e, _incReadLineInfo.lineNo, _incReadLineInfo.linePos); } startPos += charsRead; } _incReadState = endOfValue ? IncrementalReadState.ReadContentAsBinary_OnCachedValue : IncrementalReadState.ReadContentAsBinary_OnPartialValue; _readValueOffset = 0; if (_incReadDecoder.IsFull) { _curNode.SetValue(_ps.chars, startPos, endPos - startPos); // adjust line info for the chunk that has been already decoded AdjustLineInfo(_ps.chars, startPos - charsRead, startPos, _ps.eolNormalized, ref _incReadLineInfo); _curNode.SetLineInfo(_incReadLineInfo.lineNo, _incReadLineInfo.linePos); return _incReadDecoder.DecodedCount; } } // reset to normal state so we can call Read() to move forward ParsingFunction tmp = _parsingFunction; _parsingFunction = _nextParsingFunction; _nextParsingFunction = _nextNextParsingFunction; // move to next textual node in the element content; throw on sub elements if (!MoveToNextContentNode(true)) { SetupReadContentAsBinaryState(tmp); _incReadState = IncrementalReadState.ReadContentAsBinary_End; return _incReadDecoder.DecodedCount; } SetupReadContentAsBinaryState(tmp); _incReadLineInfo.Set(_curNode.LineNo, _curNode.LinePos); } } private int ReadElementContentAsBinary(byte[] buffer, int index, int count) { if (count == 0) { return 0; } int decoded = ReadContentAsBinary(buffer, index, count); if (decoded > 0) { return decoded; } // if 0 bytes returned check if we are on a closing EndElement, throw exception if not if (_curNode.type != XmlNodeType.EndElement) { throw new XmlException(SR.Xml_InvalidNodeType, _curNode.type.ToString(), this as IXmlLineInfo); } // reset state _parsingFunction = _nextParsingFunction; _nextParsingFunction = _nextNextParsingFunction; Debug.Assert(_parsingFunction != ParsingFunction.InReadElementContentAsBinary); // move off the EndElement _outerReader.Read(); return 0; } private void InitBase64Decoder() { if (_base64Decoder == null) { _base64Decoder = new Base64Decoder(); } else { _base64Decoder.Reset(); } _incReadDecoder = _base64Decoder; } private void InitBinHexDecoder() { if (_binHexDecoder == null) { _binHexDecoder = new BinHexDecoder(); } else { _binHexDecoder.Reset(); } _incReadDecoder = _binHexDecoder; } // SxS: URIs are resolved only to be compared. No resource exposure. It's OK to suppress the SxS warning. private bool UriEqual(Uri uri1, string uri1Str, string uri2Str, XmlResolver resolver) { if (resolver == null) { return uri1Str == uri2Str; } if (uri1 == null) { uri1 = resolver.ResolveUri(null, uri1Str); } Uri uri2 = resolver.ResolveUri(null, uri2Str); return uri1.Equals(uri2); } /// <summary> /// This method should be called every time the reader is about to consume some number of /// characters from the input. It will count it against the security counters and /// may throw if some of the security limits are exceeded. /// </summary> /// <param name="characters">Number of characters to be consumed.</param> /// <param name="inEntityReference">true if the characters are result of entity expansion.</param> private void RegisterConsumedCharacters(long characters, bool inEntityReference) { Debug.Assert(characters >= 0); if (_maxCharactersInDocument > 0) { long newCharactersInDocument = _charactersInDocument + characters; if (newCharactersInDocument < _charactersInDocument) { // Integer overflow while counting ThrowWithoutLineInfo(SR.Xml_LimitExceeded, "MaxCharactersInDocument"); } else { _charactersInDocument = newCharactersInDocument; } if (_charactersInDocument > _maxCharactersInDocument) { // The limit was exceeded for the total number of characters in the document ThrowWithoutLineInfo(SR.Xml_LimitExceeded, "MaxCharactersInDocument"); } } if (_maxCharactersFromEntities > 0 && inEntityReference) { long newCharactersFromEntities = _charactersFromEntities + characters; if (newCharactersFromEntities < _charactersFromEntities) { // Integer overflow while counting ThrowWithoutLineInfo(SR.Xml_LimitExceeded, "MaxCharactersFromEntities"); } else { _charactersFromEntities = newCharactersFromEntities; } if (_charactersFromEntities > _maxCharactersFromEntities) { // The limit was exceeded for the number of characters from entities ThrowWithoutLineInfo(SR.Xml_LimitExceeded, "MaxCharactersFromEntities"); } } } internal static unsafe void AdjustLineInfo(char[] chars, int startPos, int endPos, bool isNormalized, ref LineInfo lineInfo) { Debug.Assert(startPos >= 0); Debug.Assert(endPos < chars.Length); Debug.Assert(startPos <= endPos); fixed (char* pChars = &chars[startPos]) { AdjustLineInfo(pChars, endPos - startPos, isNormalized, ref lineInfo); } } internal static unsafe void AdjustLineInfo(string str, int startPos, int endPos, bool isNormalized, ref LineInfo lineInfo) { Debug.Assert(startPos >= 0); Debug.Assert(endPos < str.Length); Debug.Assert(startPos <= endPos); fixed (char* pChars = str) { AdjustLineInfo(pChars + startPos, endPos - startPos, isNormalized, ref lineInfo); } } internal static unsafe void AdjustLineInfo(char* pChars, int length, bool isNormalized, ref LineInfo lineInfo) { int lastNewLinePos = -1; for (int i = 0; i < length; i++) { switch (pChars[i]) { case '\n': lineInfo.lineNo++; lastNewLinePos = i; break; case '\r': if (isNormalized) { break; } lineInfo.lineNo++; lastNewLinePos = i; if (i + 1 < length && pChars[i + 1] == '\n') { i++; lastNewLinePos++; } break; } } if (lastNewLinePos >= 0) { lineInfo.linePos = length - lastNewLinePos; } } // StripSpaces removes spaces at the beginning and at the end of the value and replaces sequences of spaces with a single space internal static string StripSpaces(string value) { int len = value.Length; if (len <= 0) { return string.Empty; } int startPos = 0; StringBuilder norValue = null; while (value[startPos] == 0x20) { startPos++; if (startPos == len) { return " "; } } int i; for (i = startPos; i < len; i++) { if (value[i] == 0x20) { int j = i + 1; while (j < len && value[j] == 0x20) { j++; } if (j == len) { if (norValue == null) { return value.Substring(startPos, i - startPos); } else { norValue.Append(value, startPos, i - startPos); return norValue.ToString(); } } if (j > i + 1) { if (norValue == null) { norValue = new StringBuilder(len); } norValue.Append(value, startPos, i - startPos + 1); startPos = j; i = j - 1; } } } if (norValue == null) { return (startPos == 0) ? value : value.Substring(startPos, len - startPos); } else { if (i > startPos) { norValue.Append(value, startPos, i - startPos); } return norValue.ToString(); } } // StripSpaces removes spaces at the beginning and at the end of the value and replaces sequences of spaces with a single space internal static void StripSpaces(char[] value, int index, ref int len) { if (len <= 0) { return; } int startPos = index; int endPos = index + len; while (value[startPos] == 0x20) { startPos++; if (startPos == endPos) { len = 1; return; } } int offset = startPos - index; int i; for (i = startPos; i < endPos; i++) { char ch; if ((ch = value[i]) == 0x20) { int j = i + 1; while (j < endPos && value[j] == 0x20) { j++; } if (j == endPos) { offset += (j - i); break; } if (j > i + 1) { offset += (j - i - 1); i = j - 1; } } value[i - offset] = ch; } len -= offset; } internal static void BlockCopyChars(char[] src, int srcOffset, char[] dst, int dstOffset, int count) { // PERF: Buffer.BlockCopy is faster than Array.Copy Buffer.BlockCopy(src, srcOffset * sizeof(char), dst, dstOffset * sizeof(char), count * sizeof(char)); } internal static void BlockCopy(byte[] src, int srcOffset, byte[] dst, int dstOffset, int count) { Buffer.BlockCopy(src, srcOffset, dst, dstOffset, count); } static partial void ConvertAbsoluteUnixPathToAbsoluteUri(ref string url, XmlResolver resolver); } }
37.174216
185
0.435175
[ "MIT" ]
1shekhar/runtime
src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs
362,746
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; using System.Threading; using OpenQA.Selenium; namespace Atata { /// <summary> /// Represents the Atata context, the entry point for the test set-up. /// </summary> public sealed class AtataContext : IDisposable { private static readonly object s_buildStartSyncLock = new object(); private static readonly AsyncLocal<AtataContext> s_currentAsyncLocalContext = new AsyncLocal<AtataContext>(); private static AtataContextModeOfCurrent s_modeOfCurrent = AtataContextModeOfCurrent.AsyncLocal; [ThreadStatic] private static AtataContext s_currentThreadStaticContext; private static AtataContext s_currentStaticContext; private string _testName; private string _testSuiteName; private IWebDriver _driver; private bool _disposed; /// <summary> /// Gets the base retry timeout, which is <c>5</c> seconds. /// </summary> public static readonly TimeSpan DefaultRetryTimeout = TimeSpan.FromSeconds(5); /// <summary> /// Gets the default retry interval, which is <c>500</c> milliseconds. /// </summary> public static readonly TimeSpan DefaultRetryInterval = TimeSpan.FromSeconds(0.5); internal AtataContext() { Go = new AtataNavigator(this); } /// <summary> /// Gets or sets the current context. /// </summary> public static AtataContext Current { get { return ModeOfCurrent == AtataContextModeOfCurrent.ThreadStatic ? s_currentThreadStaticContext : ModeOfCurrent == AtataContextModeOfCurrent.AsyncLocal ? s_currentAsyncLocalContext.Value : s_currentStaticContext; } set { if (ModeOfCurrent == AtataContextModeOfCurrent.ThreadStatic) s_currentThreadStaticContext = value; else if (ModeOfCurrent == AtataContextModeOfCurrent.AsyncLocal) s_currentAsyncLocalContext.Value = value; else s_currentStaticContext = value; } } /// <summary> /// Gets or sets the mode of <see cref="Current"/> property. /// The default value is <see cref="AtataContextModeOfCurrent.AsyncLocal"/>. /// </summary> public static AtataContextModeOfCurrent ModeOfCurrent { get => s_modeOfCurrent; set { s_modeOfCurrent = value; RetrySettings.ThreadBoundary = value == AtataContextModeOfCurrent.ThreadStatic ? RetrySettingsThreadBoundary.ThreadStatic : value == AtataContextModeOfCurrent.AsyncLocal ? RetrySettingsThreadBoundary.AsyncLocal : RetrySettingsThreadBoundary.Static; } } /// <summary> /// Gets the global configuration. /// </summary> public static AtataContextBuilder GlobalConfiguration { get; } = new AtataContextBuilder(new AtataBuildingContext()); /// <summary> /// Gets the build start local date and time. /// Contains the same value for all the tests being executed within one build. /// </summary> public static DateTime? BuildStart { get; private set; } /// <summary> /// Gets the build start UTC date and time. /// Contains the same value for all the tests being executed within one build. /// </summary> public static DateTime? BuildStartUtc { get; private set; } // TODO: Review BuildStartInTimeZone property. internal DateTime BuildStartInTimeZone { get; private set; } internal IDriverFactory DriverFactory { get; set; } /// <summary> /// Gets the driver. /// </summary> public IWebDriver Driver { get { switch (DriverInitializationStage) { case AtataContextDriverInitializationStage.Build: return _driver; case AtataContextDriverInitializationStage.OnDemand: if (_driver is null) InitDriver(); return _driver; default: return null; } } } /// <summary> /// Gets a value indicating whether this instance has <see cref="Driver"/> instance. /// </summary> public bool HasDriver => _driver != null; /// <summary> /// Gets the driver alias. /// </summary> public string DriverAlias { get; internal set; } /// <summary> /// Gets the driver initialization stage. /// </summary> public AtataContextDriverInitializationStage DriverInitializationStage { get; internal set; } /// <summary> /// Gets the instance of the log manager. /// </summary> public ILogManager Log { get; internal set; } /// <summary> /// Gets the name of the test. /// </summary> public string TestName { get => _testName; internal set { _testName = value; TestNameSanitized = value.SanitizeForFileName(); } } /// <summary> /// Gets the name of the test sanitized for file path/name. /// </summary> public string TestNameSanitized { get; private set; } /// <summary> /// Gets the name of the test suite (fixture/class). /// </summary> public string TestSuiteName { get => _testSuiteName; internal set { _testSuiteName = value; TestSuiteNameSanitized = value.SanitizeForFileName(); } } /// <summary> /// Gets the name of the test suite sanitized for file path/name. /// </summary> public string TestSuiteNameSanitized { get; private set; } /// <summary> /// Gets the test suite (fixture/class) type. /// </summary> public Type TestSuiteType { get; internal set; } /// <summary> /// Gets the local date/time of the start. /// </summary> public DateTime StartedAt { get; private set; } /// <summary> /// Gets the UTC date/time of the start. /// </summary> public DateTime StartedAtUtc { get; private set; } /// <summary> /// Gets the time zone. /// The default value is <see cref="TimeZoneInfo.Local"/>. /// </summary> public TimeZoneInfo TimeZone { get; internal set; } /// <summary> /// Gets or sets the base URL. /// </summary> public string BaseUrl { get; set; } /// <summary> /// Gets the base retry timeout. /// The default value is <c>5</c> seconds. /// </summary> public TimeSpan BaseRetryTimeout { get; internal set; } /// <summary> /// Gets the base retry interval. /// The default value is <c>500</c> milliseconds. /// </summary> public TimeSpan BaseRetryInterval { get; internal set; } /// <summary> /// Gets the element find timeout. /// The default value is <c>5</c> seconds. /// </summary> public TimeSpan ElementFindTimeout { get; internal set; } /// <summary> /// Gets the element find retry interval. /// The default value is <c>500</c> milliseconds. /// </summary> public TimeSpan ElementFindRetryInterval { get; internal set; } /// <summary> /// Gets the waiting timeout. /// The default value is <c>5</c> seconds. /// </summary> public TimeSpan WaitingTimeout { get; internal set; } /// <summary> /// Gets the waiting retry interval. /// The default value is <c>500</c> milliseconds. /// </summary> public TimeSpan WaitingRetryInterval { get; internal set; } /// <summary> /// Gets the verification timeout. /// The default value is <c>5</c> seconds. /// </summary> public TimeSpan VerificationTimeout { get; internal set; } /// <summary> /// Gets the verification retry interval. /// The default value is <c>500</c> milliseconds. /// </summary> public TimeSpan VerificationRetryInterval { get; internal set; } /// <summary> /// Gets the default control visibility. /// The default value is <see cref="Visibility.Any"/>. /// </summary> public Visibility DefaultControlVisibility { get; internal set; } /// <summary> /// Gets the culture. /// The default value is <see cref="CultureInfo.CurrentCulture"/>. /// </summary> public CultureInfo Culture { get; internal set; } /// <summary> /// Gets the type of the assertion exception. /// The default value is a type of <see cref="AssertionException"/>. /// </summary> public Type AssertionExceptionType { get; internal set; } /// <summary> /// Gets the type of the aggregate assertion exception. /// The default value is a type of <see cref="AggregateAssertionException"/>. /// The exception type should have public constructor with <c>IEnumerable&lt;AssertionResult&gt;</c> argument. /// </summary> public Type AggregateAssertionExceptionType { get; internal set; } /// <summary> /// Gets the aggregate assertion strategy. /// The default value is an instance of <see cref="AtataAggregateAssertionStrategy"/>. /// </summary> public IAggregateAssertionStrategy AggregateAssertionStrategy { get; internal set; } /// <summary> /// Gets the aggregate assertion depth level. /// </summary> public int AggregateAssertionLevel { get; internal set; } /// <summary> /// Gets the strategy for warning assertion reporting. /// The default value is an instance of <see cref="AtataWarningReportStrategy"/>. /// </summary> public IWarningReportStrategy WarningReportStrategy { get; internal set; } /// <summary> /// Gets the list of all assertion results. /// </summary> public List<AssertionResult> AssertionResults { get; } = new List<AssertionResult>(); /// <summary> /// Gets the list of pending assertion results with <see cref="AssertionStatus.Failed"/> or <see cref="AssertionStatus.Warning"/> status. /// </summary> public List<AssertionResult> PendingFailureAssertionResults { get; } = new List<AssertionResult>(); /// <summary> /// Gets the context of the attributes. /// </summary> public AtataAttributesContext Attributes { get; internal set; } /// <summary> /// Gets the <see cref="DirectorySubject"/> of Artifacts directory. /// Artifacts directory can contain any files produced during test execution, logs, screenshots, downloads, etc. /// The default Artifacts directory path is <c>"{basedir}/artifacts/{build-start:yyyyMMddTHHmmss}{test-suite-name-sanitized:/*}{test-name-sanitized:/*}"</c>. /// </summary> public DirectorySubject Artifacts { get; internal set; } /// <summary> /// Gets the <see cref="AtataNavigator"/> instance, /// which provides the navigation functionality between pages and windows. /// </summary> public AtataNavigator Go { get; } /// <summary> /// Gets the current page object. /// </summary> public UIComponent PageObject { get; internal set; } internal List<UIComponent> TemporarilyPreservedPageObjectList { get; private set; } = new List<UIComponent>(); internal bool IsNavigated { get; set; } internal Stopwatch ExecutionStopwatch { get; } = Stopwatch.StartNew(); internal Stopwatch PureExecutionStopwatch { get; } = new Stopwatch(); public ReadOnlyCollection<UIComponent> TemporarilyPreservedPageObjects { get { return TemporarilyPreservedPageObjectList.ToReadOnly(); } } /// <summary> /// Gets the UI component access chain scope cache. /// </summary> public UIComponentAccessChainScopeCache UIComponentAccessChainScopeCache { get; } = new UIComponentAccessChainScopeCache(); /// <summary> /// Gets the object creator. /// </summary> public IObjectCreator ObjectCreator { get; internal set; } /// <summary> /// Gets the object converter. /// </summary> public IObjectConverter ObjectConverter { get; internal set; } /// <summary> /// Gets the object mapper. /// </summary> public IObjectMapper ObjectMapper { get; internal set; } /// <summary> /// Gets the event bus, which can used to subscribe to and publish events. /// </summary> public IEventBus EventBus { get; internal set; } /// <summary> /// Gets the variables dictionary. /// <para> /// The list of predefined variables: /// <list type="bullet"> /// <item><c>build-start</c></item> /// <item><c>build-start-utc</c></item> /// <item><c>basedir</c></item> /// <item><c>artifacts</c></item> /// <item><c>test-name-sanitized</c></item> /// <item><c>test-name</c></item> /// <item><c>test-suite-name-sanitized</c></item> /// <item><c>test-suite-name</c></item> /// <item><c>test-start</c></item> /// <item><c>test-start-utc</c></item> /// <item><c>driver-alias</c></item> /// </list> /// </para> /// <para> /// Custom variables can be added as well. /// </para> /// </summary> public IDictionary<string, object> Variables { get; } = new Dictionary<string, object>(); /// <summary> /// Creates <see cref="AtataContextBuilder"/> instance for <see cref="AtataContext"/> configuration. /// Sets the value to <see cref="AtataContextBuilder.BuildingContext"/> copied from <see cref="GlobalConfiguration"/>. /// </summary> /// <returns>The created <see cref="AtataContextBuilder"/> instance.</returns> public static AtataContextBuilder Configure() { AtataBuildingContext buildingContext = GlobalConfiguration.BuildingContext.Clone(); return new AtataContextBuilder(buildingContext); } internal void InitDateTimeProperties() { StartedAtUtc = DateTime.UtcNow; StartedAt = TimeZoneInfo.ConvertTimeFromUtc(StartedAtUtc, TimeZone); if (BuildStartUtc is null) { lock (s_buildStartSyncLock) { if (BuildStartUtc is null) { BuildStartUtc = StartedAtUtc; BuildStart = BuildStartUtc.Value.ToLocalTime(); } } } BuildStartInTimeZone = TimeZoneInfo.ConvertTimeFromUtc(BuildStartUtc.Value, TimeZone); } internal void InitMainVariables() { var variables = Variables; variables["build-start"] = BuildStartInTimeZone; variables["build-start-utc"] = BuildStartUtc; variables["basedir"] = AppDomain.CurrentDomain.BaseDirectory; variables["test-name-sanitized"] = TestNameSanitized; variables["test-name"] = TestName; variables["test-suite-name-sanitized"] = TestSuiteNameSanitized; variables["test-suite-name"] = TestSuiteName; variables["test-start"] = StartedAt; variables["test-start-utc"] = StartedAtUtc; variables["driver-alias"] = DriverAlias; } internal void InitCustomVariables(IDictionary<string, object> customVariables) { var variables = Variables; foreach (var variable in customVariables) variables[variable.Key] = variable.Value; } internal void InitArtifactsVariable() => Variables["artifacts"] = Artifacts.FullName.Value; internal void LogTestStart() { StringBuilder logMessageBuilder = new StringBuilder( $"Starting {GetTestUnitKindName()}"); string[] testFullNameParts = GetTestFullNameParts().ToArray(); if (testFullNameParts.Length > 0) { logMessageBuilder.Append(": ") .Append(string.Join(".", testFullNameParts)); } Log.Info(logMessageBuilder.ToString()); } private IEnumerable<string> GetTestFullNameParts() { if (TestSuiteType != null) yield return TestSuiteType.Namespace; if (TestSuiteName != null) yield return TestSuiteName; if (TestName != null) yield return TestName; } private string GetTestUnitKindName() { return TestName != null ? "test" : TestSuiteType != null ? "test suite" : "test unit"; } /// <summary> /// Executes aggregate assertion using <see cref="AggregateAssertionStrategy" />. /// </summary> /// <param name="action">The action to execute in scope of aggregate assertion.</param> /// <param name="assertionScopeName"> /// Name of the scope being asserted (page object, control, etc.). /// Is used to identify the assertion section in log. /// Can be null. /// </param> public void AggregateAssert(Action action, string assertionScopeName = null) { action.CheckNotNull(nameof(action)); AggregateAssertionStrategy.Assert(() => { AggregateAssertionLevel++; try { Log.ExecuteSection( new AggregateAssertionLogSection(assertionScopeName), action); } finally { AggregateAssertionLevel--; } }); } /// <summary> /// Cleans up the test context. /// </summary> /// <param name="quitDriver">if set to <see langword="true"/> quits WebDriver.</param> public void CleanUp(bool quitDriver = true) { if (_disposed) return; PureExecutionStopwatch.Stop(); Log.ExecuteSection( new LogSection("Clean up AtataContext", LogLevel.Trace), () => { EventBus.Publish(new AtataContextCleanUpEvent(this)); CleanUpTemporarilyPreservedPageObjectList(); if (PageObject != null) UIComponentResolver.CleanUpPageObject(PageObject); UIComponentAccessChainScopeCache.Release(); if (quitDriver) _driver?.Dispose(); }); ExecutionStopwatch.Stop(); string testUnitKindName = GetTestUnitKindName(); Log.InfoWithExecutionTimeInBrackets($"Finished {testUnitKindName}", ExecutionStopwatch.Elapsed); Log.InfoWithExecutionTime($"Pure {testUnitKindName} execution time:", PureExecutionStopwatch.Elapsed); Log = null; if (Current == this) Current = null; _disposed = true; AssertionResults.Clear(); if (PendingFailureAssertionResults.Any()) { var copyOfPendingFailureAssertionResults = PendingFailureAssertionResults.ToArray(); PendingFailureAssertionResults.Clear(); throw VerificationUtils.CreateAggregateAssertionException(copyOfPendingFailureAssertionResults); } } internal void InitDriver() { if (DriverFactory is null) throw new InvalidOperationException( $"Failed to create an instance of {typeof(IWebDriver).FullName} as driver factory is not specified."); _driver = DriverFactory.Create() ?? throw new InvalidOperationException( $"Failed to create an instance of {typeof(IWebDriver).FullName} as driver factory returned null as a driver."); _driver.Manage().Timeouts().SetRetryTimeout(ElementFindTimeout, ElementFindRetryInterval); EventBus.Publish(new DriverInitEvent(_driver)); } /// <summary> /// Restarts the driver. /// </summary> public void RestartDriver() { Log.ExecuteSection( new LogSection("Restart driver"), () => { CleanUpTemporarilyPreservedPageObjectList(); if (PageObject != null) { UIComponentResolver.CleanUpPageObject(PageObject); PageObject = null; } _driver.Dispose(); InitDriver(); }); } internal void CleanUpTemporarilyPreservedPageObjectList() { UIComponentResolver.CleanUpPageObjects(TemporarilyPreservedPageObjects); TemporarilyPreservedPageObjectList.Clear(); } /// <summary> /// Fills the template string with variables of this <see cref="AtataContext"/> instance. /// The <paramref name="template"/> can contain variables wrapped with curly braces, e.g. <c>"{varName}"</c>. /// Variables support standard .NET formatting (<c>"{numberVar:D5}"</c> or <c>"{dateTimeVar:yyyy-MM-dd}"</c>) /// and extended formatting for strings /// (for example, <c>"{stringVar:/*}"</c> appends <c>"/"</c> to the beginning of the string, if variable is not null). /// <para> /// The list of predefined variables: /// <list type="bullet"> /// <item><c>{build-start}</c></item> /// <item><c>{build-start-utc}</c></item> /// <item><c>{basedir}</c></item> /// <item><c>{artifacts}</c></item> /// <item><c>{test-name-sanitized}</c></item> /// <item><c>{test-name}</c></item> /// <item><c>{test-suite-name-sanitized}</c></item> /// <item><c>{test-suite-name}</c></item> /// <item><c>{test-start}</c></item> /// <item><c>{test-start-utc}</c></item> /// <item><c>{driver-alias}</c></item> /// </list> /// </para> /// </summary> /// <param name="template">The template string.</param> /// <returns>The filled string.</returns> public string FillTemplateString(string template) => FillTemplateString(template, null); /// <inheritdoc cref="FillTemplateString(string)"/> /// <param name="template">The template string.</param> /// <param name="additionalVariables">The additional variables.</param> public string FillTemplateString(string template, IDictionary<string, object> additionalVariables) { template.CheckNotNull(nameof(template)); if (!template.Contains('{')) return template; var variables = Variables; if (additionalVariables != null) { variables = new Dictionary<string, object>(variables); foreach (var variable in additionalVariables) variables[variable.Key] = variable.Value; } return TemplateStringTransformer.Transform(template, variables); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { CleanUp(); } } }
36.969565
166
0.547963
[ "Apache-2.0" ]
EvgeniyShunevich/Atata
src/Atata/Context/AtataContext.cs
25,511
C#
using Prism.Commands; using Prism.Navigation; using Prism.Services; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using WikiHero.Helpers; using WikiHero.Models; using WikiHero.Services; using Xamarin.Essentials; namespace WikiHero.ViewModels { public class DetailCharactersPageViewModel : BaseViewModel,INavigationAware { public ObservableCollection<Character> Characters { get; set; } public ObservableCollection<Character> CharactersEnemys { get; set; } public ObservableCollection<Comic> Comics { get; set; } public ObservableCollection<Movie> Movies { get; set; } public ObservableCollection<Volume> Volumes { get; set; } public ObservableCollection<Team> Teams { get; set; } public Video Video { get; set; } public Character Character { get; set; } public List<Task> LoadTask { get; set; } public DelegateCommand LoadCommand { get; set; } public DelegateCommand ShareCommand { get; set; } public DelegateCommand GoToVideo { get; set; } public DetailCharactersPageViewModel(INavigationService navigationService, IPageDialogService dialogService, IApiComicsVine apiComicsVine) : base(navigationService, dialogService, apiComicsVine) { ShareCommand = new DelegateCommand(async () => { await SharedOpcion(); }); GoToVideo = new DelegateCommand(async () => { var param = new NavigationParameters(); param.Add($"{nameof(Video)}", Video); await navigationService.NavigateAsync(new Uri(ConfigPageUri.VideoPage,UriKind.Relative), param); }); } async Task LoadCharacter(int id) { try { var character = await apiComicsVine.FindCharacter(id, Config.Apikey, null); Character = character.Character; } catch (Exception err) { await dialogService.DisplayAlertAsync("Error", $"{err}", "ok"); } } async Task LoadVideo() { try { var videos = await apiComicsVine.GetVideo(Config.Apikey, Character.Name, null); foreach (var item in videos.Results.Take(1)) { Video = item; } } catch (Exception err) { await dialogService.DisplayAlertAsync("Error", $"{err}", "ok"); } } async Task LoadMovies(Character character) { try { string movie = null; var take = Character.Movies.Take(20).Select(e => e.Id); movie = string.Join("|", take); var movies = await apiComicsVine.FindCharactersMovies(Config.Apikey, movie); Movies = new ObservableCollection<Movie>(movies.Results.Take(30)); } catch (Exception err) { await dialogService.DisplayAlertAsync("Error", $"{err}", "ok"); } } async Task LoadCVolumes(Character character) { try { string volume = null; var take = character.VolumeCredits.Take(30).Select(e=>e.Id); volume = string.Join("|", take); var volumes = await apiComicsVine.FindCharactersVolumes(Config.Apikey, volume); Volumes = new ObservableCollection<Volume>(volumes.Volumes); } catch (Exception err) { await dialogService.DisplayAlertAsync("Error", $"{err}", "ok"); } } async Task LoadCharacterEnemyy(Character character) { try { string volume = null; var take = character.CharacterEnemies.Take(30).Select(e=>e.Id).ToArray(); volume = string.Join("|", take); var characters = await apiComicsVine.FindEnenmyCharacter(Config.Apikey, volume); CharactersEnemys = new ObservableCollection<Character>(characters.Characters); } catch (Exception err) { await dialogService.DisplayAlertAsync("Error", $"{err}", "ok"); } } async Task LoadComics(Character character) { try { string comic = null; var take = character.Issues.Take(30).Select(e => e.Id); comic = string.Join("|", take.ToArray()); var comics = await apiComicsVine.FindCharacterComics(Config.Apikey, comic); Comics = new ObservableCollection<Comic>(comics.Results); } catch (Exception err) { await dialogService.DisplayAlertAsync("Error", $"{err}", "ok"); } } async Task SharedOpcion() { await Share.RequestAsync(new ShareTextRequest { Text = $"{Character.Name}\n{Character.Publisher.Name}\n{Character.Deck}", Title = $"{Character.Publisher.Name}\n{Character.Deck}", Uri = $"{Character.SiteDetailUrl}" }); } async Task LoadTeams(Character character) { try { string comic = null; var c = character.Teams.Take(30).Select(x=> x.Id); comic = string.Join("|", c.ToArray()); var team = await apiComicsVine.FindTeamsCharacter(Config.Apikey, comic); Teams = new ObservableCollection<Team>(team.Results); } catch (Exception err) { await dialogService.DisplayAlertAsync("Error", $"{err}", "ok"); } } public void OnNavigatedFrom(INavigationParameters parameters) { } public void OnNavigatedTo(INavigationParameters parameters) { var param = (int)parameters[nameof(Character)]; var id = param; LoadListCommand = new DelegateCommand(async () => { await LoadCharacter(id); LoadTask = new List<Task>() {LoadVideo(), LoadCharacterEnemyy(Character), LoadCVolumes(Character), LoadMovies(Character), LoadComics(Character), LoadTeams(Character) }; await Task.WhenAll(LoadTask); }); LoadListCommand.Execute(); } } }
34.71134
202
0.545738
[ "MIT" ]
daiivasq/WikiHeroApp
WikiHero/WikiHero/ViewModels/DetailCharactersPageViewModel.cs
6,736
C#
using System.Collections.Generic; using System.Text.RegularExpressions; using static Cloudtoid.Contract; namespace Cloudtoid.UrlPattern { public sealed class CompiledPattern { internal CompiledPattern( string pattern, PatternType type, Regex regex, ISet<string> variableNames) { Pattern = CheckValue(pattern, nameof(pattern)); Type = type; Regex = CheckValue(regex, nameof(regex)); VariableNames = CheckValue(variableNames, nameof(variableNames)); } public string Pattern { get; } public PatternType Type { get; } public Regex Regex { get; } public ISet<string> VariableNames { get; } } }
25.3
77
0.608696
[ "MIT" ]
cloudtoid/url-pattern
src/Cloudtoid.UrlPattern/Compiler/CompiledPattern.cs
761
C#
// ----------------------------------------------------------------------- // <copyright file="ReferenceDayType.cs" company=""> // Copyright 2016 Alexander Soffronow Pagonidis // </copyright> // ----------------------------------------------------------------------- namespace QDMS { public enum ReferenceDayType { /// <summary> /// The reference point is set at a specified number of calendar days of a specified month. /// </summary> CalendarDays, /// <summary> /// The reference point is set at a specified number of elapsed days of a specified week. /// </summary> WeekDays, /// <summary> /// The reference day is set to the last business day of the relevant month. /// </summary> LastDayOfMonth } }
30.222222
99
0.490196
[ "BSD-3-Clause" ]
karlcc/qdms
QDMS/Enums/ReferenceDayType.cs
818
C#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityModel; using IdentityServer4.Configuration; using IdentityServer4.Extensions; using IdentityServer4.Models; using IdentityServer4.Stores; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace IdentityServer4.Services { /// <summary> /// Default token service /// </summary> public class DefaultTokenService : ITokenService { /// <summary> /// The logger /// </summary> protected readonly ILogger Logger; /// <summary> /// The HTTP context accessor /// </summary> protected readonly IHttpContextAccessor ContextAccessor; /// <summary> /// The claims provider /// </summary> protected readonly IClaimsService ClaimsProvider; /// <summary> /// The reference token store /// </summary> protected readonly IReferenceTokenStore ReferenceTokenStore; /// <summary> /// The signing service /// </summary> protected readonly ITokenCreationService CreationService; /// <summary> /// The clock /// </summary> protected readonly ISystemClock Clock; /// <summary> /// The key material service /// </summary> protected readonly IKeyMaterialService KeyMaterialService; /// <summary> /// The IdentityServer options /// </summary> protected readonly IdentityServerOptions Options; /// <summary> /// Initializes a new instance of the <see cref="DefaultTokenService" /> class. /// </summary> /// <param name="claimsProvider">The claims provider.</param> /// <param name="referenceTokenStore">The reference token store.</param> /// <param name="creationService">The signing service.</param> /// <param name="contextAccessor">The HTTP context accessor.</param> /// <param name="clock">The clock.</param> /// <param name="keyMaterialService"></param> /// <param name="options">The IdentityServer options</param> /// <param name="logger">The logger.</param> public DefaultTokenService( IClaimsService claimsProvider, IReferenceTokenStore referenceTokenStore, ITokenCreationService creationService, IHttpContextAccessor contextAccessor, ISystemClock clock, IKeyMaterialService keyMaterialService, IdentityServerOptions options, ILogger<DefaultTokenService> logger) { ContextAccessor = contextAccessor; ClaimsProvider = claimsProvider; ReferenceTokenStore = referenceTokenStore; CreationService = creationService; Clock = clock; KeyMaterialService = keyMaterialService; Options = options; Logger = logger; } /// <summary> /// Creates an identity token. /// </summary> /// <param name="request">The token creation request.</param> /// <returns> /// An identity token /// </returns> public virtual async Task<Token> CreateIdentityTokenAsync(TokenCreationRequest request) { Logger.LogTrace("Creating identity token"); request.Validate(); // todo: Dom, add a test for this. validate the at and c hashes are correct for the id_token when the client's alg doesn't match the server default. var credential = await KeyMaterialService.GetSigningCredentialsAsync(request.ValidatedRequest.Client.AllowedIdentityTokenSigningAlgorithms); if (credential == null) { Logger.LogDebug("No signing credential is configured."); throw new InvalidOperationException("No signing credential is configured."); } var signingAlgorithm = credential.Algorithm; // host provided claims var claims = new List<Claim>(); // if nonce was sent, must be mirrored in id token if (request.Nonce.IsPresent()) { claims.Add(new Claim(JwtClaimTypes.Nonce, request.Nonce)); } // add iat claim claims.Add(new Claim(JwtClaimTypes.IssuedAt, Clock.UtcNow.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)); // add at_hash claim if (request.AccessTokenToHash.IsPresent()) { claims.Add(new Claim(JwtClaimTypes.AccessTokenHash, CryptoHelper.CreateHashClaimValue(request.AccessTokenToHash, signingAlgorithm))); } // add c_hash claim if (request.AuthorizationCodeToHash.IsPresent()) { claims.Add(new Claim(JwtClaimTypes.AuthorizationCodeHash, CryptoHelper.CreateHashClaimValue(request.AuthorizationCodeToHash, signingAlgorithm))); } // add s_hash claim if (request.StateHash.IsPresent()) { claims.Add(new Claim(JwtClaimTypes.StateHash, request.StateHash)); } // add sid if present if (request.ValidatedRequest.SessionId.IsPresent()) { claims.Add(new Claim(JwtClaimTypes.SessionId, request.ValidatedRequest.SessionId)); } claims.AddRange(await ClaimsProvider.GetIdentityTokenClaimsAsync( request.Subject, request.ValidatedResources, request.IncludeAllIdentityClaims, request.ValidatedRequest)); var issuer = ContextAccessor.HttpContext.GetIdentityServerIssuerUri(); Logger.LogTrace("Add issuer '{issuer}' to token", issuer); var token = new Token(OidcConstants.TokenTypes.IdentityToken) { CreationTime = Clock.UtcNow.UtcDateTime, Audiences = { request.ValidatedRequest.Client.ClientId }, Issuer = issuer, Lifetime = request.ValidatedRequest.Client.IdentityTokenLifetime, Claims = claims.Distinct(new ClaimComparer()).ToList(), ClientId = request.ValidatedRequest.Client.ClientId, AccessTokenType = request.ValidatedRequest.AccessTokenType, AllowedSigningAlgorithms = request.ValidatedRequest.Client.AllowedIdentityTokenSigningAlgorithms }; Logger.LogDebug("Create identity token complete"); return token; } /// <summary> /// Creates an access token. /// </summary> /// <param name="request">The token creation request.</param> /// <returns> /// An access token /// </returns> public virtual async Task<Token> CreateAccessTokenAsync(TokenCreationRequest request) { Logger.LogTrace("Creating access token"); request.Validate(); var claims = new List<Claim>(); claims.AddRange(await ClaimsProvider.GetAccessTokenClaimsAsync( request.Subject, request.ValidatedResources, request.ValidatedRequest)); if (request.ValidatedRequest.Client.IncludeJwtId) { claims.Add(new Claim(JwtClaimTypes.JwtId, CryptoRandom.CreateUniqueId(16, CryptoRandom.OutputFormat.Hex))); } if (request.ValidatedRequest.SessionId.IsPresent()) { claims.Add(new Claim(JwtClaimTypes.SessionId, request.ValidatedRequest.SessionId)); } // iat claim as required by JWT profile claims.Add(new Claim(JwtClaimTypes.IssuedAt, Clock.UtcNow.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)); if (request.IpAddress.IsPresent()) { claims.Add(new Claim(Constants.JwtClaims.Ip, request.IpAddress)); } if (request.Device.IsPresent()) { claims.Add(new Claim(Constants.JwtClaims.Device, request.Device)); } var issuer = ContextAccessor.HttpContext.GetIdentityServerIssuerUri(); var token = new Token(OidcConstants.TokenTypes.AccessToken) { CreationTime = Clock.UtcNow.UtcDateTime, Issuer = issuer, Lifetime = request.ValidatedRequest.AccessTokenLifetime, Claims = claims.Distinct(new ClaimComparer()).ToList(), ClientId = request.ValidatedRequest.Client.ClientId, Description = request.Description, AccessTokenType = request.ValidatedRequest.AccessTokenType, AllowedSigningAlgorithms = request.ValidatedResources.Resources.ApiResources.FindMatchingSigningAlgorithms() }; // add aud based on ApiResources in the validated request foreach (var aud in request.ValidatedResources.Resources.ApiResources.Select(x => x.Name).Distinct()) { token.Audiences.Add(aud); } if (Options.EmitStaticAudienceClaim) { token.Audiences.Add(string.Format(IdentityServerConstants.AccessTokenAudience, issuer.EnsureTrailingSlash())); } // add cnf if present if (request.ValidatedRequest.Confirmation.IsPresent()) { token.Confirmation = request.ValidatedRequest.Confirmation; } else { if (Options.MutualTls.AlwaysEmitConfirmationClaim) { var clientCertificate = await ContextAccessor.HttpContext.Connection.GetClientCertificateAsync(); if (clientCertificate != null) { token.Confirmation = clientCertificate.CreateThumbprintCnf(); } } } return token; } /// <summary> /// Creates a serialized and protected security token. /// </summary> /// <param name="token">The token.</param> /// <returns> /// A security token in serialized form /// </returns> /// <exception cref="System.InvalidOperationException">Invalid token type.</exception> public virtual async Task<string> CreateSecurityTokenAsync(Token token) { string tokenResult; if (token.Type == OidcConstants.TokenTypes.AccessToken) { if (token.AccessTokenType == AccessTokenType.Jwt) { Logger.LogTrace("Creating JWT access token"); tokenResult = await CreationService.CreateTokenAsync(token); } else { Logger.LogTrace("Creating reference access token"); tokenResult = await ReferenceTokenStore.StoreReferenceTokenAsync(token); } } else if (token.Type == OidcConstants.TokenTypes.IdentityToken) { Logger.LogTrace("Creating JWT identity token"); tokenResult = await CreationService.CreateTokenAsync(token); } else { throw new InvalidOperationException("Invalid token type."); } return tokenResult; } } }
38.930921
161
0.595437
[ "Apache-2.0" ]
yartat/IdentityServer4
src/IdentityServer4/src/Services/Default/DefaultTokenService.cs
11,835
C#
using System; using ParkApp.Models; using System.Collections.Generic; namespace ParkAppCore.Repositorio.Mocks { public class UsuarioMock : IRepository<Usuario> { public UsuarioMock() { } public IList<Usuario> Find() { throw new NotImplementedException(); } public Usuario Find(int id) { throw new NotImplementedException(); } public bool Insert(Usuario obj) { throw new NotImplementedException(); } public bool Remove(Usuario obj) { throw new NotImplementedException(); } public bool Update(Usuario obj) { throw new NotImplementedException(); } } }
20.475
52
0.522589
[ "MIT" ]
xamarin-com-br/ParkForms
src/ParkApp/ParkAppCore/Repositorio/Mocks/UsuarioMock.cs
821
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using BeatmapDownloader.Database.Database; namespace BeatmapDownloader.Database.Migrations { [DbContext(typeof(BeatmapDownloaderDatabaseContext))] [Migration("20200704040633_InitializeMigration")] partial class InitializeMigration { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.5"); modelBuilder.Entity("MultiplayerDownloader.WpfUI.Model.DownloadBeatmapSet", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int>("BeatmapId") .HasColumnType("INTEGER"); b.Property<int>("BeatmapSetId") .HasColumnType("INTEGER"); b.Property<string>("DownloadProviderId") .HasColumnType("TEXT"); b.Property<string>("DownloadProviderName") .HasColumnType("TEXT"); b.Property<DateTime>("DownloadTime") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("DownloadProviderId"); b.HasIndex("DownloadProviderName"); b.ToTable("DownloadedBeatmapSets"); }); #pragma warning restore 612, 618 } } }
32.407407
92
0.576
[ "MIT" ]
OsuSync/EmberTools
src/plugins/osu/BeatmapDownloader.Database/Migrations/20200704040633_InitializeMigration.Designer.cs
1,752
C#
namespace MagicMedia.Thumbprint { public class DeviceInfo { public string? Brand { get; set; } public string? Model { get; set; } public string? Family { get; set; } } }
17.416667
43
0.574163
[ "MIT" ]
philbir/magic-media
src/Services/Abstractions/Thumbprint/DeviceInfo.cs
211
C#
// AUTOGENERATED using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FlatSharp.Attributes; using NamelessRogue.Engine.Serialization.SerializationIfrastructure; using NamelessRogue.Engine.Serialization.CustomSerializationClasses; namespace NamelessRogue.Engine.Serialization.AutogeneratedSerializationClasses { [FlatBufferTable] public class CitySlotStorage : IStorage<NamelessRogue.Engine.Generation.World.CitySlot> { [FlatBufferItem(0)] public string Id { get; set; } [FlatBufferItem(1)] public string ParentEntityId { get; set; } [FlatBufferItem(2)] public BoundingBoxStorage Placement { get; set; } [FlatBufferItem(3)] public Boolean Occupied { get; set; } [FlatBufferItem(4)] public EntityStorage OccupiedBy { get; set; } public void FillFrom(NamelessRogue.Engine.Generation.World.CitySlot component) { this.Placement = component.Placement; this.Occupied = component.Occupied; this.OccupiedBy.FillFrom(component.OccupiedBy); } public void FillTo(NamelessRogue.Engine.Generation.World.CitySlot component) { component.Placement = this.Placement; component.Occupied = this.Occupied; this.OccupiedBy.FillTo(component.OccupiedBy); } public static implicit operator NamelessRogue.Engine.Generation.World.CitySlot (CitySlotStorage thisType) { if(thisType == null) { return null; } NamelessRogue.Engine.Generation.World.CitySlot result = new NamelessRogue.Engine.Generation.World.CitySlot(); thisType.FillTo(result); return result; } public static implicit operator CitySlotStorage (NamelessRogue.Engine.Generation.World.CitySlot component) { if(component == null) { return null; } CitySlotStorage result = new CitySlotStorage(); result.FillFrom(component); return result; } } }
32.123077
121
0.681034
[ "MIT" ]
GreyArmor/SomeRogueMonogame
NamelessRogue_updated/Engine/Serialization/AutogeneratedSerializationClasses/CitySlotStorage.cs
2,088
C#
namespace MiniRent.Application.Common.Interfaces; public interface IDateTime { DateTime Now { get; } }
15.571429
50
0.752294
[ "MIT" ]
r-ost/MiniRent
src/Application/Common/Interfaces/IDateTime.cs
111
C#
namespace ForumSystem.Identity.Models { using System.Data.Entity; using ForumSystem.Identity.Migrations; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; public class IdentityDbContext : IdentityDbContext<ApplicationIdentityUser> { public IdentityDbContext() : base("IdentityDbConnection", throwIfV1Schema: false) { Database.SetInitializer(new MigrateDatabaseToLatestVersion<IdentityDbContext, Configuration>()); } public static IdentityDbContext Create() { return new IdentityDbContext(); } public class SeedOnlyInitializer : IDatabaseInitializer<IdentityDbContext> { protected void Seed(ForumSystem.Identity.Models.IdentityDbContext context) { RoleStore<IdentityRole> roleStore = new RoleStore<IdentityRole>(context); RoleManager<IdentityRole> roleManager = new RoleManager<IdentityRole>(roleStore); IdentityRole role = new IdentityRole { Name = "ThreadsAdmin" }; roleManager.Create(role); context.SaveChanges(); UserStore<ApplicationIdentityUser> userStore = new UserStore<ApplicationIdentityUser>(context); UserManager<ApplicationIdentityUser> userManager = new UserManager<ApplicationIdentityUser>(userStore); ApplicationIdentityUser user = new ApplicationIdentityUser { UserName = "admin@admin.com" }; // Initial admin user userManager.Create(user, "admin123"); userManager.AddToRole(user.Id, "ThreadsAdmin"); context.SaveChanges(); } public void InitializeDatabase(IdentityDbContext context) { Seed(context); context.SaveChanges(); } } } }
35
119
0.633766
[ "MIT" ]
bugsancho/ForumSystem
src/ForumSystem.Identity/Models/IdentityDbContext.cs
1,927
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ecs-2014-11-13.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ECS.Model { /// <summary> /// Hostnames and IP address entries that are added to the <code>/etc/hosts</code> file /// of a container via the <code>extraHosts</code> parameter of its <a>ContainerDefinition</a>. /// </summary> public partial class HostEntry { private string _hostname; private string _ipAddress; /// <summary> /// Gets and sets the property Hostname. /// <para> /// The hostname to use in the <code>/etc/hosts</code> entry. /// </para> /// </summary> public string Hostname { get { return this._hostname; } set { this._hostname = value; } } // Check to see if Hostname property is set internal bool IsSetHostname() { return this._hostname != null; } /// <summary> /// Gets and sets the property IpAddress. /// <para> /// The IP address to use in the <code>/etc/hosts</code> entry. /// </para> /// </summary> public string IpAddress { get { return this._ipAddress; } set { this._ipAddress = value; } } // Check to see if IpAddress property is set internal bool IsSetIpAddress() { return this._ipAddress != null; } } }
29.578947
101
0.611655
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/ECS/Generated/Model/HostEntry.cs
2,248
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; using Microsoft.Net.Http.Headers; namespace Microsoft.AspNetCore.ResponseCaching { internal class ResponseCachingPolicyProvider : IResponseCachingPolicyProvider { public virtual bool AttemptResponseCaching(ResponseCachingContext context) { var request = context.HttpContext.Request; // Verify the method if (!HttpMethods.IsGet(request.Method) && !HttpMethods.IsHead(request.Method)) { context.Logger.RequestMethodNotCacheable(request.Method); return false; } // Verify existence of authorization headers if (!StringValues.IsNullOrEmpty(request.Headers[HeaderNames.Authorization])) { context.Logger.RequestWithAuthorizationNotCacheable(); return false; } return true; } public virtual bool AllowCacheLookup(ResponseCachingContext context) { var requestHeaders = context.HttpContext.Request.Headers; var cacheControl = requestHeaders[HeaderNames.CacheControl]; // Verify request cache-control parameters if (!StringValues.IsNullOrEmpty(cacheControl)) { if (HeaderUtilities.ContainsCacheDirective(cacheControl, CacheControlHeaderValue.NoCacheString)) { context.Logger.RequestWithNoCacheNotCacheable(); return false; } } else { // Support for legacy HTTP 1.0 cache directive if (HeaderUtilities.ContainsCacheDirective(requestHeaders[HeaderNames.Pragma], CacheControlHeaderValue.NoCacheString)) { context.Logger.RequestWithPragmaNoCacheNotCacheable(); return false; } } return true; } public virtual bool AllowCacheStorage(ResponseCachingContext context) { // Check request no-store return !HeaderUtilities.ContainsCacheDirective(context.HttpContext.Request.Headers[HeaderNames.CacheControl], CacheControlHeaderValue.NoStoreString); } public virtual bool IsResponseCacheable(ResponseCachingContext context) { var responseCacheControlHeader = context.HttpContext.Response.Headers[HeaderNames.CacheControl]; // Only cache pages explicitly marked with public if (!HeaderUtilities.ContainsCacheDirective(responseCacheControlHeader, CacheControlHeaderValue.PublicString)) { context.Logger.ResponseWithoutPublicNotCacheable(); return false; } // Check response no-store if (HeaderUtilities.ContainsCacheDirective(responseCacheControlHeader, CacheControlHeaderValue.NoStoreString)) { context.Logger.ResponseWithNoStoreNotCacheable(); return false; } // Check no-cache if (HeaderUtilities.ContainsCacheDirective(responseCacheControlHeader, CacheControlHeaderValue.NoCacheString)) { context.Logger.ResponseWithNoCacheNotCacheable(); return false; } var response = context.HttpContext.Response; // Do not cache responses with Set-Cookie headers if (!StringValues.IsNullOrEmpty(response.Headers[HeaderNames.SetCookie])) { context.Logger.ResponseWithSetCookieNotCacheable(); return false; } // Do not cache responses varying by * var varyHeader = response.Headers[HeaderNames.Vary]; if (varyHeader.Count == 1 && string.Equals(varyHeader, "*", StringComparison.OrdinalIgnoreCase)) { context.Logger.ResponseWithVaryStarNotCacheable(); return false; } // Check private if (HeaderUtilities.ContainsCacheDirective(responseCacheControlHeader, CacheControlHeaderValue.PrivateString)) { context.Logger.ResponseWithPrivateNotCacheable(); return false; } // Check response code if (response.StatusCode != StatusCodes.Status200OK) { context.Logger.ResponseWithUnsuccessfulStatusCodeNotCacheable(response.StatusCode); return false; } // Check response freshness if (!context.ResponseDate.HasValue) { if (!context.ResponseSharedMaxAge.HasValue && !context.ResponseMaxAge.HasValue && context.ResponseTime.Value >= context.ResponseExpires) { context.Logger.ExpirationExpiresExceeded(context.ResponseTime.Value, context.ResponseExpires.Value); return false; } } else { var age = context.ResponseTime.Value - context.ResponseDate.Value; // Validate shared max age if (age >= context.ResponseSharedMaxAge) { context.Logger.ExpirationSharedMaxAgeExceeded(age, context.ResponseSharedMaxAge.Value); return false; } else if (!context.ResponseSharedMaxAge.HasValue) { // Validate max age if (age >= context.ResponseMaxAge) { context.Logger.ExpirationMaxAgeExceeded(age, context.ResponseMaxAge.Value); return false; } else if (!context.ResponseMaxAge.HasValue) { // Validate expiration if (context.ResponseTime.Value >= context.ResponseExpires) { context.Logger.ExpirationExpiresExceeded(context.ResponseTime.Value, context.ResponseExpires.Value); return false; } } } } return true; } public virtual bool IsCachedEntryFresh(ResponseCachingContext context) { var age = context.CachedEntryAge.Value; var cachedCacheControlHeaders = context.CachedResponseHeaders[HeaderNames.CacheControl]; var requestCacheControlHeaders = context.HttpContext.Request.Headers[HeaderNames.CacheControl]; // Add min-fresh requirements TimeSpan? minFresh; if (HeaderUtilities.TryParseSeconds(requestCacheControlHeaders, CacheControlHeaderValue.MinFreshString, out minFresh)) { age += minFresh.Value; context.Logger.ExpirationMinFreshAdded(minFresh.Value); } // Validate shared max age, this overrides any max age settings for shared caches TimeSpan? cachedSharedMaxAge; HeaderUtilities.TryParseSeconds(cachedCacheControlHeaders, CacheControlHeaderValue.SharedMaxAgeString, out cachedSharedMaxAge); if (age >= cachedSharedMaxAge) { // shared max age implies must revalidate context.Logger.ExpirationSharedMaxAgeExceeded(age, cachedSharedMaxAge.Value); return false; } else if (!cachedSharedMaxAge.HasValue) { TimeSpan? requestMaxAge; HeaderUtilities.TryParseSeconds(requestCacheControlHeaders, CacheControlHeaderValue.MaxAgeString, out requestMaxAge); TimeSpan? cachedMaxAge; HeaderUtilities.TryParseSeconds(cachedCacheControlHeaders, CacheControlHeaderValue.MaxAgeString, out cachedMaxAge); var lowestMaxAge = cachedMaxAge < requestMaxAge ? cachedMaxAge : requestMaxAge ?? cachedMaxAge; // Validate max age if (age >= lowestMaxAge) { // Must revalidate or proxy revalidate if (HeaderUtilities.ContainsCacheDirective(cachedCacheControlHeaders, CacheControlHeaderValue.MustRevalidateString) || HeaderUtilities.ContainsCacheDirective(cachedCacheControlHeaders, CacheControlHeaderValue.ProxyRevalidateString)) { context.Logger.ExpirationMustRevalidate(age, lowestMaxAge.Value); return false; } TimeSpan? requestMaxStale; var maxStaleExist = HeaderUtilities.ContainsCacheDirective(requestCacheControlHeaders, CacheControlHeaderValue.MaxStaleString); HeaderUtilities.TryParseSeconds(requestCacheControlHeaders, CacheControlHeaderValue.MaxStaleString, out requestMaxStale); // Request allows stale values with no age limit if (maxStaleExist && !requestMaxStale.HasValue) { context.Logger.ExpirationInfiniteMaxStaleSatisfied(age, lowestMaxAge.Value); return true; } // Request allows stale values with age limit if (requestMaxStale.HasValue && age - lowestMaxAge < requestMaxStale) { context.Logger.ExpirationMaxStaleSatisfied(age, lowestMaxAge.Value, requestMaxStale.Value); return true; } context.Logger.ExpirationMaxAgeExceeded(age, lowestMaxAge.Value); return false; } else if (!cachedMaxAge.HasValue && !requestMaxAge.HasValue) { // Validate expiration DateTimeOffset expires; if (HeaderUtilities.TryParseDate(context.CachedResponseHeaders[HeaderNames.Expires].ToString(), out expires) && context.ResponseTime.Value >= expires) { context.Logger.ExpirationExpiresExceeded(context.ResponseTime.Value, expires); return false; } } } return true; } } }
43.028112
161
0.585216
[ "Apache-2.0" ]
4samitim/aspnetcore
src/Middleware/ResponseCaching/src/ResponseCachingPolicyProvider.cs
10,714
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.Devices.V20200710Preview.Inputs { /// <summary> /// The properties related to a storage container endpoint. /// </summary> public sealed class RoutingStorageContainerPropertiesArgs : Pulumi.ResourceArgs { /// <summary> /// Method used to authenticate against the storage endpoint /// </summary> [Input("authenticationType")] public InputUnion<string, Pulumi.AzureNextGen.Devices.V20200710Preview.AuthenticationType>? AuthenticationType { get; set; } /// <summary> /// Time interval at which blobs are written to storage. Value should be between 60 and 720 seconds. Default value is 300 seconds. /// </summary> [Input("batchFrequencyInSeconds")] public Input<int>? BatchFrequencyInSeconds { get; set; } /// <summary> /// The connection string of the storage account. /// </summary> [Input("connectionString")] public Input<string>? ConnectionString { get; set; } /// <summary> /// The name of storage container in the storage account. /// </summary> [Input("containerName", required: true)] public Input<string> ContainerName { get; set; } = null!; /// <summary> /// Encoding that is used to serialize messages to blobs. Supported values are 'avro', 'avrodeflate', and 'JSON'. Default value is 'avro'. /// </summary> [Input("encoding")] public Input<string>? Encoding { get; set; } /// <summary> /// The url of the storage endpoint. It must include the protocol https:// /// </summary> [Input("endpointUri")] public Input<string>? EndpointUri { get; set; } /// <summary> /// File name format for the blob. Default format is {iothub}/{partition}/{YYYY}/{MM}/{DD}/{HH}/{mm}. All parameters are mandatory but can be reordered. /// </summary> [Input("fileNameFormat")] public Input<string>? FileNameFormat { get; set; } /// <summary> /// Id of the storage container endpoint /// </summary> [Input("id")] public Input<string>? Id { get; set; } /// <summary> /// Maximum number of bytes for each blob written to storage. Value should be between 10485760(10MB) and 524288000(500MB). Default value is 314572800(300MB). /// </summary> [Input("maxChunkSizeInBytes")] public Input<int>? MaxChunkSizeInBytes { get; set; } /// <summary> /// The name that identifies this endpoint. The name can only include alphanumeric characters, periods, underscores, hyphens and has a maximum length of 64 characters. The following names are reserved: events, fileNotifications, $default. Endpoint names must be unique across endpoint types. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; /// <summary> /// The name of the resource group of the storage account. /// </summary> [Input("resourceGroup")] public Input<string>? ResourceGroup { get; set; } /// <summary> /// The subscription identifier of the storage account. /// </summary> [Input("subscriptionId")] public Input<string>? SubscriptionId { get; set; } public RoutingStorageContainerPropertiesArgs() { } } }
39.6
300
0.621744
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Devices/V20200710Preview/Inputs/RoutingStorageContainerPropertiesArgs.cs
3,762
C#
public class NotImplementedException : System.Exception { public NotImplementedException() : base() { } public NotImplementedException(string message) : base(message) { } public NotImplementedException(string message, System.Exception inner) : base(message, inner) { } } public abstract class Spline{ public Spline(int n, double[] x, double[] y){ this.n = n; this.x = x; this.y = y; } public int n { get; } public double[] x { get; } public double[] y { get; } protected int binsearch(double z){ int i = 0; int j = n - 1; while(j - i > 1){ int mid = (i + j) / 2; if(z > this.x[mid]){ i = mid; } else { j = mid; } } return i; } abstract public double eval(double z); abstract public double integ(double z, double constant = 0); abstract public double deriv(double z); }
23.190476
101
0.541068
[ "MIT" ]
mads-hb/ppnm-2022
homeworks/splines/cs/A/src/spline.cs
974
C#
//MIT, 2017-present,WinterDev, EngineKit using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading; namespace EasePatcher { delegate void SimpleAction(); enum BuildState { Zero, InitBuild, } enum PatcherOS { Unknown, Windows, Mac, Linux } abstract class PatcherBase { protected string _original_node_src_dir; protected string _espresso_src; protected BuildState _buildState; protected List<string> _newHeaderFiles = new List<string>(); protected List<string> _newCppImplFiles = new List<string>(); /// <summary> /// path to patch folder relative to main espresso src folder (eg. node_patches\node7.10_modified) /// </summary> public string PatchSubFolder { get; set; } protected virtual void OnPatchFinishing() { } public void DoPatch() { //1. copy file from espresso's patch folder //and place into target dir //the version must be match between original source and the patch //string patch_folder = _espresso_src + "\"+ @"node_patches\node7.10_modified"; string patch_folder = _espresso_src + "/" + PatchSubFolder; ReplaceFileInDirectory(patch_folder, _original_node_src_dir); //2. copy core of libespresso bridge code( nodejs and .NET) //to src/espresso_ext folder string libespr_dir = "src/libespresso"; string targetDir = _original_node_src_dir + "/" + libespr_dir; if (Directory.Exists(targetDir)) { Directory.Delete(targetDir, true); } //create targetdir Directory.CreateDirectory(targetDir); //copy the following file to target folder string[] libEsprCoreFiles = Directory.GetFiles(_espresso_src + @"/libespresso"); int j = libEsprCoreFiles.Length; _newHeaderFiles.Clear(); _newCppImplFiles.Clear(); for (int i = 0; i < j; ++i) { string esprCodeFilename = libEsprCoreFiles[i]; switch (Path.GetExtension(esprCodeFilename).ToLower()) { default: continue; case ".cpp": { string onlyfilename = Path.GetFileName(esprCodeFilename); _newCppImplFiles.Add(libespr_dir + "/" + onlyfilename); File.Copy(esprCodeFilename, targetDir + "/" + onlyfilename); } break; case ".h": { string onlyfilename = Path.GetFileName(esprCodeFilename); _newHeaderFiles.Add(libespr_dir + "/" + onlyfilename); File.Copy(esprCodeFilename, targetDir + "/" + onlyfilename); } break; } } // OnPatchFinishing(); } static void ReplaceFileInDirectory(string patchSrcDir, string targetDir) { //recursive string[] allFiles = Directory.GetFiles(patchSrcDir); //copy these files to target folder int j = allFiles.Length; for (int i = 0; i < j; ++i) { string patchSrcFile = allFiles[i]; string extension = Path.GetExtension(patchSrcFile); switch (extension) { default: break; case ".js": case ".h": case ".cpp": case ".cc": ReplaceFile(patchSrcFile, targetDir + "/" + Path.GetFileName(patchSrcFile)); break; } } //sub-folders string[] subFolders = Directory.GetDirectories(patchSrcDir); j = subFolders.Length; for (int i = 0; i < j; ++i) { ReplaceFileInDirectory(subFolders[i], targetDir + "/" + Path.GetFileName(subFolders[i])); } } static void ReplaceFile(string patchFileName, string targetToBeReplacedFileName) { if (!File.Exists(targetToBeReplacedFileName)) { //not found -> stop Console.WriteLine("NOT FOUND targetToBeReplacedFileName: " + targetToBeReplacedFileName); throw new NotSupportedException(); } //---------------------------- if (Path.GetFileName(targetToBeReplacedFileName) != Path.GetFileName(patchFileName)) { //filename must match throw new NotSupportedException(); } //---------------------------- //replace src to dest File.Copy(patchFileName, targetToBeReplacedFileName, true); } public static PatcherOS GetPatcherOS() { //check platform if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform( System.Runtime.InteropServices.OSPlatform.OSX)) { return PatcherOS.Mac; } else if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform( System.Runtime.InteropServices.OSPlatform.Linux) ) { return PatcherOS.Linux; } else if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform( System.Runtime.InteropServices.OSPlatform.Windows)) { return PatcherOS.Windows; } else { return PatcherOS.Unknown; } } } class WindowsPatcher : PatcherBase { string _initBuildParameters; public void Setup(string original_node_src_dir, string espresso_src, string initBuildParameters = "") { _buildState = BuildState.Zero; _initBuildParameters = initBuildParameters; _original_node_src_dir = original_node_src_dir; _espresso_src = espresso_src; } public bool ConfigHasSomeErrs { get; private set; } public void Configure(SimpleAction nextAction) { //------------------------------------------------------- //FOR WINDOWS:.... //------------------------------------------------------- //1. specific location of original node src //2. run first FRESH build of the node src string vc_build_script = Path.Combine( Directory.GetCurrentDirectory(), _original_node_src_dir + @"/vcbuild.bat").ToString(); if (!File.Exists(vc_build_script)) { Console.WriteLine("Err! not found batch files"); ConfigHasSomeErrs = true; if (nextAction != null) { nextAction(); } return; } _buildState = BuildState.InitBuild; ThreadPool.QueueUserWorkItem(delegate { //choose x86 or x64; //choose release or debug ProcessStartInfo procStartInfo = new ProcessStartInfo( vc_build_script, _initBuildParameters); //procStartInfo.UseShellExecute = false; //procStartInfo.RedirectStandardOutput = true; //procStartInfo.CreateNoWindow = true; procStartInfo.WorkingDirectory = _original_node_src_dir; Process proc = System.Diagnostics.Process.Start(procStartInfo); proc.WaitForExit(); //finish if (nextAction != null) { nextAction(); } }); } protected override void OnPatchFinishing() { base.OnPatchFinishing(); //------- //modify vcx project //insert string vcx = _original_node_src_dir + "/libnode.vcxproj"; List<string> allLines = new List<string>(); //------- //create backup if (!File.Exists(vcx + ".backup")) { File.Copy(vcx, vcx + ".backup"); } // using (FileStream fs = new FileStream(vcx, FileMode.Open)) using (StreamReader reader = new StreamReader(fs)) { string line = reader.ReadLine(); while (line != null) { allLines.Add(line.Trim());//trim here line = reader.ReadLine(); } } //------- //find proper insert location int j = allLines.Count; //remove some config line for (int i = j - 1; i >= 0; --i) { string line = allLines[i]; //1. remove if (line == @"<ModuleDefinitionFile>$(OutDir)obj\global_intermediate\openssl.def</ModuleDefinitionFile>") { //remove this line allLines.RemoveAt(i); } else if (line == "<ClCompile Include=\"src\\node_main.cc\">") { //check next line string nextline = allLines[i + 1]; if (nextline == "<ExcludedFromBuild>true</ExcludedFromBuild>") { //remove next line allLines.RemoveAt(i + 1); } } //2. if we config as dll , //it exclude main.cc, //but in our case we need it // } //------- bool add_header_files = false; bool add_impl_files = false; j = allLines.Count;//reset for (int i = 0; i < j; ++i) { string line = allLines[i]; if (line == "<ItemGroup>") { //next line line = allLines[i + 1]; if (!add_impl_files && line.StartsWith("<ClCompile")) { //found insertion point add_impl_files = true; int impl_count = _newCppImplFiles.Count; for (int m = 0; m < impl_count; ++m) { allLines.Insert(i + 2 + m, "<ClCompile Include=\"" + _newCppImplFiles[m] + "\" />"); } } else if (!add_header_files && line.StartsWith("<ClInclude")) { add_header_files = true; int header_count = _newHeaderFiles.Count; for (int m = 0; m < header_count; ++m) { allLines.Insert(i + 2 + m, "<ClInclude Include=\"" + _newHeaderFiles[m] + "\" />"); } } } //---- if (add_impl_files && add_header_files) { break; } } //save back using (FileStream fs = new FileStream(vcx, FileMode.Create)) using (StreamWriter writer = new StreamWriter(fs)) { j = allLines.Count;//reset for (int i = 0; i < j; ++i) { writer.WriteLine(allLines[i]); } writer.Flush(); } } } class LinuxAndMacPatcher : PatcherBase { string _init_build_pars = ""; public void Setup(string original_node_src, string espresso_src, string initBuildParameters = "") { _buildState = BuildState.Zero; _init_build_pars = initBuildParameters; _original_node_src_dir = original_node_src; _espresso_src = espresso_src; } public void PatchGyp(SimpleAction nextAction) { _buildState = BuildState.InitBuild; ThreadPool.QueueUserWorkItem(delegate { InternalPatchGyp(); //we patch the gyp *** UnixConfigure(); //UnixMake(); if (nextAction != null) { nextAction(); } }); } void InternalPatchGyp() { string src_dir = _original_node_src_dir; List<string> lines = new List<string>(); using (FileStream fs = new FileStream(src_dir + "/" + "node.gyp", FileMode.Open)) using (StreamReader reader = new StreamReader(fs)) { string line = reader.ReadLine(); while (line != null) { lines.Add(line); line = reader.ReadLine(); } } //------------------- //find specific location and insert src string[] new_patches = new string[] { "src/libespresso/bridge.cpp", "src/libespresso/bridge2_impl.cpp", "src/libespresso/jscontext.cpp", "src/libespresso/jsengine.cpp", "src/libespresso/jsscript.cpp", "src/libespresso/managedref.cpp", "src/libespresso/mini_BinaryReaderWriter.cpp", "src/libespresso/libespr_nodemain.cpp", "src/libespresso/bridge2.h", "src/libespresso/espresso.h", "src/libespresso/jsscript.h", }; int j = lines.Count; for (int i = j - 1; i >= 0; --i) { string line = lines[i].Trim(); if (line == "'src/node.cc',") { //insert //and break foreach (string patchFileName in new_patches) { lines.Insert(i, "'" + patchFileName + "',"); } break; } } //---------- //save gyp j = lines.Count; using (FileStream fs = new FileStream(src_dir + "/" + "node.gyp", FileMode.Create)) using (StreamWriter writer = new StreamWriter(fs)) { for (int i = 0; i < j; ++i) { writer.WriteLine(lines[i]); } writer.Flush(); } } void UnixConfigure() { ProcessStartInfo stInfo = new ProcessStartInfo(_original_node_src_dir + "/configure", _init_build_pars); stInfo.WorkingDirectory = _original_node_src_dir; // Process proc = Process.Start(stInfo); proc.WaitForExit(); } void UnixMake() { ProcessStartInfo stInfo = new ProcessStartInfo("make"); stInfo.WorkingDirectory = _original_node_src_dir; Process proc = Process.Start(stInfo); proc.WaitForExit(); } } }
35.313199
121
0.464935
[ "MIT" ]
CIVITAS-John/Espresso
Tools/EasePatcher/EasePatcher.cs
15,787
C#
using UnityEngine; using System; using System.Collections; using Hobscure.Items; namespace Hobscure.UI { [Serializable] public class ItemContainerModel: iComponentModel { public Item item; public bool selected = false; public ItemContainerModel() { } public ItemContainerModel(Item _item, bool selected) { item = _item; } public ItemContainerModel Clone() { return new ItemContainerModel (this.item, this.selected); } } }
21.178571
70
0.561551
[ "Apache-2.0" ]
nahkranoth/DevilsTrinkets
Assets/GameWorld/UI/Components/ItemContainer/Scripts/Hobscure/UI/ItemContainerModel.cs
595
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Framework.Graphics.Sprites; using osu.Game.Beatmaps; using osu.Game.Rulesets.Osu.Objects; namespace osu.Game.Rulesets.Osu.Beatmaps { public class OsuBeatmap : Beatmap<OsuHitObject> { public override IEnumerable<BeatmapStatistic> GetStatistics() { int circles = HitObjects.Count(c => c is HitCircle); int sliders = HitObjects.Count(s => s is Slider); int spinners = HitObjects.Count(s => s is Spinner); return new[] { new BeatmapStatistic { Name = @"Circle Count", Content = circles.ToString(), Icon = FontAwesome.Regular.Circle }, new BeatmapStatistic { Name = @"Slider Count", Content = sliders.ToString(), Icon = FontAwesome.Regular.Circle }, new BeatmapStatistic { Name = @"Spinner Count", Content = spinners.ToString(), Icon = FontAwesome.Regular.Circle } }; } } }
33.181818
80
0.506164
[ "MIT" ]
123tris/osu
osu.Game.Rulesets.Osu/Beatmaps/OsuBeatmap.cs
1,419
C#
using System; using Newtonsoft.Json; using XamarinFormsClean.Common.Data.Converters.Json; using XamarinFormsClean.Common.Data.Model.Local; using XamarinFormsClean.Common.Data.Utils; namespace XamarinFormsClean.Feature.Authentication.Data.Model.Local { public class SessionData : BaseData { [JsonConverter(typeof(OptionJsonConverter<string>))] public Option<string> SessionId { get; set; } [JsonConverter(typeof(OptionJsonConverter<string>))] public Option<string> RequestToken { get; set; } public DateTime ExpiresAt { get; set; } public SessionData() { ExpiresAt = MachineTime.Now; } } }
29
67
0.678161
[ "MIT" ]
Bhekinkosi12/Xamarin.Forms-CleanArchitecture
src/Features/Authentication/XamarinFormsClean.Feature.Authentication.Data/Model/Local/SessionData.cs
696
C#
using UnityEngine; namespace ZenjectPrototype.Entities.Capabilities { public class PerfectReflector : IReflector { public void Reflect(IMovable movable, Vector3 normal) { var reflectedVelocity = Vector3.Reflect(movable.Velocity, normal); movable.Velocity = reflectedVelocity; } } }
24.571429
78
0.668605
[ "MIT" ]
Nitue/MirrorPuzzle
Assets/ZenjectPrototype/Scripts/Entities/Capabilities/PerfectReflector.cs
346
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the workspaces-web-2020-07-08.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.WorkSpacesWeb.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.WorkSpacesWeb.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DeleteNetworkSettings operation /// </summary> public class DeleteNetworkSettingsResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { DeleteNetworkSettingsResponse response = new DeleteNetworkSettingsResponse(); return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDeniedException")) { return AccessDeniedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ConflictException")) { return ConflictExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerException")) { return InternalServerExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ThrottlingException")) { return ThrottlingExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ValidationException")) { return ValidationExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonWorkSpacesWebException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static DeleteNetworkSettingsResponseUnmarshaller _instance = new DeleteNetworkSettingsResponseUnmarshaller(); internal static DeleteNetworkSettingsResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DeleteNetworkSettingsResponseUnmarshaller Instance { get { return _instance; } } } }
40.226087
196
0.657804
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/WorkSpacesWeb/Generated/Model/Internal/MarshallTransformations/DeleteNetworkSettingsResponseUnmarshaller.cs
4,626
C#
/* BIMserver.center license This file is part of BIMserver.center IFC frameworks. Copyright (c) 2017 BIMserver.center Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files, to use this software with the purpose of developing new tools for the BIMserver.center platform or interacting with it. 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. */ namespace BIMservercenter.Toolkit.Internal.API.Response.Schema { public class BSBaseSchema { public BSBaseSchema() { version = null; status = null; } public string version { get; set; } public string status { get; set; } } }
39.4375
80
0.749604
[ "MIT" ]
BIMservercenterDeveloper/BIMserver.center-unity-api
Assets/Packages/BIMserver.center Toolkit/Scripts/Internal/API/Response/Schema/BSBaseSchema.cs
1,264
C#
using System.Reflection; using System.Runtime.CompilerServices; 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("02.TwoGirlsOnePath")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("02.TwoGirlsOnePath")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("d240ba76-8d0b-4148-ae97-5fb14b2e0f34")] // 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.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.081081
84
0.745919
[ "MIT" ]
kossov/Telerik-Academy
C#/C#2/ExamPrep/C Part 2 20132014 24 Jan 2014 Evening STRANGELANDNUMBERS/02.TwoGirlsOnePath/Properties/AssemblyInfo.cs
1,412
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the synthetics-2017-10-11.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Synthetics.Model { /// <summary> /// Container for the parameters to the UntagResource operation. /// Removes one or more tags from the specified canary. /// </summary> public partial class UntagResourceRequest : AmazonSyntheticsRequest { private string _resourceArn; private List<string> _tagKeys = new List<string>(); /// <summary> /// Gets and sets the property ResourceArn. /// <para> /// The ARN of the canary that you're removing tags from. /// </para> /// /// <para> /// The ARN format of a canary is <code>arn:aws:synthetics:<i>Region</i>:<i>account-id</i>:canary:<i>canary-name</i> /// </code>. /// </para> /// </summary> [AWSProperty(Required=true)] public string ResourceArn { get { return this._resourceArn; } set { this._resourceArn = value; } } // Check to see if ResourceArn property is set internal bool IsSetResourceArn() { return this._resourceArn != null; } /// <summary> /// Gets and sets the property TagKeys. /// <para> /// The list of tag keys to remove from the resource. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=50)] public List<string> TagKeys { get { return this._tagKeys; } set { this._tagKeys = value; } } // Check to see if TagKeys property is set internal bool IsSetTagKeys() { return this._tagKeys != null && this._tagKeys.Count > 0; } } }
30.916667
124
0.61032
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Synthetics/Generated/Model/UntagResourceRequest.cs
2,597
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.Diagnostics.CodeAnalysis; using System.Diagnostics.ContractsLight; using System.Threading.Tasks; using BuildXL.App.Tracing; using BuildXL.FrontEnd.CMake; using BuildXL.Utilities; using BuildXL.Utilities.Instrumentation.Common; using BuildXL.Utilities.Tracing; using BuildXL.FrontEnd.Script.Evaluator.Profiling; using BuildXL.FrontEnd.Workspaces.Core; using BuildXL.Utilities.Configuration; using BuildXL.FrontEnd.Core; using BuildXL.FrontEnd.Download; using BuildXL.FrontEnd.Script; using BuildXL.FrontEnd.Script.Values; using BuildXL.FrontEnd.Script.Debugger; using BuildXL.FrontEnd.Script.Evaluator; using BuildXL.FrontEnd.Nuget; using BuildXL.FrontEnd.MsBuild; using BuildXL.FrontEnd.Sdk; using VSCode.DebugProtocol; using BuildXL.FrontEnd.Ninja; namespace BuildXL { /// <summary> /// "Yet another factory" (c) that is responsible for entire front-end construction. /// </summary> /// <remarks> /// This class glues together different lower level factories like <see cref="FrontEndFactory"/> and <see cref="DScriptWorkspaceResolverFactory"/> /// in order to hide all this complexity. /// </remarks> public sealed class FrontEndControllerFactory : IFrontEndControllerFactory { private readonly FrontEndMode m_mode; private readonly IFrontEndStatistics m_statistics; private bool CollectMemoryAsSoonAsPossible { get; } /// <nodoc /> public ICommandLineConfiguration Configuration { get; } /// <nodoc /> public LoggingContext LoggingContext { get; } /// <nodoc /> public PerformanceCollector Collector { get; } /// <nodoc /> private FrontEndControllerFactory( FrontEndMode mode, LoggingContext loggingContext, ICommandLineConfiguration configuration, PerformanceCollector collector, bool collectMemoryAsSoonAsPossible, IFrontEndStatistics statistics) { m_mode = mode; CollectMemoryAsSoonAsPossible = collectMemoryAsSoonAsPossible; Configuration = configuration; LoggingContext = loggingContext; Collector = collector; m_statistics = statistics; } /// <nodoc /> public IFrontEndController Create(PathTable pathTable, SymbolTable symbolTable) { if (m_mode == FrontEndMode.DebugScript) { return CreateControllerWithDebugger(pathTable, symbolTable); } if (m_mode == FrontEndMode.ProfileScript) { return CreateControllerWithProfiler(pathTable, symbolTable); } return CreateRegularController(symbolTable); } /// <nodoc /> public static FrontEndControllerFactory Create( FrontEndMode mode, LoggingContext loggingContext, ICommandLineConfiguration configuration, PerformanceCollector collector, bool collectMemoryAsSoonAsPossible = true, IFrontEndStatistics statistics = null) { return new FrontEndControllerFactory( mode, loggingContext, configuration, collector, collectMemoryAsSoonAsPossible, statistics); } private IFrontEndController CreateControllerWithProfiler(PathTable pathTable, SymbolTable symbolTable) { var frontEndFactory = new FrontEndFactory(); var profilerDecorator = new ProfilerDecorator(); // When evaluation is done we materialize the result of the profiler frontEndFactory.AddPhaseEndHook(EnginePhases.Evaluate, () => { var entries = profilerDecorator.GetProfiledEntries(); var materializer = new ProfilerMaterializer(pathTable); var reportDestination = Configuration.FrontEnd.ProfileReportDestination(pathTable); Logger.Log.MaterializingProfilerReport(LoggingContext, reportDestination.ToString(pathTable)); try { materializer.Materialize(entries, reportDestination); } catch (BuildXLException ex) { Logger.Log.ErrorMaterializingProfilerReport(LoggingContext, ex.LogEventErrorCode, ex.LogEventMessage); } }); return TryCreateFrontEndController( frontEndFactory, profilerDecorator, Configuration, symbolTable, LoggingContext, Collector, collectMemoryAsSoonAsPossible: CollectMemoryAsSoonAsPossible, statistics: m_statistics); } private IFrontEndController CreateControllerWithDebugger(PathTable pathTable, SymbolTable symbolTable) { var confPort = Configuration.FrontEnd.DebuggerPort(); var debugServerPort = confPort != 0 ? confPort : DebugServer.DefaultDebugPort; var pathTranslator = GetPathTranslator(Configuration.Logging, pathTable); var debugServer = new DebugServer(LoggingContext, pathTable, pathTranslator, debugServerPort); Task<IDebugger> debuggerTask = debugServer.StartAsync(); var evaluationDecorator = new LazyDecorator(debuggerTask, Configuration.FrontEnd.DebuggerBreakOnExit()); var frontEndFactory = new FrontEndFactory(); frontEndFactory.AddPhaseStartHook(EnginePhases.Evaluate, () => { if (!debuggerTask.IsCompleted) { Logger.Log.WaitingForClientDebuggerToConnect(LoggingContext, debugServer.Port); } debuggerTask.Result?.Session.WaitSessionInitialized(); }); frontEndFactory.AddPhaseEndHook(EnginePhases.Evaluate, () => { // make sure the debugger is shut down at the end (unnecessary in most cases, as the debugger will shut itself down after completion) debugServer.ShutDown(); debuggerTask.Result?.ShutDown(); }); return TryCreateFrontEndController( frontEndFactory, evaluationDecorator, Configuration, symbolTable, LoggingContext, Collector, collectMemoryAsSoonAsPossible: CollectMemoryAsSoonAsPossible, statistics: m_statistics); } private IFrontEndController CreateRegularController(SymbolTable symbolTable) { var frontEndFactory = new FrontEndFactory(); return TryCreateFrontEndController( frontEndFactory, decorator: null, configuration: Configuration, symbolTable: symbolTable, loggingContext: LoggingContext, collector: Collector, collectMemoryAsSoonAsPossible: CollectMemoryAsSoonAsPossible, statistics: m_statistics); } private static PathTranslator GetPathTranslator(ILoggingConfiguration conf, PathTable pathTable) { return conf.SubstTarget.IsValid && conf.SubstSource.IsValid ? new PathTranslator(conf.SubstTarget.ToString(pathTable), conf.SubstSource.ToString(pathTable)) : null; } [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Consumers should call Dispose explicitly")] private static IFrontEndController TryCreateFrontEndController( FrontEndFactory frontEndFactory, IDecorator<EvaluationResult> decorator, ICommandLineConfiguration configuration, SymbolTable symbolTable, LoggingContext loggingContext, PerformanceCollector collector, bool collectMemoryAsSoonAsPossible, IFrontEndStatistics statistics) { var workspaceResolverFactory = new DScriptWorkspaceResolverFactory(); Contract.Requires(frontEndFactory != null && !frontEndFactory.IsSealed); // Statistic should be global for all front-ends, not per an instance. var frontEndStatistics = statistics ?? new FrontEndStatistics(); var globalConstants = new GlobalConstants(symbolTable); var sharedModuleRegistry = new ModuleRegistry(); // Note, that the following code is absolutely critical for detecting that front-end related objects // are freed successfully after evaluation. // ModuleRegistry was picked intentionally because it holds vast amount of front-end data. FrontEndControllerMemoryObserver.CaptureFrontEndReference(sharedModuleRegistry); frontEndFactory.SetConfigurationProcessor( new ConfigurationProcessor(globalConstants, sharedModuleRegistry, logger: null)); var msBuildFrontEnd = new MsBuildFrontEnd( globalConstants, sharedModuleRegistry, frontEndStatistics); var ninjaFrontEnd = new NinjaFrontEnd( globalConstants, sharedModuleRegistry, frontEndStatistics); var cmakeFrontEnd = new CMakeFrontEnd( globalConstants, sharedModuleRegistry, frontEndStatistics); // TODO: Workspace resolvers and frontends are registered in separate factories. Consider // adding a main coordinator/registry RegisterKnownWorkspaceResolvers( workspaceResolverFactory, globalConstants, sharedModuleRegistry, frontEndStatistics, msBuildFrontEnd, ninjaFrontEnd, cmakeFrontEnd); frontEndFactory.AddFrontEnd(new DScriptFrontEnd( globalConstants, sharedModuleRegistry, frontEndStatistics, evaluationDecorator: decorator)); frontEndFactory.AddFrontEnd(new NugetFrontEnd( globalConstants, sharedModuleRegistry, frontEndStatistics, evaluationDecorator: decorator)); frontEndFactory.AddFrontEnd(new DownloadFrontEnd( globalConstants, sharedModuleRegistry)); frontEndFactory.AddFrontEnd(msBuildFrontEnd); frontEndFactory.AddFrontEnd(ninjaFrontEnd); frontEndFactory.AddFrontEnd(cmakeFrontEnd); if (!frontEndFactory.TrySeal(loggingContext)) { return null; } return new FrontEndHostController(frontEndFactory, workspaceResolverFactory, frontEndStatistics: frontEndStatistics, collector: collector, collectMemoryAsSoonAsPossible: collectMemoryAsSoonAsPossible); } private static void RegisterKnownWorkspaceResolvers( DScriptWorkspaceResolverFactory workspaceFactory, GlobalConstants constants, ModuleRegistry sharedModuleRegistry, IFrontEndStatistics statistics, MsBuildFrontEnd msBuildFrontEnd, NinjaFrontEnd ninjaFrontEnd, CMakeFrontEnd cmakeFrontend) { workspaceFactory.RegisterResolver( KnownResolverKind.SourceResolverKind, () => new WorkspaceSourceModuleResolver(constants, sharedModuleRegistry, statistics, logger: null)); workspaceFactory.RegisterResolver( KnownResolverKind.DScriptResolverKind, () => new WorkspaceSourceModuleResolver(constants, sharedModuleRegistry, statistics, logger: null)); workspaceFactory.RegisterResolver( KnownResolverKind.DefaultSourceResolverKind, () => new WorkspaceDefaultSourceModuleResolver(constants, sharedModuleRegistry, statistics, logger: null)); workspaceFactory.RegisterResolver( KnownResolverKind.NugetResolverKind, () => new WorkspaceNugetModuleResolver(constants, sharedModuleRegistry, statistics)); workspaceFactory.RegisterResolver( KnownResolverKind.DownloadResolverKind, () => new DownloadWorkspaceResolver(constants, sharedModuleRegistry)); workspaceFactory.RegisterResolver( KnownResolverKind.MsBuildResolverKind, () => new MsBuildWorkspaceResolver(constants, sharedModuleRegistry, statistics, msBuildFrontEnd)); workspaceFactory.RegisterResolver( KnownResolverKind.NinjaResolverKind, () => new NinjaWorkspaceResolver(constants, sharedModuleRegistry, statistics, ninjaFrontEnd)); workspaceFactory.RegisterResolver( KnownResolverKind.CMakeResolverKind, () => new CMakeWorkspaceResolver(constants, sharedModuleRegistry, statistics, cmakeFrontend, ninjaFrontEnd)); } } }
43.119122
153
0.627626
[ "MIT" ]
socat/BuildXL
Public/Src/App/Bxl/FrontEndControllerFactory.cs
13,755
C#
using System.Threading.Tasks; namespace RoomsService.Common.GetToken { public interface IGetTokenStrategy { Task<string> GetAsync(); } }
15.9
38
0.691824
[ "MIT" ]
gendalf90/WhenGunsSpeak
RoomsService/RoomsService/Common/GetToken/IGetTokenStrategy.cs
161
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.Billing.V20180709.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class DescribeBillDetailRequest : AbstractModel { /// <summary> /// 偏移量 /// </summary> [JsonProperty("Offset")] public ulong? Offset{ get; set; } /// <summary> /// 数量 /// </summary> [JsonProperty("Limit")] public ulong? Limit{ get; set; } /// <summary> /// 周期类型,byPayTime按扣费周期/byUsedTime按计费周期 /// </summary> [JsonProperty("PeriodType")] public string PeriodType{ get; set; } /// <summary> /// 月份,格式为yyyy-mm /// </summary> [JsonProperty("Month")] public string Month{ get; set; } /// <summary> /// 内部实现,用户禁止调用 /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "Offset", this.Offset); this.SetParamSimple(map, prefix + "Limit", this.Limit); this.SetParamSimple(map, prefix + "PeriodType", this.PeriodType); this.SetParamSimple(map, prefix + "Month", this.Month); } } }
29.692308
83
0.608808
[ "Apache-2.0" ]
geffzhang/tencentcloud-sdk-dotnet
TencentCloud/Billing/V20180709/Models/DescribeBillDetailRequest.cs
2,004
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 Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.Extensions.Hosting { /// <summary> /// A program initialization abstraction. /// </summary> public interface IHostBuilder { /// <summary> /// A central location for sharing state between components during the host building process. /// </summary> IDictionary<object, object> Properties { get; } /// <summary> /// Set up the configuration for the builder itself. This will be used to initialize the <see cref="IHostEnvironment"/> /// for use later in the build process. This can be called multiple times and the results will be additive. /// </summary> /// <param name="configureDelegate">The delegate for configuring the <see cref="IConfigurationBuilder"/> that will be used /// to construct the <see cref="IConfiguration"/> for the host.</param> /// <returns>The same instance of the <see cref="IHostBuilder"/> for chaining.</returns> IHostBuilder ConfigureHostConfiguration(Action<IConfigurationBuilder> configureDelegate); /// <summary> /// Sets up the configuration for the remainder of the build process and application. This can be called multiple times and /// the results will be additive. The results will be available at <see cref="HostBuilderContext.Configuration"/> for /// subsequent operations, as well as in <see cref="IHost.Services"/>. /// </summary> /// <param name="configureDelegate">The delegate for configuring the <see cref="IConfigurationBuilder"/> that will be used /// to construct the <see cref="IConfiguration"/> for the application.</param> /// <returns>The same instance of the <see cref="IHostBuilder"/> for chaining.</returns> IHostBuilder ConfigureAppConfiguration(Action<HostBuilderContext, IConfigurationBuilder> configureDelegate); /// <summary> /// Adds services to the container. This can be called multiple times and the results will be additive. /// </summary> /// <param name="configureDelegate">The delegate for configuring the <see cref="IServiceCollection"/> that will be used /// to construct the <see cref="IServiceProvider"/>.</param> /// <returns>The same instance of the <see cref="IHostBuilder"/> for chaining.</returns> IHostBuilder ConfigureServices(Action<HostBuilderContext, IServiceCollection> configureDelegate); /// <summary> /// Overrides the factory used to create the service provider. /// </summary> /// <typeparam name="TContainerBuilder">The type of builder.</typeparam> /// <param name="factory">The factory to register.</param> /// <returns>The same instance of the <see cref="IHostBuilder"/> for chaining.</returns> IHostBuilder UseServiceProviderFactory<TContainerBuilder>(IServiceProviderFactory<TContainerBuilder> factory); /// <summary> /// Overrides the factory used to create the service provider. /// </summary> /// <typeparam name="TContainerBuilder">The type of builder.</typeparam> /// <returns>The same instance of the <see cref="IHostBuilder"/> for chaining.</returns> IHostBuilder UseServiceProviderFactory<TContainerBuilder>(Func<HostBuilderContext, IServiceProviderFactory<TContainerBuilder>> factory); /// <summary> /// Enables configuring the instantiated dependency container. This can be called multiple times and /// the results will be additive. /// </summary> /// <typeparam name="TContainerBuilder">The type of builder.</typeparam> /// <param name="configureDelegate">The delegate which configures the builder.</param> /// <returns>The same instance of the <see cref="IHostBuilder"/> for chaining.</returns> IHostBuilder ConfigureContainer<TContainerBuilder>(Action<HostBuilderContext, TContainerBuilder> configureDelegate); /// <summary> /// Run the given actions to initialize the host. This can only be called once. /// </summary> /// <returns>An initialized <see cref="IHost"/>.</returns> IHost Build(); } }
56.5875
144
0.686768
[ "MIT" ]
06needhamt/runtime
src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/IHostBuilder.cs
4,527
C#
namespace Computers.Tests.CpusTests { using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using Computers.Logic.Cpus; using Moq; using Computers.Logic.MotherBoards; [TestClass] public class RandShouild { [TestMethod] public void NotProduseNumberLessTHanMin() { var cpu = new Cpu32(4); var motherBoardMock = new Mock<IMotherBoard>(); cpu.AttachTo(motherBoardMock.Object); var currentMin = int.MaxValue; motherBoardMock.Setup(x => x.SaveRamValue(It.IsAny<int>())) .Callback<int>(param => currentMin = Math.Min(currentMin, param)); for (int i = 0; i < 1000; i++) { cpu.Rand(1, 10); } Assert.AreEqual(1, currentMin); } [TestMethod] public void NotProduseNumberMoreThanMax() { var cpu = new Cpu32(4); var motherBoardMock = new Mock<IMotherBoard>(); cpu.AttachTo(motherBoardMock.Object); var currentMax = int.MinValue; motherBoardMock.Setup(x => x.SaveRamValue(It.IsAny<int>())) .Callback<int>(param => currentMax = Math.Max(currentMax, param)); for (int i = 0; i < 1000; i++) { cpu.Rand(1, 10); } Assert.AreEqual(10, currentMax); } [TestMethod] public void ReturnRandomNumbers() { var hashSet = new HashSet<int>(); var cpu = new Cpu32(4); var motherBoardMock = new Mock<IMotherBoard>(); cpu.AttachTo(motherBoardMock.Object); motherBoardMock.Setup(x => x.SaveRamValue(It.IsAny<int>())) .Callback<int>(param => hashSet.Add(param)); for (int i = 0; i < 10000; i++) { cpu.Rand(1, 10); } Assert.AreEqual(10, hashSet.Count); } } }
30.787879
82
0.530512
[ "MIT" ]
zachdimitrov/Learning_2017
Design-Patterns/ExamPrep-2015-Computers/Computers/Computers.Tests/CpusTests/RandShouild.cs
2,034
C#
// Copyright 2021 Yubico AB // // Licensed under the Apache License, Version 2.0 (the "License"). // You may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using Yubico.Core.Tlv; namespace Yubico.YubiKey.Sample.PivSampleCode { // This class demonstrates how to build an X500DistinguishedName object from // a collection of individual elements. // In the .NET Base Class Library (BCL), a name in a Cert Request or Cert // class is represented by either a string or an X500DistinguishedName // object. The string form will look something like this. // // string sampleRootName = "C=US,ST=CA,L=Palo Alto,O=Fake,CN=Fake Root"; // // This is not really documented in the .NET classes, but this format is // described in RFC 4514. The only documentation in the .NET classes says the // following. // // Properties // Name Gets the comma-delimited distinguished name from an X500 certificate. // // However, this string form is not supported on the Mac version of .NET. On // a Mac, this form will cause an exception to be thrown. On Mac, another // form (a form NOT listed in RFC 4514) will purportedly work. // // string sampleRootName = "C=US/ST=CA/L=Palo Alto/O=Fake/CN=Fake Root"; // // While using this form, .NET's implementation of certificate classes on Mac // will not throw an exception, unfortunately, it will not work. It ignores // the / separating character and considers this string to contain only one // element, namely the country of "US/ST=CA/L=Palo Alto/O=Fake/CN=Fake Root". // On a Mac, therefore, the only way to provide the name for a cert or // request is as an X500DistinguishedName object. Unfortunately, the only way // to build an X500DistinguishedName object is with a string or the DER // encoding of the name. // Hence, the only portable way to supply a name to the .NET classes is to // create the DER encoding of the name and use that to build the // X500DistinguishedName object. // This class will take in the individual elements and build the // X500DistinguishedName object. That is, the caller supplies each individual // name element, and this class will build the DER encoding, and then from // that encoding, build the Name object. // To use this class, instantiate, then call the Add method for each element. // Call the GetEncodedName method to get the DER encoding of the name, or // else call the GetNameObject method to get an X500DistinguishedName object. public class X500NameBuilder { internal const string InvalidElementMessage = "Invalid X500Name element"; internal const string InvalidNameMessage = "Invalid X500Name"; private readonly Dictionary<X500NameElement, byte[]> _elements; // The constructor creates an empty object. Call the Add method for each // element of the name you wish to add. // When you have added all the elements you want to add, call a Get // method. public X500NameBuilder() { _elements = new Dictionary<X500NameElement, byte[]>(); } // Add the given string value as the specified X500NameElement. // If you Add the same element twice, this method will throw an exception. public void AddNameElement(X500NameElement nameElement, string value) { if (!_elements.ContainsKey(nameElement)) { _elements.Add(nameElement, nameElement.GetDerEncoding(value)); return; } throw new ArgumentException(InvalidElementMessage); } // Get the DER encoding of the name. // If no elements had been added, this method will throw an exception. public byte[] GetEncodedName() { Array enumValues = Enum.GetValues(typeof(X500NameElement)); // The DER encoding is simply the SEQUENCE of each element. // Get each encoding in order. That is, no matter what order they // were added to _elements, get them out in the order of the Enum. int count = 0; var tlvWriter = new TlvWriter(); using (tlvWriter.WriteNestedTlv(0x30)) { foreach (X500NameElement nameElement in enumValues) { if (_elements.TryGetValue(nameElement, out byte[] encodedValue)) { tlvWriter.WriteEncoded(encodedValue); count++; } } } if (count > 0) { return tlvWriter.Encode(); } throw new ArgumentException(InvalidNameMessage); } // Get the name as an object of type X500DistinguishedName. // If no elements had been added, this method will throw an exception. public X500DistinguishedName GetDistinguishedName() { return new X500DistinguishedName(GetEncodedName()); } } // Currently supported name elements. // If you ever want to add an element, just add it. But don't forget to add // the extensions (OID, etc.). public enum X500NameElement { Country = 0, State = 1, Locality = 2, Organization = 3, CommonName = 4, } public static class X500NameElementExtensions { // Get the DER encoding of one name element. // This method currently treats all elements the same. It treats each // element as an ASCII string, and they are all encoded as the // following. // SET { // SEQ { // OID, // PrintableString // } // } // If you ever add an element that is encoded differently, update this // method. // This method will simply get the string as a CharArray (see String.ToCharArray), // then convert those chars into bytes by keeping only the low order byte. public static byte[] GetDerEncoding(this X500NameElement nameElement, string value) { byte[] valueBytes = Array.Empty<byte>(); if (!(value is null)) { // Convert the string to a byte array. char[] valueArray = value.ToCharArray(); valueBytes = new byte[valueArray.Length]; for (int index = 0; index < valueArray.Length; index++) { valueBytes[index] = (byte)valueArray[index]; } } if (nameElement.IsValidValueLength(valueBytes.Length)) { var tlvWriter = new TlvWriter(); using (tlvWriter.WriteNestedTlv(0x31)) { using (tlvWriter.WriteNestedTlv(0x30)) { tlvWriter.WriteValue(0x06, nameElement.GetOid()); tlvWriter.WriteValue(0x13, valueBytes); } } return tlvWriter.Encode(); } throw new ArgumentException(X500NameBuilder.InvalidElementMessage); } public static byte[] GetOid(this X500NameElement nameElement) => nameElement switch { X500NameElement.Country => new byte[] { 0x55, 0x04, 0x06 }, X500NameElement.State => new byte[] { 0x55, 0x04, 0x08 }, X500NameElement.Locality => new byte[] { 0x55, 0x04, 0x07 }, X500NameElement.Organization => new byte[] { 0x55, 0x04, 0x0A }, X500NameElement.CommonName => new byte[] { 0x55, 0x04, 0x03 }, _ => throw new ArgumentException(X500NameBuilder.InvalidElementMessage), }; // Is the given length valid for the specified nameElement? public static bool IsValidValueLength(this X500NameElement nameElement, int length) => nameElement switch { X500NameElement.Country => length == 2, X500NameElement.State => (length > 0) && (length < 32), X500NameElement.Locality => (length > 0) && (length < 32), X500NameElement.Organization => (length > 0) && (length < 64), X500NameElement.CommonName => (length > 0) && (length < 64), _ => throw new ArgumentException(X500NameBuilder.InvalidElementMessage), }; } }
42.816038
113
0.610995
[ "Apache-2.0" ]
Yubico/Yubico.NET.SDK
Yubico.YubiKey/examples/PivSampleCode/CertificateOperations/X500NameBuilder.cs
9,077
C#
using UnityEngine; using System; using System.Linq; using System.Collections.Generic; namespace SSM.GraphDrawing { [System.Serializable] public class GraphView { public List<Graph> graphs = new List<Graph>(); public GraphViewStyle style; public void RemoveGraph(Graph graph) { if (graphs.Contains(graph)) { graphs.Remove(graph); graph.DestroyLine(); } } public void AddGraph(Graph graph, LineStyle lineStyle = null) { if (graphs.Contains(graph)) { return; } if (style.lineStyleDefaults.Count < graphs.Count) { for (int i = style.lineStyleDefaults.Count; i < graphs.Count; i++) { style.lineStyleDefaults.Add(new LineStyle(style.lineStyleDefaults[0])); } } graphs.Add(graph); if (style.lineStyleDefaults.Count >= graphs.Count) { if (lineStyle != null) { style.lineStyleDefaults[graphs.Count - 1] = lineStyle; } } else { style.lineStyleDefaults.Add(lineStyle ?? new LineStyle(style.lineStyleDefaults[0])); } } } }
26.692308
100
0.493516
[ "MIT" ]
Anvoker/MicrogridPSO
Assets/Scripts/SSM.GraphDrawing/GraphView.cs
1,390
C#
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; using Microsoft.bliztafree.BuildingBlocks.Resilience.Http; using Microsoft.bliztafree.WebMVC.ViewModels; using Microsoft.Extensions.Options; using Newtonsoft.Json; using System.Collections.Generic; using System.Threading.Tasks; using WebMVC.Infrastructure; using WebMVC.Models; namespace Microsoft.bliztafree.WebMVC.Services { public class BasketService : IBasketService { private readonly IOptionsSnapshot<AppSettings> _settings; private IHttpClient _apiClient; private readonly string _remoteServiceBaseUrl; private IHttpContextAccessor _httpContextAccesor; public BasketService(IOptionsSnapshot<AppSettings> settings, IHttpContextAccessor httpContextAccesor, IHttpClient httpClient) { _settings = settings; _remoteServiceBaseUrl = $"{_settings.Value.BasketUrl}/api/v1/basket"; _httpContextAccesor = httpContextAccesor; _apiClient = httpClient; } public async Task<Basket> GetBasket(ApplicationUser user) { var token = await GetUserTokenAsync(); var getBasketUri = API.Basket.GetBasket(_remoteServiceBaseUrl, user.Id); var dataString = await _apiClient.GetStringAsync(getBasketUri, token); // Use the ?? Null conditional operator to simplify the initialization of response var response = JsonConvert.DeserializeObject<Basket>(dataString) ?? new Basket() { BuyerId = user.Id }; return response; } public async Task<Basket> UpdateBasket(Basket basket) { var token = await GetUserTokenAsync(); var updateBasketUri = API.Basket.UpdateBasket(_remoteServiceBaseUrl); var response = await _apiClient.PostAsync(updateBasketUri, basket, token); response.EnsureSuccessStatusCode(); return basket; } public async Task Checkout(BasketDTO basket) { var token = await GetUserTokenAsync(); var updateBasketUri = API.Basket.CheckoutBasket(_remoteServiceBaseUrl); var response = await _apiClient.PostAsync(updateBasketUri, basket, token); response.EnsureSuccessStatusCode(); } public async Task<Basket> SetQuantities(ApplicationUser user, Dictionary<string, int> quantities) { var basket = await GetBasket(user); basket.Items.ForEach(x => { // Simplify this logic by using the // new out variable initializer. if (quantities.TryGetValue(x.Id, out var quantity)) { x.Quantity = quantity; } }); return basket; } public Order MapBasketToOrder(Basket basket) { var order = new Order(); order.Total = 0; basket.Items.ForEach(x => { order.OrderItems.Add(new OrderItem() { ProductId = int.Parse(x.ProductId), PictureUrl = x.PictureUrl, ProductName = x.ProductName, Units = x.Quantity, UnitPrice = x.UnitPrice }); order.Total += (x.Quantity * x.UnitPrice); }); return order; } public async Task AddItemToBasket(ApplicationUser user, BasketItem product) { var basket = await GetBasket(user); if (basket == null) { basket = new Basket() { BuyerId = user.Id, Items = new List<BasketItem>() }; } basket.Items.Add(product); await UpdateBasket(basket); } async Task<string> GetUserTokenAsync() { var context = _httpContextAccesor.HttpContext; return await context.GetTokenAsync("access_token"); } } }
31.772727
133
0.579638
[ "MIT" ]
bliztafree/webdev
src/Web/WebMVC/Services/BasketService.cs
4,196
C#
#pragma checksum "..\..\BingMap.xaml" "{8829d00f-11b8-4213-878b-770e8597ac16}" "07A1BD0B17D5809FA7E890901C40D0CFD8C3827E1FCFCC3A268F1A46654A9E35" //------------------------------------------------------------------------------ // <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> //------------------------------------------------------------------------------ using MaterialDesignThemes.Wpf; using MaterialDesignThemes.Wpf.Converters; using MaterialDesignThemes.Wpf.Transitions; using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; using test; namespace test { /// <summary> /// BingMap /// </summary> public partial class BingMap : System.Windows.Window, System.Windows.Markup.IComponentConnector { private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/test;component/bingmap.xaml", System.UriKind.Relative); #line 1 "..\..\BingMap.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { this._contentLoaded = true; } } }
38.696203
146
0.675172
[ "MIT" ]
AmolDerickSoans/projekt-foo
test/test/obj/Debug/BingMap.g.i.cs
3,059
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text.Encodings.Web; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.WebUtilities; using LazZiya.ExpressLocalization; using LazZiya.ExpressLocalization.Messages; using LazZiya.ExpressLocalization.DataAnnotations; namespace ExpressLocalizationSampleCore3.Areas.Identity.Pages.Account { [AllowAnonymous] public class ForgotPasswordModel : PageModel { private readonly UserManager<IdentityUser> _userManager; private readonly IEmailSender _emailSender; private readonly SharedCultureLocalizer _loc; private readonly string culture; public ForgotPasswordModel(UserManager<IdentityUser> userManager, IEmailSender emailSender, SharedCultureLocalizer loc) { _userManager = userManager; _emailSender = emailSender; _loc = loc; culture = System.Globalization.CultureInfo.CurrentCulture.Name; } [BindProperty] public InputModel Input { get; set; } public class InputModel { [ExRequired] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } } public async Task<IActionResult> OnPostAsync() { if (ModelState.IsValid) { var user = await _userManager.FindByEmailAsync(Input.Email); if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) { // Don't reveal that the user does not exist or is not confirmed return RedirectToPage("./ForgotPasswordConfirmation", new { culture }); } // For more information on how to enable account confirmation and password reset please // visit https://go.microsoft.com/fwlink/?LinkID=532713 var code = await _userManager.GeneratePasswordResetTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ResetPassword", pageHandler: null, values: new { area = "Identity", code, culture }, protocol: Request.Scheme); var mailHeader = _loc.GetLocalizedString("Reset Password"); var mailBody = _loc.GetLocalizedString("Please reset your password by <a href='{0}'>clicking here</a>.", HtmlEncoder.Default.Encode(callbackUrl)); await _emailSender.SendEmailAsync( Input.Email, mailHeader, mailBody); return RedirectToPage("./ForgotPasswordConfirmation", new { culture }); } return Page(); } } }
37.60241
162
0.631528
[ "MIT" ]
SamChuang0305/ExpressLocalizationSampleCore3
ExpressLocalizationSampleCore3/Areas/Identity/Pages/Account/ForgotPassword.cshtml.cs
3,123
C#
// Copyright 2019 Cohesity Inc. 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; namespace Cohesity.Model { /// <summary> /// The daily schedule encompasses weekly schedules as well. This has been done so there is only one way of specifying a schedule (backing up daily is the same as backing up weekly, but on all days of the week). /// </summary> [DataContract] public partial class BackupPolicyProtoDailySchedule : IEquatable<BackupPolicyProtoDailySchedule> { /// <summary> /// Initializes a new instance of the <see cref="BackupPolicyProtoDailySchedule" /> class. /// </summary> /// <param name="days">The days of the week backup must be performed. If no days are specified, then the backup will be performed on all days..</param> /// <param name="time">time.</param> public BackupPolicyProtoDailySchedule(List<int> days = default(List<int>), Time time = default(Time)) { this.Days = days; this.Days = days; this.Time = time; } /// <summary> /// The days of the week backup must be performed. If no days are specified, then the backup will be performed on all days. /// </summary> /// <value>The days of the week backup must be performed. If no days are specified, then the backup will be performed on all days.</value> [DataMember(Name="days", EmitDefaultValue=true)] public List<int> Days { get; set; } /// <summary> /// Gets or Sets Time /// </summary> [DataMember(Name="time", EmitDefaultValue=false)] public Time Time { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { return ToJson(); } /// <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 BackupPolicyProtoDailySchedule); } /// <summary> /// Returns true if BackupPolicyProtoDailySchedule instances are equal /// </summary> /// <param name="input">Instance of BackupPolicyProtoDailySchedule to be compared</param> /// <returns>Boolean</returns> public bool Equals(BackupPolicyProtoDailySchedule input) { if (input == null) return false; return ( this.Days == input.Days || this.Days != null && input.Days != null && this.Days.SequenceEqual(input.Days) ) && ( this.Time == input.Time || (this.Time != null && this.Time.Equals(input.Time)) ); } /// <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.Days != null) hashCode = hashCode * 59 + this.Days.GetHashCode(); if (this.Time != null) hashCode = hashCode * 59 + this.Time.GetHashCode(); return hashCode; } } } }
35.516949
215
0.568599
[ "Apache-2.0" ]
DavidSeaton/cohesity-powershell-module
src/Cohesity.Powershell.Models/BackupPolicyProtoDailySchedule.cs
4,191
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the macie2-2020-01-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Macie2.Model { /// <summary> /// Provides information about an error that occurred due to a syntax error in a request. /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class ValidationException : AmazonMacie2Exception { /// <summary> /// Constructs a new ValidationException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public ValidationException(string message) : base(message) {} /// <summary> /// Construct instance of ValidationException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public ValidationException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of ValidationException /// </summary> /// <param name="innerException"></param> public ValidationException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of ValidationException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public ValidationException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of ValidationException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public ValidationException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !NETSTANDARD /// <summary> /// Constructs a new instance of the ValidationException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected ValidationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); } #endif } }
46.701613
178
0.676567
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Macie2/Generated/Model/ValidationException.cs
5,791
C#
using UnityEngine; using System.Collections; /// <summary> /// Controller responsbile to mimics the Mortal Kombat's Toasty! easter egg. /// </summary> public class ToastyController : MonoBehaviour { #region Fields private AudioSource m_audio; private Vector2 m_currentTargetPosition; private float m_currentSpeed; #endregion #region Editor properties public float WarmupSeconds = 2f; public Vector3 MoveSize = new Vector3(85, 0, 0); public float SlideInSpeed = 0.5f; public float SlideOutSpeed = 1f; #endregion #region Methods void Awake() { m_audio = GetComponentInChildren<AudioSource> (); } void Update () { // Update the Toasty's sprite in direction of the target position. transform.position = Vector2.Lerp (transform.position, m_currentTargetPosition, m_currentSpeed); } void OnEnable() { // Everty time that became enabled, starts the slide. StartCoroutine (Slide ()); } /// <summary> /// Perform the slide of the Toasty's sprite. /// </summary> /// <returns>The enumerator.</returns> private IEnumerator Slide() { // Put the game object in the initial position and wait the warmup seconds. m_currentTargetPosition = transform.position; yield return new WaitForSeconds (WarmupSeconds); // The sound duration will be used as time of the slide. var slideSeconds = m_audio.clip.length; // Slide in. Sets the target position (used on Update method) and play sound. m_currentTargetPosition = transform.position - MoveSize; m_currentSpeed = SlideInSpeed; m_audio.Play (); // Wait for the sound finish. yield return new WaitForSeconds (slideSeconds); // Slide out. Sets the target position back to out of the screen. m_currentTargetPosition = transform.position + MoveSize; m_currentSpeed = SlideOutSpeed; yield return new WaitForSeconds (slideSeconds); // Deactivate the game object, then it can be used a next time. gameObject.SetActive(false); } #endregion }
29.385714
98
0.701021
[ "MIT" ]
skahal/Buildron-Mod-Samples
src/Code/ToastyMod/ToastyController.cs
2,059
C#
using System; namespace LinqToDB.SchemaProvider { /// <summary> /// Database procedure or function parameter description. /// </summary> public class ProcedureParameterInfo { /// <summary> /// Gets or sets unique procedure identifier. /// NOTE: this is not fully-qualified procedure name (even if it used right now for some providers as procedure identifier). /// </summary> public string ProcedureID; /// <summary> /// Gets or sets parameter position. /// </summary> public int Ordinal; /// <summary> /// Gets or sets parameter name. /// </summary> public string ParameterName; /// <summary> /// Get or sets database type for parameter. /// </summary> public string DataType; /// <summary> /// Gets or sets parameter type length attribute. /// </summary> public long? Length; /// <summary> /// Gets or sets parameter type precision attribute. /// </summary> public int? Precision; /// <summary> /// Gets or sets parameter type scale attribute. /// </summary> public int? Scale; /// <summary> /// Gets or sets input or input-output parameter flag. /// </summary> public bool IsIn; /// <summary> /// Gets or sets output or input-output parameter flag. /// </summary> public bool IsOut; /// <summary> /// Gets or sets return value parameter flag. /// </summary> public bool IsResult; } }
27.207547
127
0.626214
[ "MIT" ]
BlackballSoftware/linq2db
Source/LinqToDB/SchemaProvider/ProcedureParameterInfo.cs
1,444
C#
using System; using System.Collections.Generic; using System.Linq; namespace KnightsOfHonor { class Program { static void Main(string[] args) { Action<string> print = n => Console.WriteLine($"Sir {n}"); var input = Console.ReadLine().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); input.ToList().ForEach(print); } } }
23
110
0.599034
[ "MIT" ]
valkin88/CSharp-Fundamentals
CSharp Advanced/Functional Programming - Exercises/KnightsOfHonor/KnightsOfHonor/Program.cs
416
C#
namespace GuiLabs.Editor.Sample { partial class TutorialForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.RootList = new GuiLabs.Editor.UI.ViewWindow(); this.BlockView = new GuiLabs.Editor.UI.ViewWindow(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.SuspendLayout(); // // splitContainer1 // this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.Location = new System.Drawing.Point(0, 0); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.RootList); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.BlockView); this.splitContainer1.Size = new System.Drawing.Size(920, 656); this.splitContainer1.SplitterDistance = 197; this.splitContainer1.TabIndex = 0; // // RootList // this.RootList.Dock = System.Windows.Forms.DockStyle.Fill; this.RootList.Location = new System.Drawing.Point(0, 0); this.RootList.Name = "RootList"; this.RootList.ShowScrollbars = false; this.RootList.Size = new System.Drawing.Size(197, 656); this.RootList.TabIndex = 0; // // BlockView // this.BlockView.Dock = System.Windows.Forms.DockStyle.Fill; this.BlockView.Location = new System.Drawing.Point(0, 0); this.BlockView.Name = "BlockView"; this.BlockView.ShowScrollbars = true; this.BlockView.Size = new System.Drawing.Size(719, 656); this.BlockView.TabIndex = 1; // // TutorialForm // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(920, 656); this.Controls.Add(this.splitContainer1); this.Name = "TutorialForm"; this.Text = "TutorialForm"; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); this.splitContainer1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.SplitContainer splitContainer1; private GuiLabs.Editor.UI.ViewWindow RootList; private GuiLabs.Editor.UI.ViewWindow BlockView; } }
32.907216
102
0.690789
[ "MIT" ]
KirillOsenkov/StructuredEditor
SampleEditor/Tutorial/TutorialForm.Designer.cs
3,192
C#
using System; using Nest; namespace Tests.Mapping.Types.Complex.Object { public class ObjectTest { public class InnerObject { public string Name { get; set; } } [Object( Enabled = true)] public InnerObject Full { get; set; } [Object] public InnerObject Minimal { get; set; } } public class ObjectAttributeTests : AttributeTestsBase<ObjectTest> { protected override object ExpectJson => new { properties = new { full = new { type = "object", enabled = true, properties = new { name = new { type = "text", fields = new { keyword = new { type = "keyword", ignore_above = 256 } } } } }, minimal = new { type = "object", properties = new { name = new { type = "text", fields = new { keyword = new { type = "keyword", ignore_above = 256 } } } } } } }; } }
14.871429
67
0.486071
[ "Apache-2.0" ]
Tchami/elasticsearch-net
src/Tests/Mapping/Types/Complex/Object/ObjectAttributeTests.cs
1,043
C#
namespace CoursesSystem.Server.Models.Users { using CoursesSystem.Data.Models; using CoursesSystem.Server.Infrastructure.Mapping; public class UserRequestModel : IMapFrom<User> { public string FirstName { get; set; } public string LastName { get; set; } public bool IsEmployeer { get; set; } public int Age { get; set; } public bool IsMale { get; set; } public string Address { get; set; } public string PhoneNumber { get; set; } public string Email { get; set; } } }
23.333333
54
0.621429
[ "MIT" ]
g-yonchev/CoursesSystem
CoursesSystem/CoursesSystem.Server/Models/Users/UserRequestModel.cs
562
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager; using Azure.ResourceManager.Core; using Azure.ResourceManager.Network.Models; using Azure.ResourceManager.Resources; namespace Azure.ResourceManager.Network { /// <summary> A class representing collection of BastionHost and their operations over its parent. </summary> public partial class BastionHostCollection : ArmCollection, IEnumerable<BastionHost>, IAsyncEnumerable<BastionHost> { private readonly ClientDiagnostics _clientDiagnostics; private readonly BastionHostsRestOperations _bastionHostsRestClient; /// <summary> Initializes a new instance of the <see cref="BastionHostCollection"/> class for mocking. </summary> protected BastionHostCollection() { } /// <summary> Initializes a new instance of the <see cref="BastionHostCollection"/> class. </summary> /// <param name="parent"> The resource representing the parent resource. </param> internal BastionHostCollection(ArmResource parent) : base(parent) { _clientDiagnostics = new ClientDiagnostics(ClientOptions); ClientOptions.TryGetApiVersion(BastionHost.ResourceType, out string apiVersion); _bastionHostsRestClient = new BastionHostsRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri, apiVersion); #if DEBUG ValidateResourceId(Id); #endif } internal static void ValidateResourceId(ResourceIdentifier id) { if (id.ResourceType != ResourceGroup.ResourceType) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceGroup.ResourceType), nameof(id)); } // Collection level operations. /// <summary> Creates or updates the specified Bastion Host. </summary> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="bastionHostName"> The name of the Bastion Host. </param> /// <param name="parameters"> Parameters supplied to the create or update Bastion Host operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="bastionHostName"/> or <paramref name="parameters"/> is null. </exception> public virtual BastionHostCreateOrUpdateOperation CreateOrUpdate(bool waitForCompletion, string bastionHostName, BastionHostData parameters, CancellationToken cancellationToken = default) { if (bastionHostName == null) { throw new ArgumentNullException(nameof(bastionHostName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var scope = _clientDiagnostics.CreateScope("BastionHostCollection.CreateOrUpdate"); scope.Start(); try { var response = _bastionHostsRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, bastionHostName, parameters, cancellationToken); var operation = new BastionHostCreateOrUpdateOperation(this, _clientDiagnostics, Pipeline, _bastionHostsRestClient.CreateCreateOrUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, bastionHostName, parameters).Request, response); if (waitForCompletion) operation.WaitForCompletion(cancellationToken); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Creates or updates the specified Bastion Host. </summary> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="bastionHostName"> The name of the Bastion Host. </param> /// <param name="parameters"> Parameters supplied to the create or update Bastion Host operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="bastionHostName"/> or <paramref name="parameters"/> is null. </exception> public async virtual Task<BastionHostCreateOrUpdateOperation> CreateOrUpdateAsync(bool waitForCompletion, string bastionHostName, BastionHostData parameters, CancellationToken cancellationToken = default) { if (bastionHostName == null) { throw new ArgumentNullException(nameof(bastionHostName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var scope = _clientDiagnostics.CreateScope("BastionHostCollection.CreateOrUpdate"); scope.Start(); try { var response = await _bastionHostsRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, bastionHostName, parameters, cancellationToken).ConfigureAwait(false); var operation = new BastionHostCreateOrUpdateOperation(this, _clientDiagnostics, Pipeline, _bastionHostsRestClient.CreateCreateOrUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, bastionHostName, parameters).Request, response); if (waitForCompletion) await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets the specified Bastion Host. </summary> /// <param name="bastionHostName"> The name of the Bastion Host. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="bastionHostName"/> is null. </exception> public virtual Response<BastionHost> Get(string bastionHostName, CancellationToken cancellationToken = default) { if (bastionHostName == null) { throw new ArgumentNullException(nameof(bastionHostName)); } using var scope = _clientDiagnostics.CreateScope("BastionHostCollection.Get"); scope.Start(); try { var response = _bastionHostsRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, bastionHostName, cancellationToken); if (response.Value == null) throw _clientDiagnostics.CreateRequestFailedException(response.GetRawResponse()); return Response.FromValue(new BastionHost(this, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets the specified Bastion Host. </summary> /// <param name="bastionHostName"> The name of the Bastion Host. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="bastionHostName"/> is null. </exception> public async virtual Task<Response<BastionHost>> GetAsync(string bastionHostName, CancellationToken cancellationToken = default) { if (bastionHostName == null) { throw new ArgumentNullException(nameof(bastionHostName)); } using var scope = _clientDiagnostics.CreateScope("BastionHostCollection.Get"); scope.Start(); try { var response = await _bastionHostsRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, bastionHostName, cancellationToken).ConfigureAwait(false); if (response.Value == null) throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false); return Response.FromValue(new BastionHost(this, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Tries to get details for this resource from the service. </summary> /// <param name="bastionHostName"> The name of the Bastion Host. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="bastionHostName"/> is null. </exception> public virtual Response<BastionHost> GetIfExists(string bastionHostName, CancellationToken cancellationToken = default) { if (bastionHostName == null) { throw new ArgumentNullException(nameof(bastionHostName)); } using var scope = _clientDiagnostics.CreateScope("BastionHostCollection.GetIfExists"); scope.Start(); try { var response = _bastionHostsRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, bastionHostName, cancellationToken: cancellationToken); if (response.Value == null) return Response.FromValue<BastionHost>(null, response.GetRawResponse()); return Response.FromValue(new BastionHost(this, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Tries to get details for this resource from the service. </summary> /// <param name="bastionHostName"> The name of the Bastion Host. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="bastionHostName"/> is null. </exception> public async virtual Task<Response<BastionHost>> GetIfExistsAsync(string bastionHostName, CancellationToken cancellationToken = default) { if (bastionHostName == null) { throw new ArgumentNullException(nameof(bastionHostName)); } using var scope = _clientDiagnostics.CreateScope("BastionHostCollection.GetIfExists"); scope.Start(); try { var response = await _bastionHostsRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, bastionHostName, cancellationToken: cancellationToken).ConfigureAwait(false); if (response.Value == null) return Response.FromValue<BastionHost>(null, response.GetRawResponse()); return Response.FromValue(new BastionHost(this, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Tries to get details for this resource from the service. </summary> /// <param name="bastionHostName"> The name of the Bastion Host. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="bastionHostName"/> is null. </exception> public virtual Response<bool> Exists(string bastionHostName, CancellationToken cancellationToken = default) { if (bastionHostName == null) { throw new ArgumentNullException(nameof(bastionHostName)); } using var scope = _clientDiagnostics.CreateScope("BastionHostCollection.Exists"); scope.Start(); try { var response = GetIfExists(bastionHostName, cancellationToken: cancellationToken); return Response.FromValue(response.Value != null, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Tries to get details for this resource from the service. </summary> /// <param name="bastionHostName"> The name of the Bastion Host. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="bastionHostName"/> is null. </exception> public async virtual Task<Response<bool>> ExistsAsync(string bastionHostName, CancellationToken cancellationToken = default) { if (bastionHostName == null) { throw new ArgumentNullException(nameof(bastionHostName)); } using var scope = _clientDiagnostics.CreateScope("BastionHostCollection.Exists"); scope.Start(); try { var response = await GetIfExistsAsync(bastionHostName, cancellationToken: cancellationToken).ConfigureAwait(false); return Response.FromValue(response.Value != null, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Lists all Bastion Hosts in a resource group. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> A collection of <see cref="BastionHost" /> that may take multiple service requests to iterate over. </returns> public virtual Pageable<BastionHost> GetAll(CancellationToken cancellationToken = default) { Page<BastionHost> FirstPageFunc(int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("BastionHostCollection.GetAll"); scope.Start(); try { var response = _bastionHostsRestClient.ListByResourceGroup(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken: cancellationToken); return Page.FromValues(response.Value.Value.Select(value => new BastionHost(this, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } Page<BastionHost> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("BastionHostCollection.GetAll"); scope.Start(); try { var response = _bastionHostsRestClient.ListByResourceGroupNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, cancellationToken: cancellationToken); return Page.FromValues(response.Value.Value.Select(value => new BastionHost(this, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> Lists all Bastion Hosts in a resource group. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> An async collection of <see cref="BastionHost" /> that may take multiple service requests to iterate over. </returns> public virtual AsyncPageable<BastionHost> GetAllAsync(CancellationToken cancellationToken = default) { async Task<Page<BastionHost>> FirstPageFunc(int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("BastionHostCollection.GetAll"); scope.Start(); try { var response = await _bastionHostsRestClient.ListByResourceGroupAsync(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken: cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value.Select(value => new BastionHost(this, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } async Task<Page<BastionHost>> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("BastionHostCollection.GetAll"); scope.Start(); try { var response = await _bastionHostsRestClient.ListByResourceGroupNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, cancellationToken: cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value.Select(value => new BastionHost(this, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> Filters the list of <see cref="BastionHost" /> for this resource group represented as generic resources. </summary> /// <param name="nameFilter"> The filter used in this operation. </param> /// <param name="expand"> Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. </param> /// <param name="top"> The number of results to return. </param> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> /// <returns> A collection of resource that may take multiple service requests to iterate over. </returns> public virtual Pageable<GenericResource> GetAllAsGenericResources(string nameFilter, string expand = null, int? top = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("BastionHostCollection.GetAllAsGenericResources"); scope.Start(); try { var filters = new ResourceFilterCollection(BastionHost.ResourceType); filters.SubstringFilter = nameFilter; return ResourceListOperations.GetAtContext(Parent as ResourceGroup, filters, expand, top, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Filters the list of <see cref="BastionHost" /> for this resource group represented as generic resources. </summary> /// <param name="nameFilter"> The filter used in this operation. </param> /// <param name="expand"> Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. </param> /// <param name="top"> The number of results to return. </param> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> /// <returns> An async collection of resource that may take multiple service requests to iterate over. </returns> public virtual AsyncPageable<GenericResource> GetAllAsGenericResourcesAsync(string nameFilter, string expand = null, int? top = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("BastionHostCollection.GetAllAsGenericResources"); scope.Start(); try { var filters = new ResourceFilterCollection(BastionHost.ResourceType); filters.SubstringFilter = nameFilter; return ResourceListOperations.GetAtContextAsync(Parent as ResourceGroup, filters, expand, top, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } IEnumerator<BastionHost> IEnumerable<BastionHost>.GetEnumerator() { return GetAll().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetAll().GetEnumerator(); } IAsyncEnumerator<BastionHost> IAsyncEnumerable<BastionHost>.GetAsyncEnumerator(CancellationToken cancellationToken) { return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); } // Builders. // public ArmBuilder<Azure.Core.ResourceIdentifier, BastionHost, BastionHostData> Construct() { } } }
51.347518
248
0.629098
[ "MIT" ]
BaherAbdullah/azure-sdk-for-net
sdk/network/Azure.ResourceManager.Network/src/Generated/BastionHostCollection.cs
21,720
C#
using Xunit; namespace Challenges.Tests { public class ArrayShiftTests { [Fact] public void Can_shift_into_even_length() { // Arrange int[] input = new[] { 1, 2, 4, 5 }; // Act int[] result = ArrayChallenges.ArrayShift(input, 3); // Assert Assert.Equal(new[] { 1, 2, 3, 4, 5 }, result); } [Fact] public void Can_shift_into_odd_length() { // Arrange int[] input = new[] { 1, 2, 3, 5, 6 }; // Act int[] result = ArrayChallenges.ArrayShift(input, 4); // Assert Assert.Equal(new[] { 1, 2, 3, 4, 5, 6 }, result); } [Theory] [InlineData(1, new int[0], new[] { 1 })] // Even (Zero) [InlineData(2, new int[0], new[] { 2 })] [InlineData(3, new int[] { 2 }, new[] { 2, 3 })] // Odd (1) [InlineData(3, new int[] { 2, 4 }, new[] { 2, 3, 4 })] // Even (2) [InlineData(4, new int[] { 1, 2, 3, 5, 6 }, new[] { 1, 2, 3, 4, 5, 6 })] // Odd (5) public void Can_shift(int value, int[] input, int[] expected) { // Arrange // from parameters // Act int[] result = ArrayChallenges.ArrayShift(input, value); // Assert Assert.Equal(expected, result); } [Fact] public void Returns_null_given_null() { int[] result = ArrayChallenges.ArrayShift(null, 1); Assert.Null(result); } } }
26.433333
91
0.453972
[ "MIT" ]
TheAgileMCB/cr-dotnet-401d1
Class02/demo/Challenges.Tests/ArrayShiftTests.cs
1,586
C#
using System.Reflection; using System.Runtime.CompilerServices; 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("Softwarekueche.MimeTypeDetective.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Softwarekueche.MimeTypeDetective.Tests")] [assembly: AssemblyCopyright("Copyright © Microsoft 2014")] [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("90cf10bb-7f43-4820-b862-7ff13e9aa41e")] // 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.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.648649
84
0.754601
[ "Apache-2.0" ]
awesome-inc/MimeTypeDetective
Softwarekueche.MimeTypeDetective.Tests/Properties/AssemblyInfo.cs
1,470
C#
using Tera.Game.Messages; using RichPresence = Tera.RichPresence.RichPresence; namespace DamageMeter.Processing { internal class S_CREATURE_CHANGE_HP { internal S_CREATURE_CHANGE_HP(SCreatureChangeHp message) { HudManager.Instance.UpdateBoss(message); PacketProcessor.Instance.AbnormalityTracker.Update(message); NotifyProcessor.Instance.S_CREATURE_CHANGE_HP(message); RichPresence.Instance.HandleBossHp(message); } } }
29.764706
72
0.709486
[ "MIT" ]
tmopcode/ShinraMeter_beta_kr
DamageMeter.Core/Processing/S_CREATURE_CHANGE_HP.cs
508
C#
using System; namespace Packages.Rider.Editor.ProjectGeneration { [Flags] enum ProjectGenerationFlag { None = 0, Embedded = 1, Local = 2, Registry = 4, Git = 8, BuiltIn = 16, Unknown = 32, PlayerAssemblies = 64, LocalTarBall = 128, } }
14.789474
49
0.604982
[ "MIT" ]
11xdev-coder/Snek
Library/PackageCache/com.unity.ide.rider@2.0.7/Rider/Editor/ProjectGeneration/ProjectGenerationFlag.cs
281
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. // // Generated on 2020 October 09 06:00:26 UTC // </auto-generated> //--------------------------------------------------------- using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using go; #nullable enable namespace go { namespace cmd { namespace vendor { namespace golang.org { namespace x { namespace sys { public static partial class unix_package { [GeneratedCode("go2cs", "0.1.0.0")] public partial struct FdSet { // Constructors public FdSet(NilType _) { this.Bits = default; } public FdSet(array<int> Bits = default) { this.Bits = Bits; } // Enable comparisons between nil and FdSet struct [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(FdSet value, NilType nil) => value.Equals(default(FdSet)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(FdSet value, NilType nil) => !(value == nil); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NilType nil, FdSet value) => value == nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NilType nil, FdSet value) => value != nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator FdSet(NilType nil) => default(FdSet); } [GeneratedCode("go2cs", "0.1.0.0")] public static FdSet FdSet_cast(dynamic value) { return new FdSet(value.Bits); } } }}}}}}
30.727273
101
0.578895
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/cmd/vendor/golang.org/x/sys/unix/ztypes_aix_ppc_FdSetStruct.cs
2,028
C#
using System.Drawing; using ImageProcessing.App.ServiceLayer.ServiceModel.Visitors.BitmapLuminance.Interface; namespace ImageProcessing.App.ServiceLayer.ServiceModel.Visitable.BitmapLuminance { public interface IBitmapLuminanceVisitable : IVisitable<IBitmapLuminanceVisitable, IBitmapLuminanceVisitor> { decimal GetInfo(Bitmap bmp); } }
28.230769
87
0.798365
[ "Apache-2.0" ]
Softenraged/Image-Processing
Source/ImageProcessing.App.ServiceLayer/ServiceModel/Visitable/BitmapLuminance/IBitmapLuminanceVisitable.cs
367
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace MiniBank { using System; using System.Collections.Generic; public partial class Bank_Transaction { public int TransactionID { get; set; } public Nullable<int> AccountID { get; set; } public Nullable<decimal> Amount { get; set; } public string Reference { get; set; } public Nullable<int> TransactionType { get; set; } public Nullable<decimal> PreviousBalance { get; set; } public Nullable<decimal> NewBalance { get; set; } public Nullable<System.DateTime> TransactionDate { get; set; } } }
37.518519
85
0.556762
[ "MIT" ]
aesmailsparta/MiniBank_ASP.NET_Framework_Website
MiniBank/MiniBank/Bank_Transaction.cs
1,013
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { #region Bind All Attributes // Method to bind attributes types early for all attributes to enable early decoding of some well-known attributes used within the binder. // Note: attributesToBind contains merged attributes from all the different syntax locations (e.g. for named types, partial methods, etc.). // Note: Additionally, the attributes with non-matching target specifier for the given owner symbol have been filtered out, i.e. Binder.MatchAttributeTarget method returned true. // For example, if were binding attributes on delegate type symbol for below code snippet: // [A1] // [return: A2] // public delegate void Goo(); // attributesToBind will only contain first attribute syntax. internal static void BindAttributeTypes(ImmutableArray<Binder> binders, ImmutableArray<AttributeSyntax> attributesToBind, Symbol ownerSymbol, NamedTypeSymbol[] boundAttributeTypes, DiagnosticBag diagnostics) { Debug.Assert(binders.Any()); Debug.Assert(attributesToBind.Any()); Debug.Assert((object)ownerSymbol != null); Debug.Assert(binders.Length == attributesToBind.Length); Debug.Assert(boundAttributeTypes != null); for (int i = 0; i < attributesToBind.Length; i++) { // Some types may have been bound by an earlier stage. if ((object)boundAttributeTypes[i] == null) { var binder = binders[i]; // BindType for AttributeSyntax's name is handled specially during lookup, see Binder.LookupAttributeType. // When looking up a name in attribute type context, we generate a diagnostic + error type if it is not an attribute type, i.e. named type deriving from System.Attribute. // Hence we can assume here that BindType returns a NamedTypeSymbol. boundAttributeTypes[i] = (NamedTypeSymbol)binder.BindType(attributesToBind[i].Name, diagnostics).Type; } } } // Method to bind all attributes (attribute arguments and constructor) internal static void GetAttributes( ImmutableArray<Binder> binders, ImmutableArray<AttributeSyntax> attributesToBind, ImmutableArray<NamedTypeSymbol> boundAttributeTypes, CSharpAttributeData[] attributesBuilder, DiagnosticBag diagnostics) { Debug.Assert(binders.Any()); Debug.Assert(attributesToBind.Any()); Debug.Assert(boundAttributeTypes.Any()); Debug.Assert(binders.Length == attributesToBind.Length); Debug.Assert(boundAttributeTypes.Length == attributesToBind.Length); Debug.Assert(attributesBuilder != null); for (int i = 0; i < attributesToBind.Length; i++) { AttributeSyntax attributeSyntax = attributesToBind[i]; NamedTypeSymbol boundAttributeType = boundAttributeTypes[i]; Binder binder = binders[i]; var attribute = (SourceAttributeData)attributesBuilder[i]; if (attribute == null) { attributesBuilder[i] = binder.GetAttribute(attributeSyntax, boundAttributeType, diagnostics); } else { // attributesBuilder might contain some early bound well-known attributes, which had no errors. // We don't rebind the early bound attributes, but need to compute isConditionallyOmitted. // Note that AttributeData.IsConditionallyOmitted is required only during emit, but must be computed here as // its value depends on the values of conditional symbols, which in turn depends on the source file where the attribute is applied. Debug.Assert(!attribute.HasErrors); HashSet<DiagnosticInfo> useSiteDiagnostics = null; bool isConditionallyOmitted = binder.IsAttributeConditionallyOmitted(attribute.AttributeClass, attributeSyntax.SyntaxTree, ref useSiteDiagnostics); diagnostics.Add(attributeSyntax, useSiteDiagnostics); attributesBuilder[i] = attribute.WithOmittedCondition(isConditionallyOmitted); } } } #endregion #region Bind Single Attribute internal CSharpAttributeData GetAttribute(AttributeSyntax node, NamedTypeSymbol boundAttributeType, DiagnosticBag diagnostics) { var boundAttribute = new ExecutableCodeBinder(node, this.ContainingMemberOrLambda, this).BindAttribute(node, boundAttributeType, diagnostics); return GetAttribute(boundAttribute, diagnostics); } internal BoundAttribute BindAttribute(AttributeSyntax node, NamedTypeSymbol attributeType, DiagnosticBag diagnostics) { return this.GetBinder(node).BindAttributeCore(node, attributeType, diagnostics); } private Binder SkipSemanticModelBinder() { Binder result = this; while (result.IsSemanticModelBinder) { result = result.Next; } return result; } private BoundAttribute BindAttributeCore(AttributeSyntax node, NamedTypeSymbol attributeType, DiagnosticBag diagnostics) { Debug.Assert(this.SkipSemanticModelBinder() == this.GetBinder(node).SkipSemanticModelBinder()); // If attribute name bound to an error type with a single named type // candidate symbol, we want to bind the attribute constructor // and arguments with that named type to generate better semantic info. // CONSIDER: Do we need separate code paths for IDE and // CONSIDER: batch compilation scenarios? Above mentioned scenario // CONSIDER: is not useful for batch compilation. NamedTypeSymbol attributeTypeForBinding = attributeType; LookupResultKind resultKind = LookupResultKind.Viable; if (attributeTypeForBinding.IsErrorType()) { var errorType = (ErrorTypeSymbol)attributeTypeForBinding; resultKind = errorType.ResultKind; if (errorType.CandidateSymbols.Length == 1 && errorType.CandidateSymbols[0] is NamedTypeSymbol) { attributeTypeForBinding = (NamedTypeSymbol)errorType.CandidateSymbols[0]; } } // Bind constructor and named attribute arguments using the attribute binder var argumentListOpt = node.ArgumentList; Binder attributeArgumentBinder = this.WithAdditionalFlags(BinderFlags.AttributeArgument); AnalyzedAttributeArguments analyzedArguments = attributeArgumentBinder.BindAttributeArguments(argumentListOpt, attributeTypeForBinding, diagnostics); HashSet<DiagnosticInfo> useSiteDiagnostics = null; ImmutableArray<int> argsToParamsOpt = default; bool expanded = false; MethodSymbol attributeConstructor = null; // Bind attributeType's constructor based on the bound constructor arguments if (!attributeTypeForBinding.IsErrorType()) { attributeConstructor = BindAttributeConstructor(node, attributeTypeForBinding, analyzedArguments.ConstructorArguments, diagnostics, ref resultKind, suppressErrors: attributeType.IsErrorType(), ref argsToParamsOpt, ref expanded, ref useSiteDiagnostics); } diagnostics.Add(node, useSiteDiagnostics); if (attributeConstructor is object) { ReportDiagnosticsIfObsolete(diagnostics, attributeConstructor, node, hasBaseReceiver: false); if (attributeConstructor.Parameters.Any(p => p.RefKind == RefKind.In)) { Error(diagnostics, ErrorCode.ERR_AttributeCtorInParameter, node, attributeConstructor.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)); } } var constructorArguments = analyzedArguments.ConstructorArguments; ImmutableArray<BoundExpression> boundConstructorArguments = constructorArguments.Arguments.ToImmutableAndFree(); ImmutableArray<string> boundConstructorArgumentNamesOpt = constructorArguments.GetNames(); ImmutableArray<BoundExpression> boundNamedArguments = analyzedArguments.NamedArguments; constructorArguments.Free(); return new BoundAttribute(node, attributeConstructor, boundConstructorArguments, boundConstructorArgumentNamesOpt, argsToParamsOpt, expanded, boundNamedArguments, resultKind, attributeType, hasErrors: resultKind != LookupResultKind.Viable); } private CSharpAttributeData GetAttribute(BoundAttribute boundAttribute, DiagnosticBag diagnostics) { var attributeType = (NamedTypeSymbol)boundAttribute.Type; var attributeConstructor = boundAttribute.Constructor; Debug.Assert((object)attributeType != null); NullableWalker.AnalyzeIfNeeded(this, boundAttribute, diagnostics); bool hasErrors = boundAttribute.HasAnyErrors; if (attributeType.IsErrorType() || attributeType.IsAbstract || (object)attributeConstructor == null) { // prevent cascading diagnostics Debug.Assert(hasErrors); return new SourceAttributeData(boundAttribute.Syntax.GetReference(), attributeType, attributeConstructor, hasErrors); } // Validate attribute constructor parameters have valid attribute parameter type ValidateTypeForAttributeParameters(attributeConstructor.Parameters, ((AttributeSyntax)boundAttribute.Syntax).Name, diagnostics, ref hasErrors); // Validate the attribute arguments and generate TypedConstant for argument's BoundExpression. var visitor = new AttributeExpressionVisitor(this); var arguments = boundAttribute.ConstructorArguments; var constructorArgsArray = visitor.VisitArguments(arguments, diagnostics, ref hasErrors); var namedArguments = visitor.VisitNamedArguments(boundAttribute.NamedArguments, diagnostics, ref hasErrors); Debug.Assert(!constructorArgsArray.IsDefault, "Property of VisitArguments"); ImmutableArray<int> constructorArgumentsSourceIndices; ImmutableArray<TypedConstant> constructorArguments; if (hasErrors || attributeConstructor.ParameterCount == 0) { constructorArgumentsSourceIndices = default(ImmutableArray<int>); constructorArguments = constructorArgsArray; } else { constructorArguments = GetRewrittenAttributeConstructorArguments(out constructorArgumentsSourceIndices, attributeConstructor, constructorArgsArray, boundAttribute.ConstructorArgumentNamesOpt, (AttributeSyntax)boundAttribute.Syntax, diagnostics, ref hasErrors); } HashSet<DiagnosticInfo> useSiteDiagnostics = null; bool isConditionallyOmitted = IsAttributeConditionallyOmitted(attributeType, boundAttribute.SyntaxTree, ref useSiteDiagnostics); diagnostics.Add(boundAttribute.Syntax, useSiteDiagnostics); return new SourceAttributeData(boundAttribute.Syntax.GetReference(), attributeType, attributeConstructor, constructorArguments, constructorArgumentsSourceIndices, namedArguments, hasErrors, isConditionallyOmitted); } private void ValidateTypeForAttributeParameters(ImmutableArray<ParameterSymbol> parameters, CSharpSyntaxNode syntax, DiagnosticBag diagnostics, ref bool hasErrors) { foreach (var parameter in parameters) { var paramType = parameter.TypeWithAnnotations; Debug.Assert(paramType.HasType); if (!paramType.Type.IsValidAttributeParameterType(Compilation)) { Error(diagnostics, ErrorCode.ERR_BadAttributeParamType, syntax, parameter.Name, paramType.Type); hasErrors = true; } } } protected bool IsAttributeConditionallyOmitted(NamedTypeSymbol attributeType, SyntaxTree syntaxTree, ref HashSet<DiagnosticInfo> useSiteDiagnostics) { // When early binding attributes, we don't want to determine if the attribute type is conditional and if so, must be emitted or not. // Invoking IsConditional property on attributeType can lead to a cycle, hence we delay this computation until after early binding. if (IsEarlyAttributeBinder) { return false; } Debug.Assert((object)attributeType != null); Debug.Assert(!attributeType.IsErrorType()); if (attributeType.IsConditional) { ImmutableArray<string> conditionalSymbols = attributeType.GetAppliedConditionalSymbols(); Debug.Assert(conditionalSymbols != null); if (syntaxTree.IsAnyPreprocessorSymbolDefined(conditionalSymbols)) { return false; } var baseType = attributeType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteDiagnostics); if ((object)baseType != null && baseType.IsConditional) { return IsAttributeConditionallyOmitted(baseType, syntaxTree, ref useSiteDiagnostics); } return true; } else { return false; } } /// <summary> /// The result of this method captures some AnalyzedArguments, which must be free'ed by the caller. /// </summary> private AnalyzedAttributeArguments BindAttributeArguments( AttributeArgumentListSyntax attributeArgumentList, NamedTypeSymbol attributeType, DiagnosticBag diagnostics) { var boundConstructorArguments = AnalyzedArguments.GetInstance(); var boundNamedArguments = ImmutableArray<BoundExpression>.Empty; if (attributeArgumentList != null) { ArrayBuilder<BoundExpression> boundNamedArgumentsBuilder = null; HashSet<string> boundNamedArgumentsSet = null; // Only report the first "non-trailing named args required C# 7.2" error, // so as to avoid "cascading" errors. bool hadLangVersionError = false; var shouldHaveName = false; foreach (var argument in attributeArgumentList.Arguments) { if (argument.NameEquals == null) { if (shouldHaveName) { diagnostics.Add(ErrorCode.ERR_NamedArgumentExpected, argument.Expression.GetLocation()); } // Constructor argument this.BindArgumentAndName( boundConstructorArguments, diagnostics, ref hadLangVersionError, argument, BindArgumentExpression(diagnostics, argument.Expression, RefKind.None, allowArglist: false), argument.NameColon, refKind: RefKind.None); } else { shouldHaveName = true; // Named argument // TODO: use fully qualified identifier name for boundNamedArgumentsSet string argumentName = argument.NameEquals.Name.Identifier.ValueText; if (boundNamedArgumentsBuilder == null) { boundNamedArgumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(); boundNamedArgumentsSet = new HashSet<string>(); } else if (boundNamedArgumentsSet.Contains(argumentName)) { // Duplicate named argument Error(diagnostics, ErrorCode.ERR_DuplicateNamedAttributeArgument, argument, argumentName); } BoundExpression boundNamedArgument = BindNamedAttributeArgument(argument, attributeType, diagnostics); boundNamedArgumentsBuilder.Add(boundNamedArgument); boundNamedArgumentsSet.Add(argumentName); } } if (boundNamedArgumentsBuilder != null) { boundNamedArguments = boundNamedArgumentsBuilder.ToImmutableAndFree(); } } return new AnalyzedAttributeArguments(boundConstructorArguments, boundNamedArguments); } private BoundExpression BindNamedAttributeArgument(AttributeArgumentSyntax namedArgument, NamedTypeSymbol attributeType, DiagnosticBag diagnostics) { bool wasError; LookupResultKind resultKind; Symbol namedArgumentNameSymbol = BindNamedAttributeArgumentName(namedArgument, attributeType, diagnostics, out wasError, out resultKind); ReportDiagnosticsIfObsolete(diagnostics, namedArgumentNameSymbol, namedArgument, hasBaseReceiver: false); if (namedArgumentNameSymbol.Kind == SymbolKind.Property) { var propertySymbol = (PropertySymbol)namedArgumentNameSymbol; var setMethod = propertySymbol.GetOwnOrInheritedSetMethod(); if (setMethod != null) { ReportDiagnosticsIfObsolete(diagnostics, setMethod, namedArgument, hasBaseReceiver: false); } } Debug.Assert(resultKind == LookupResultKind.Viable || wasError); TypeSymbol namedArgumentType; if (wasError) { namedArgumentType = CreateErrorType(); // don't generate cascaded errors. } else { namedArgumentType = BindNamedAttributeArgumentType(namedArgument, namedArgumentNameSymbol, attributeType, diagnostics); } // BindRValue just binds the expression without doing any validation (if its a valid expression for attribute argument). // Validation is done later by AttributeExpressionVisitor BoundExpression namedArgumentValue = this.BindValue(namedArgument.Expression, diagnostics, BindValueKind.RValue); namedArgumentValue = GenerateConversionForAssignment(namedArgumentType, namedArgumentValue, diagnostics); // TODO: should we create an entry even if there are binding errors? var fieldSymbol = namedArgumentNameSymbol as FieldSymbol; IdentifierNameSyntax nameSyntax = namedArgument.NameEquals.Name; BoundExpression lvalue; if ((object)fieldSymbol != null) { var containingAssembly = fieldSymbol.ContainingAssembly as SourceAssemblySymbol; // We do not want to generate any unassigned field or unreferenced field diagnostics. containingAssembly?.NoteFieldAccess(fieldSymbol, read: true, write: true); lvalue = new BoundFieldAccess(nameSyntax, null, fieldSymbol, ConstantValue.NotAvailable, resultKind, fieldSymbol.Type); } else { var propertySymbol = namedArgumentNameSymbol as PropertySymbol; if ((object)propertySymbol != null) { lvalue = new BoundPropertyAccess(nameSyntax, null, propertySymbol, resultKind, namedArgumentType); } else { lvalue = BadExpression(nameSyntax, resultKind); } } return new BoundAssignmentOperator(namedArgument, lvalue, namedArgumentValue, namedArgumentType); } private Symbol BindNamedAttributeArgumentName(AttributeArgumentSyntax namedArgument, NamedTypeSymbol attributeType, DiagnosticBag diagnostics, out bool wasError, out LookupResultKind resultKind) { var identifierName = namedArgument.NameEquals.Name; var name = identifierName.Identifier.ValueText; LookupResult result = LookupResult.GetInstance(); HashSet<DiagnosticInfo> useSiteDiagnostics = null; this.LookupMembersWithFallback(result, attributeType, name, 0, ref useSiteDiagnostics); diagnostics.Add(identifierName, useSiteDiagnostics); Symbol resultSymbol = this.ResultSymbol(result, name, 0, identifierName, diagnostics, false, out wasError); resultKind = result.Kind; result.Free(); return resultSymbol; } private TypeSymbol BindNamedAttributeArgumentType(AttributeArgumentSyntax namedArgument, Symbol namedArgumentNameSymbol, NamedTypeSymbol attributeType, DiagnosticBag diagnostics) { if (namedArgumentNameSymbol.Kind == SymbolKind.ErrorType) { return (TypeSymbol)namedArgumentNameSymbol; } // SPEC: For each named-argument Arg in named-argument-list N: // SPEC: Let Name be the identifier of the named-argument Arg. // SPEC: Name must identify a non-static read-write public field or property on // SPEC: attribute class T. If T has no such field or property, then a compile-time error occurs. bool invalidNamedArgument = false; TypeSymbol namedArgumentType = null; invalidNamedArgument |= (namedArgumentNameSymbol.DeclaredAccessibility != Accessibility.Public); invalidNamedArgument |= namedArgumentNameSymbol.IsStatic; if (!invalidNamedArgument) { switch (namedArgumentNameSymbol.Kind) { case SymbolKind.Field: var fieldSymbol = (FieldSymbol)namedArgumentNameSymbol; namedArgumentType = fieldSymbol.Type; invalidNamedArgument |= fieldSymbol.IsReadOnly; invalidNamedArgument |= fieldSymbol.IsConst; break; case SymbolKind.Property: var propertySymbol = ((PropertySymbol)namedArgumentNameSymbol).GetLeastOverriddenProperty(this.ContainingType); namedArgumentType = propertySymbol.Type; invalidNamedArgument |= propertySymbol.IsReadOnly; var getMethod = propertySymbol.GetMethod; var setMethod = propertySymbol.SetMethod; invalidNamedArgument = invalidNamedArgument || (object)getMethod == null || (object)setMethod == null; if (!invalidNamedArgument) { invalidNamedArgument = getMethod.DeclaredAccessibility != Accessibility.Public || setMethod.DeclaredAccessibility != Accessibility.Public; } break; default: invalidNamedArgument = true; break; } } if (invalidNamedArgument) { return new ExtendedErrorTypeSymbol(attributeType, namedArgumentNameSymbol, LookupResultKind.NotAVariable, diagnostics.Add(ErrorCode.ERR_BadNamedAttributeArgument, namedArgument.NameEquals.Name.Location, namedArgumentNameSymbol.Name)); } if (!namedArgumentType.IsValidAttributeParameterType(Compilation)) { return new ExtendedErrorTypeSymbol(attributeType, namedArgumentNameSymbol, LookupResultKind.NotAVariable, diagnostics.Add(ErrorCode.ERR_BadNamedAttributeArgumentType, namedArgument.NameEquals.Name.Location, namedArgumentNameSymbol.Name)); } return namedArgumentType; } protected MethodSymbol BindAttributeConstructor( AttributeSyntax node, NamedTypeSymbol attributeType, AnalyzedArguments boundConstructorArguments, DiagnosticBag diagnostics, ref LookupResultKind resultKind, bool suppressErrors, ref ImmutableArray<int> argsToParamsOpt, ref bool expanded, ref HashSet<DiagnosticInfo> useSiteDiagnostics) { MemberResolutionResult<MethodSymbol> memberResolutionResult; ImmutableArray<MethodSymbol> candidateConstructors; if (!TryPerformConstructorOverloadResolution( attributeType, boundConstructorArguments, attributeType.Name, node.Location, suppressErrors, //don't cascade in these cases diagnostics, out memberResolutionResult, out candidateConstructors, allowProtectedConstructorsOfBaseType: true)) { resultKind = resultKind.WorseResultKind( memberResolutionResult.IsValid && !IsConstructorAccessible(memberResolutionResult.Member, ref useSiteDiagnostics) ? LookupResultKind.Inaccessible : LookupResultKind.OverloadResolutionFailure); } argsToParamsOpt = memberResolutionResult.Result.ArgsToParamsOpt; expanded = memberResolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; return memberResolutionResult.Member; } /// <summary> /// Gets the rewritten attribute constructor arguments, i.e. the arguments /// are in the order of parameters, which may differ from the source /// if named constructor arguments are used. /// /// For example: /// void Goo(int x, int y, int z, int w = 3); /// /// Goo(0, z: 2, y: 1); /// /// Arguments returned: 0, 1, 2, 3 /// </summary> /// <returns>Rewritten attribute constructor arguments</returns> /// <remarks> /// CONSIDER: Can we share some code will call rewriting in the local rewriter? /// </remarks> private ImmutableArray<TypedConstant> GetRewrittenAttributeConstructorArguments( out ImmutableArray<int> constructorArgumentsSourceIndices, MethodSymbol attributeConstructor, ImmutableArray<TypedConstant> constructorArgsArray, ImmutableArray<string> constructorArgumentNamesOpt, AttributeSyntax syntax, DiagnosticBag diagnostics, ref bool hasErrors) { Debug.Assert((object)attributeConstructor != null); Debug.Assert(!constructorArgsArray.IsDefault); Debug.Assert(!hasErrors); int argumentsCount = constructorArgsArray.Length; // argsConsumedCount keeps track of the number of constructor arguments // consumed from this.ConstructorArguments array int argsConsumedCount = 0; bool hasNamedCtorArguments = !constructorArgumentNamesOpt.IsDefault; Debug.Assert(!hasNamedCtorArguments || constructorArgumentNamesOpt.Length == argumentsCount); // index of the first named constructor argument int firstNamedArgIndex = -1; ImmutableArray<ParameterSymbol> parameters = attributeConstructor.Parameters; int parameterCount = parameters.Length; var reorderedArguments = new TypedConstant[parameterCount]; int[] sourceIndices = null; for (int i = 0; i < parameterCount; i++) { Debug.Assert(argsConsumedCount <= argumentsCount); ParameterSymbol parameter = parameters[i]; TypedConstant reorderedArgument; if (parameter.IsParams && parameter.Type.IsSZArray() && i + 1 == parameterCount) { reorderedArgument = GetParamArrayArgument(parameter, constructorArgsArray, constructorArgumentNamesOpt, argumentsCount, argsConsumedCount, this.Conversions, out bool foundNamed); if (!foundNamed) { sourceIndices = sourceIndices ?? CreateSourceIndicesArray(i, parameterCount); } } else if (argsConsumedCount < argumentsCount) { if (!hasNamedCtorArguments || constructorArgumentNamesOpt[argsConsumedCount] == null) { // positional constructor argument reorderedArgument = constructorArgsArray[argsConsumedCount]; if (sourceIndices != null) { sourceIndices[i] = argsConsumedCount; } argsConsumedCount++; } else { // named constructor argument // Store the index of the first named constructor argument if (firstNamedArgIndex == -1) { firstNamedArgIndex = argsConsumedCount; } // Current parameter must either have a matching named argument or a default value // For the former case, argsConsumedCount must be incremented to note that we have // consumed a named argument. For the latter case, argsConsumedCount stays same. int matchingArgumentIndex; reorderedArgument = GetMatchingNamedOrOptionalConstructorArgument(out matchingArgumentIndex, constructorArgsArray, constructorArgumentNamesOpt, parameter, firstNamedArgIndex, argumentsCount, ref argsConsumedCount, syntax, diagnostics); sourceIndices = sourceIndices ?? CreateSourceIndicesArray(i, parameterCount); sourceIndices[i] = matchingArgumentIndex; } } else { reorderedArgument = GetDefaultValueArgument(parameter, syntax, diagnostics); sourceIndices = sourceIndices ?? CreateSourceIndicesArray(i, parameterCount); } if (!hasErrors) { if (reorderedArgument.Kind == TypedConstantKind.Error) { hasErrors = true; } else if (reorderedArgument.Kind == TypedConstantKind.Array && parameter.Type.TypeKind == TypeKind.Array && !((TypeSymbol)reorderedArgument.Type).Equals(parameter.Type, TypeCompareKind.AllIgnoreOptions)) { // NOTE: As in dev11, we don't allow array covariance conversions (presumably, we don't have a way to // represent the conversion in metadata). diagnostics.Add(ErrorCode.ERR_BadAttributeArgument, syntax.Location); hasErrors = true; } } reorderedArguments[i] = reorderedArgument; } constructorArgumentsSourceIndices = sourceIndices != null ? sourceIndices.AsImmutableOrNull() : default(ImmutableArray<int>); return reorderedArguments.AsImmutableOrNull(); } private static int[] CreateSourceIndicesArray(int paramIndex, int parameterCount) { Debug.Assert(paramIndex >= 0); Debug.Assert(paramIndex < parameterCount); var sourceIndices = new int[parameterCount]; for (int i = 0; i < paramIndex; i++) { sourceIndices[i] = i; } for (int i = paramIndex; i < parameterCount; i++) { sourceIndices[i] = -1; } return sourceIndices; } private TypedConstant GetMatchingNamedOrOptionalConstructorArgument( out int matchingArgumentIndex, ImmutableArray<TypedConstant> constructorArgsArray, ImmutableArray<string> constructorArgumentNamesOpt, ParameterSymbol parameter, int startIndex, int argumentsCount, ref int argsConsumedCount, AttributeSyntax syntax, DiagnosticBag diagnostics) { int index = GetMatchingNamedConstructorArgumentIndex(parameter.Name, constructorArgumentNamesOpt, startIndex, argumentsCount); if (index < argumentsCount) { // found a matching named argument Debug.Assert(index >= startIndex); // increment argsConsumedCount argsConsumedCount++; matchingArgumentIndex = index; return constructorArgsArray[index]; } else { matchingArgumentIndex = -1; return GetDefaultValueArgument(parameter, syntax, diagnostics); } } private static int GetMatchingNamedConstructorArgumentIndex(string parameterName, ImmutableArray<string> argumentNamesOpt, int startIndex, int argumentsCount) { Debug.Assert(parameterName != null); Debug.Assert(startIndex >= 0 && startIndex < argumentsCount); if (parameterName.IsEmpty() || !argumentNamesOpt.Any()) { return argumentsCount; } // get the matching named (constructor) argument int argIndex = startIndex; while (argIndex < argumentsCount) { var name = argumentNamesOpt[argIndex]; if (string.Equals(name, parameterName, StringComparison.Ordinal)) { break; } argIndex++; } return argIndex; } private TypedConstant GetDefaultValueArgument(ParameterSymbol parameter, AttributeSyntax syntax, DiagnosticBag diagnostics) { var parameterType = parameter.Type; ConstantValue defaultConstantValue = parameter.IsOptional ? parameter.ExplicitDefaultConstantValue : ConstantValue.NotAvailable; TypedConstantKind kind; object defaultValue = null; if (!IsEarlyAttributeBinder && parameter.IsCallerLineNumber) { int line = syntax.SyntaxTree.GetDisplayLineNumber(syntax.Name.Span); kind = TypedConstantKind.Primitive; HashSet<DiagnosticInfo> useSiteDiagnostics = null; var conversion = Conversions.GetCallerLineNumberConversion(parameterType, ref useSiteDiagnostics); diagnostics.Add(syntax, useSiteDiagnostics); if (conversion.IsNumeric || conversion.IsConstantExpression) { // DoUncheckedConversion() keeps "single" floats as doubles internally to maintain higher // precision, so make sure they get cast to floats here. defaultValue = (parameterType.SpecialType == SpecialType.System_Single) ? (float)line : Binder.DoUncheckedConversion(parameterType.SpecialType, ConstantValue.Create(line)); } else { // Boxing or identity conversion: parameterType = Compilation.GetSpecialType(SpecialType.System_Int32); defaultValue = line; } } else if (!IsEarlyAttributeBinder && parameter.IsCallerFilePath) { parameterType = Compilation.GetSpecialType(SpecialType.System_String); kind = TypedConstantKind.Primitive; defaultValue = syntax.SyntaxTree.GetDisplayPath(syntax.Name.Span, Compilation.Options.SourceReferenceResolver); } else if (!IsEarlyAttributeBinder && parameter.IsCallerMemberName && (object)((ContextualAttributeBinder)this).AttributedMember != null) { parameterType = Compilation.GetSpecialType(SpecialType.System_String); kind = TypedConstantKind.Primitive; defaultValue = ((ContextualAttributeBinder)this).AttributedMember.GetMemberCallerName(); } else if (defaultConstantValue == ConstantValue.NotAvailable) { // There is no constant value given for the parameter in source/metadata. // For example, the attribute constructor with signature: M([Optional] int x), has no default value from syntax or attributes. // Default value for these cases is "default(parameterType)". // Optional parameter of System.Object type is treated specially though. // Native compiler treats "M([Optional] object x)" equivalent to "M(object x)" for attributes if parameter type is System.Object. // We generate a better diagnostic for this case by treating "x" in the above case as optional, but generating CS7067 instead. if (parameterType.SpecialType == SpecialType.System_Object) { // CS7067: Attribute constructor parameter '{0}' is optional, but no default parameter value was specified. diagnostics.Add(ErrorCode.ERR_BadAttributeParamDefaultArgument, syntax.Name.Location, parameter.Name); kind = TypedConstantKind.Error; } else { kind = TypedConstant.GetTypedConstantKind(parameterType, this.Compilation); Debug.Assert(kind != TypedConstantKind.Error); defaultConstantValue = parameterType.GetDefaultValue(); if (defaultConstantValue != null) { defaultValue = defaultConstantValue.Value; } } } else if (defaultConstantValue.IsBad) { // Constant value through syntax had errors, don't generate cascading diagnostics. kind = TypedConstantKind.Error; } else if (parameterType.SpecialType == SpecialType.System_Object && !defaultConstantValue.IsNull) { // error CS1763: '{0}' is of type '{1}'. A default parameter value of a reference type other than string can only be initialized with null diagnostics.Add(ErrorCode.ERR_NotNullRefDefaultParameter, syntax.Location, parameter.Name, parameterType); kind = TypedConstantKind.Error; } else { kind = TypedConstant.GetTypedConstantKind(parameterType, this.Compilation); Debug.Assert(kind != TypedConstantKind.Error); defaultValue = defaultConstantValue.Value; } if (kind == TypedConstantKind.Array) { Debug.Assert(defaultValue == null); return new TypedConstant(parameterType, default(ImmutableArray<TypedConstant>)); } else { return new TypedConstant(parameterType, kind, defaultValue); } } private static TypedConstant GetParamArrayArgument(ParameterSymbol parameter, ImmutableArray<TypedConstant> constructorArgsArray, ImmutableArray<string> constructorArgumentNamesOpt, int argumentsCount, int argsConsumedCount, Conversions conversions, out bool foundNamed) { Debug.Assert(argsConsumedCount <= argumentsCount); // If there's a named argument, we'll use that if (!constructorArgumentNamesOpt.IsDefault) { int argIndex = constructorArgumentNamesOpt.IndexOf(parameter.Name); if (argIndex >= 0) { foundNamed = true; if (TryGetNormalParamValue(parameter, constructorArgsArray, argIndex, conversions, out var namedValue)) { return namedValue; } // A named argument for a params parameter is necessarily the only one for that parameter return new TypedConstant(parameter.Type, ImmutableArray.Create(constructorArgsArray[argIndex])); } } int paramArrayArgCount = argumentsCount - argsConsumedCount; foundNamed = false; // If there are zero arguments left if (paramArrayArgCount == 0) { return new TypedConstant(parameter.Type, ImmutableArray<TypedConstant>.Empty); } // If there's exactly one argument left, we'll try to use it in normal form if (paramArrayArgCount == 1 && TryGetNormalParamValue(parameter, constructorArgsArray, argsConsumedCount, conversions, out var lastValue)) { return lastValue; } Debug.Assert(!constructorArgsArray.IsDefault); Debug.Assert(argsConsumedCount <= constructorArgsArray.Length); // Take the trailing arguments as an array for expanded form var values = new TypedConstant[paramArrayArgCount]; for (int i = 0; i < paramArrayArgCount; i++) { values[i] = constructorArgsArray[argsConsumedCount++]; } return new TypedConstant(parameter.Type, values.AsImmutableOrNull()); } private static bool TryGetNormalParamValue(ParameterSymbol parameter, ImmutableArray<TypedConstant> constructorArgsArray, int argIndex, Conversions conversions, out TypedConstant result) { TypedConstant argument = constructorArgsArray[argIndex]; if (argument.Kind != TypedConstantKind.Array) { result = default; return false; } HashSet<DiagnosticInfo> useSiteDiagnostics = null; // ignoring, since already bound argument and parameter Conversion conversion = conversions.ClassifyBuiltInConversion((TypeSymbol)argument.Type, parameter.Type, ref useSiteDiagnostics); // NOTE: Won't always succeed, even though we've performed overload resolution. // For example, passing int[] to params object[] actually treats the int[] as an element of the object[]. if (conversion.IsValid && (conversion.Kind == ConversionKind.ImplicitReference || conversion.Kind == ConversionKind.Identity)) { result = argument; return true; } result = default; return false; } #endregion #region AttributeExpressionVisitor /// <summary> /// Walk a custom attribute argument bound node and return a TypedConstant. Verify that the expression is a constant expression. /// </summary> private struct AttributeExpressionVisitor { private readonly Binder _binder; public AttributeExpressionVisitor(Binder binder) { _binder = binder; } public ImmutableArray<TypedConstant> VisitArguments(ImmutableArray<BoundExpression> arguments, DiagnosticBag diagnostics, ref bool attrHasErrors, bool parentHasErrors = false) { var validatedArguments = ImmutableArray<TypedConstant>.Empty; int numArguments = arguments.Length; if (numArguments > 0) { var builder = ArrayBuilder<TypedConstant>.GetInstance(numArguments); foreach (var argument in arguments) { // current argument has errors if parent had errors OR argument.HasErrors. bool curArgumentHasErrors = parentHasErrors || argument.HasAnyErrors; builder.Add(VisitExpression(argument, diagnostics, ref attrHasErrors, curArgumentHasErrors)); } validatedArguments = builder.ToImmutableAndFree(); } return validatedArguments; } public ImmutableArray<KeyValuePair<string, TypedConstant>> VisitNamedArguments(ImmutableArray<BoundExpression> arguments, DiagnosticBag diagnostics, ref bool attrHasErrors) { ArrayBuilder<KeyValuePair<string, TypedConstant>> builder = null; foreach (var argument in arguments) { var kv = VisitNamedArgument(argument, diagnostics, ref attrHasErrors); if (kv.HasValue) { if (builder == null) { builder = ArrayBuilder<KeyValuePair<string, TypedConstant>>.GetInstance(); } builder.Add(kv.Value); } } if (builder == null) { return ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty; } return builder.ToImmutableAndFree(); } private KeyValuePair<String, TypedConstant>? VisitNamedArgument(BoundExpression argument, DiagnosticBag diagnostics, ref bool attrHasErrors) { KeyValuePair<String, TypedConstant>? visitedArgument = null; switch (argument.Kind) { case BoundKind.AssignmentOperator: var assignment = (BoundAssignmentOperator)argument; switch (assignment.Left.Kind) { case BoundKind.FieldAccess: var fa = (BoundFieldAccess)assignment.Left; visitedArgument = new KeyValuePair<String, TypedConstant>(fa.FieldSymbol.Name, VisitExpression(assignment.Right, diagnostics, ref attrHasErrors, argument.HasAnyErrors)); break; case BoundKind.PropertyAccess: var pa = (BoundPropertyAccess)assignment.Left; visitedArgument = new KeyValuePair<String, TypedConstant>(pa.PropertySymbol.Name, VisitExpression(assignment.Right, diagnostics, ref attrHasErrors, argument.HasAnyErrors)); break; } break; } return visitedArgument; } // SPEC: An expression E is an attribute-argument-expression if all of the following statements are true: // SPEC: 1) The type of E is an attribute parameter type (§17.1.3). // SPEC: 2) At compile-time, the value of Expression can be resolved to one of the following: // SPEC: a) A constant value. // SPEC: b) A System.Type object. // SPEC: c) A one-dimensional array of attribute-argument-expressions private TypedConstant VisitExpression(BoundExpression node, DiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors) { // Validate Statement 1) of the spec comment above. var typedConstantKind = node.Type.GetAttributeParameterTypedConstantKind(_binder.Compilation); return VisitExpression(node, typedConstantKind, diagnostics, ref attrHasErrors, curArgumentHasErrors || typedConstantKind == TypedConstantKind.Error); } private TypedConstant VisitExpression(BoundExpression node, TypedConstantKind typedConstantKind, DiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors) { // Validate Statement 2) of the spec comment above. ConstantValue constantValue = node.ConstantValue; if (constantValue != null) { if (constantValue.IsBad) { typedConstantKind = TypedConstantKind.Error; } return CreateTypedConstant(node, typedConstantKind, diagnostics, ref attrHasErrors, curArgumentHasErrors, simpleValue: node.ConstantValue.Value); } switch (node.Kind) { case BoundKind.Conversion: return VisitConversion((BoundConversion)node, diagnostics, ref attrHasErrors, curArgumentHasErrors); case BoundKind.TypeOfOperator: return VisitTypeOfExpression((BoundTypeOfOperator)node, diagnostics, ref attrHasErrors, curArgumentHasErrors); case BoundKind.ArrayCreation: return VisitArrayCreation((BoundArrayCreation)node, diagnostics, ref attrHasErrors, curArgumentHasErrors); default: return CreateTypedConstant(node, TypedConstantKind.Error, diagnostics, ref attrHasErrors, curArgumentHasErrors); } } private TypedConstant VisitConversion(BoundConversion node, DiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors) { Debug.Assert(node.ConstantValue == null); // We have a bound conversion with a non-constant value. // According to statement 2) of the spec comment, this is not a valid attribute argument. // However, native compiler allows conversions to object type if the conversion operand is a valid attribute argument. // See method AttributeHelper::VerifyAttrArg(EXPR *arg). // We will match native compiler's behavior here. // Devdiv Bug #8763: Additionally we allow conversions from array type to object[], provided a conversion exists and each array element is a valid attribute argument. var type = node.Type; var operand = node.Operand; var operandType = operand.Type; if ((object)type != null && (object)operandType != null) { if (type.SpecialType == SpecialType.System_Object || operandType.IsArray() && type.IsArray() && ((ArrayTypeSymbol)type).ElementType.SpecialType == SpecialType.System_Object) { var typedConstantKind = operandType.GetAttributeParameterTypedConstantKind(_binder.Compilation); return VisitExpression(operand, typedConstantKind, diagnostics, ref attrHasErrors, curArgumentHasErrors); } } return CreateTypedConstant(node, TypedConstantKind.Error, diagnostics, ref attrHasErrors, curArgumentHasErrors); } private static TypedConstant VisitTypeOfExpression(BoundTypeOfOperator node, DiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors) { var typeOfArgument = (TypeSymbol)node.SourceType.Type; // typeof argument is allowed to be: // (a) an unbound type // (b) closed constructed type // typeof argument cannot be an open type if ((object)typeOfArgument != null) // skip this if the argument was an alias symbol { var isValidArgument = true; switch (typeOfArgument.Kind) { case SymbolKind.TypeParameter: // type parameter represents an open type isValidArgument = false; break; default: isValidArgument = typeOfArgument.IsUnboundGenericType() || !typeOfArgument.ContainsTypeParameter(); break; } if (!isValidArgument && !curArgumentHasErrors) { // attribute argument type cannot be an open type Binder.Error(diagnostics, ErrorCode.ERR_AttrArgWithTypeVars, node.Syntax, typeOfArgument.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)); curArgumentHasErrors = true; attrHasErrors = true; } } return CreateTypedConstant(node, TypedConstantKind.Type, diagnostics, ref attrHasErrors, curArgumentHasErrors, simpleValue: node.SourceType.Type); } private TypedConstant VisitArrayCreation(BoundArrayCreation node, DiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors) { ImmutableArray<BoundExpression> bounds = node.Bounds; int boundsCount = bounds.Length; if (boundsCount > 1) { return CreateTypedConstant(node, TypedConstantKind.Error, diagnostics, ref attrHasErrors, curArgumentHasErrors); } var type = (ArrayTypeSymbol)node.Type; var typedConstantKind = type.GetAttributeParameterTypedConstantKind(_binder.Compilation); ImmutableArray<TypedConstant> initializer; if (node.InitializerOpt == null) { if (boundsCount == 0) { initializer = ImmutableArray<TypedConstant>.Empty; } else { if (bounds[0].IsDefaultValue()) { initializer = ImmutableArray<TypedConstant>.Empty; } else { // error: non-constant array creation initializer = ImmutableArray.Create(CreateTypedConstant(node, TypedConstantKind.Error, diagnostics, ref attrHasErrors, curArgumentHasErrors)); } } } else { initializer = VisitArguments(node.InitializerOpt.Initializers, diagnostics, ref attrHasErrors, curArgumentHasErrors); } return CreateTypedConstant(node, typedConstantKind, diagnostics, ref attrHasErrors, curArgumentHasErrors, arrayValue: initializer); } private static TypedConstant CreateTypedConstant(BoundExpression node, TypedConstantKind typedConstantKind, DiagnosticBag diagnostics, ref bool attrHasErrors, bool curArgumentHasErrors, object simpleValue = null, ImmutableArray<TypedConstant> arrayValue = default(ImmutableArray<TypedConstant>)) { var type = node.Type; if (typedConstantKind != TypedConstantKind.Error && type.ContainsTypeParameter()) { // Devdiv Bug #12636: Constant values of open types should not be allowed in attributes // SPEC ERROR: C# language specification does not explicitly disallow constant values of open types. For e.g. // public class C<T> // { // public enum E { V } // } // // [SomeAttr(C<T>.E.V)] // case (a): Constant value of open type. // [SomeAttr(C<int>.E.V)] // case (b): Constant value of constructed type. // Both expressions 'C<T>.E.V' and 'C<int>.E.V' satisfy the requirements for a valid attribute-argument-expression: // (a) Its type is a valid attribute parameter type as per section 17.1.3 of the specification. // (b) It has a compile time constant value. // However, native compiler disallows both the above cases. // We disallow case (a) as it cannot be serialized correctly, but allow case (b) to compile. typedConstantKind = TypedConstantKind.Error; } if (typedConstantKind == TypedConstantKind.Error) { if (!curArgumentHasErrors) { Binder.Error(diagnostics, ErrorCode.ERR_BadAttributeArgument, node.Syntax); attrHasErrors = true; } return new TypedConstant(type, TypedConstantKind.Error, null); } else if (typedConstantKind == TypedConstantKind.Array) { return new TypedConstant(type, arrayValue); } else { return new TypedConstant(type, typedConstantKind, simpleValue); } } } #endregion #region AnalyzedAttributeArguments private struct AnalyzedAttributeArguments { internal readonly AnalyzedArguments ConstructorArguments; internal readonly ImmutableArray<BoundExpression> NamedArguments; internal AnalyzedAttributeArguments(AnalyzedArguments constructorArguments, ImmutableArray<BoundExpression> namedArguments) { this.ConstructorArguments = constructorArguments; this.NamedArguments = namedArguments; } } #endregion } }
48.748788
226
0.591142
[ "Apache-2.0" ]
GKotfis/roslyn
src/Compilers/CSharp/Portable/Binder/Binder_Attributes.cs
60,354
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v4/services/language_constant_service.proto // </auto-generated> // Original file comments: // Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma warning disable 0414, 1591 #region Designer generated code using grpc = global::Grpc.Core; namespace Google.Ads.GoogleAds.V4.Services { /// <summary> /// Service to fetch language constants. /// </summary> public static partial class LanguageConstantService { static readonly string __ServiceName = "google.ads.googleads.v4.services.LanguageConstantService"; static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V4.Services.GetLanguageConstantRequest> __Marshaller_google_ads_googleads_v4_services_GetLanguageConstantRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Ads.GoogleAds.V4.Services.GetLanguageConstantRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V4.Resources.LanguageConstant> __Marshaller_google_ads_googleads_v4_resources_LanguageConstant = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Ads.GoogleAds.V4.Resources.LanguageConstant.Parser.ParseFrom); static readonly grpc::Method<global::Google.Ads.GoogleAds.V4.Services.GetLanguageConstantRequest, global::Google.Ads.GoogleAds.V4.Resources.LanguageConstant> __Method_GetLanguageConstant = new grpc::Method<global::Google.Ads.GoogleAds.V4.Services.GetLanguageConstantRequest, global::Google.Ads.GoogleAds.V4.Resources.LanguageConstant>( grpc::MethodType.Unary, __ServiceName, "GetLanguageConstant", __Marshaller_google_ads_googleads_v4_services_GetLanguageConstantRequest, __Marshaller_google_ads_googleads_v4_resources_LanguageConstant); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V4.Services.LanguageConstantServiceReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of LanguageConstantService</summary> [grpc::BindServiceMethod(typeof(LanguageConstantService), "BindService")] public abstract partial class LanguageConstantServiceBase { /// <summary> /// Returns the requested language constant. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Ads.GoogleAds.V4.Resources.LanguageConstant> GetLanguageConstant(global::Google.Ads.GoogleAds.V4.Services.GetLanguageConstantRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for LanguageConstantService</summary> public partial class LanguageConstantServiceClient : grpc::ClientBase<LanguageConstantServiceClient> { /// <summary>Creates a new client for LanguageConstantService</summary> /// <param name="channel">The channel to use to make remote calls.</param> public LanguageConstantServiceClient(grpc::ChannelBase channel) : base(channel) { } /// <summary>Creates a new client for LanguageConstantService that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public LanguageConstantServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected LanguageConstantServiceClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected LanguageConstantServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Returns the requested language constant. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Ads.GoogleAds.V4.Resources.LanguageConstant GetLanguageConstant(global::Google.Ads.GoogleAds.V4.Services.GetLanguageConstantRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetLanguageConstant(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Returns the requested language constant. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Ads.GoogleAds.V4.Resources.LanguageConstant GetLanguageConstant(global::Google.Ads.GoogleAds.V4.Services.GetLanguageConstantRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetLanguageConstant, null, options, request); } /// <summary> /// Returns the requested language constant. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V4.Resources.LanguageConstant> GetLanguageConstantAsync(global::Google.Ads.GoogleAds.V4.Services.GetLanguageConstantRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetLanguageConstantAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Returns the requested language constant. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V4.Resources.LanguageConstant> GetLanguageConstantAsync(global::Google.Ads.GoogleAds.V4.Services.GetLanguageConstantRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetLanguageConstant, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override LanguageConstantServiceClient NewInstance(ClientBaseConfiguration configuration) { return new LanguageConstantServiceClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(LanguageConstantServiceBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_GetLanguageConstant, serviceImpl.GetLanguageConstant).Build(); } /// <summary>Register service method with a service binder with or without implementation. Useful when customizing the service binding logic. /// Note: this method is part of an experimental API that can change or be removed without any prior notice.</summary> /// <param name="serviceBinder">Service methods will be bound by calling <c>AddMethod</c> on this object.</param> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static void BindService(grpc::ServiceBinderBase serviceBinder, LanguageConstantServiceBase serviceImpl) { serviceBinder.AddMethod(__Method_GetLanguageConstant, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Ads.GoogleAds.V4.Services.GetLanguageConstantRequest, global::Google.Ads.GoogleAds.V4.Resources.LanguageConstant>(serviceImpl.GetLanguageConstant)); } } } #endregion
62.0125
392
0.742794
[ "Apache-2.0" ]
PierrickVoulet/google-ads-dotnet
src/V4/Services/LanguageConstantServiceGrpc.cs
9,922
C#
using System.Collections.Generic; using Newtonsoft.Json; namespace EncompassRest.Schema { public sealed class FieldOptions : ExtensibleObject { [JsonProperty(ItemConverterType = typeof(FieldOptionConverter))] public List<FieldOption> Options { get; set; } public bool? RequireValueFromList { get; set; } } }
28.75
72
0.713043
[ "MIT" ]
gashach/EncompassRest
src/EncompassRest/Schema/FieldOptions.cs
347
C#
using System; using System.Collections.Generic; using Comformation.IntrinsicFunctions; namespace Comformation.KMS.Alias { /// <summary> /// AWS::KMS::Alias /// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kms-alias.html /// </summary> public class AliasResource : ResourceBase { public class AliasProperties { /// <summary> /// AliasName /// Specifies the alias name. This value must begin with alias/ followed by a name, such as /// alias/ExampleAlias. /// Note If you change the value of a Replacement property, such as AliasName, the existing alias is /// deleted and a new alias is created for the specified CMK. This change can disrupt applications that /// use the alias. It can also allow or deny access to a CMK affected by attribute-based access control /// (ABAC). /// The alias must be string of 1-256 characters. It can contain only alphanumeric characters, forward /// slashes (/), underscores (_), and dashes (-). The alias name cannot begin with alias/aws/. The /// alias/aws/ prefix is reserved for AWS managed CMKs. /// Pattern: alias/^[a-zA-Z0-9/_-]+$ /// Minimum: 1 /// Maximum: 256 /// Required: Yes /// Type: String /// Update requires: Replacement /// </summary> public Union<string, IntrinsicFunction> AliasName { get; set; } /// <summary> /// TargetKeyId /// Associates the alias with the specified customer managed CMK. The CMK must be in the same AWS /// account and Region. /// A valid CMK ID is required. If you supply a null or empty string value, this operation returns an /// error. /// For help finding the key ID and ARN, see Finding the key ID and ARN in the AWS Key Management /// Service Developer Guide. /// Specify the key ID or the key ARN of the CMK. /// For example: /// Key ID: 1234abcd-12ab-34cd-56ef-1234567890ab Key ARN: /// arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab /// To get the key ID and key ARN for a CMK, use ListKeys or DescribeKey. /// Required: Yes /// Type: String /// Minimum: 1 /// Maximum: 2048 /// Update requires: No interruption /// </summary> public Union<string, IntrinsicFunction> TargetKeyId { get; set; } } public string Type { get; } = "AWS::KMS::Alias"; public AliasProperties Properties { get; } = new AliasProperties(); } }
43.78125
115
0.584226
[ "MIT" ]
stanb/Comformation
src/Comformation/Generated/KMS/Alias/AliasResource.cs
2,802
C#
using System; namespace NadekoBot.Core.Services.Database.Models { public class UnmuteTimer : DbEntity { public ulong UserId { get; set; } public DateTime UnmuteAt { get; set; } public override int GetHashCode() => UserId.GetHashCode(); public override bool Equals(object obj) { return obj is UnmuteTimer ut ? ut.UserId == UserId : false; } } }
22.095238
49
0.553879
[ "MIT" ]
Duinhil/NadekoBot
NadekoBot.Core/Services/Database/Models/UnmuteTimer.cs
466
C#
using System.IO; using System.Runtime.Serialization; using GameEstate.Red.Formats.Red.CR2W.Reflection; using FastMember; using static GameEstate.Red.Formats.Red.Records.Enums; namespace GameEstate.Red.Formats.Red.Types { [DataContract(Namespace = "")] [REDMeta] public class SSbDescDialogLine : CVariable { [Ordinal(1)] [RED("prodActorId")] public CString ProdActorId { get; set;} [Ordinal(2)] [RED("id")] public CInt32 Id { get; set;} [Ordinal(3)] [RED("str")] public CString Str { get; set;} public SSbDescDialogLine(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new SSbDescDialogLine(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
32.137931
125
0.708155
[ "MIT" ]
bclnet/GameEstate
src/Estates/Red/GameEstate.Red.Format/Red/W3/RTTIConvert/SSbDescDialogLine.cs
932
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 DLaB.Xrm.Entities { /// <summary> /// Non-public custom configuration that is passed to a plug-in's constructor. /// </summary> [System.Runtime.Serialization.DataContractAttribute()] [Microsoft.Xrm.Sdk.Client.EntityLogicalNameAttribute("sdkmessageprocessingstepsecureconfig")] [System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "8.0.1.7297")] public partial class SdkMessageProcessingStepSecureConfig : Microsoft.Xrm.Sdk.Entity, System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged { public struct Fields { public const string CreatedBy = "createdby"; public const string CreatedOn = "createdon"; public const string CreatedOnBehalfBy = "createdonbehalfby"; public const string CustomizationLevel = "customizationlevel"; public const string ModifiedBy = "modifiedby"; public const string ModifiedOn = "modifiedon"; public const string ModifiedOnBehalfBy = "modifiedonbehalfby"; public const string OrganizationId = "organizationid"; public const string SdkMessageProcessingStepSecureConfigId = "sdkmessageprocessingstepsecureconfigid"; public const string Id = "sdkmessageprocessingstepsecureconfigid"; public const string SdkMessageProcessingStepSecureConfigIdUnique = "sdkmessageprocessingstepsecureconfigidunique"; public const string SecureConfig = "secureconfig"; public const string createdby_sdkmessageprocessingstepsecureconfig = "createdby_sdkmessageprocessingstepsecureconfig"; public const string lk_sdkmessageprocessingstepsecureconfig_createdonbehalfby = "lk_sdkmessageprocessingstepsecureconfig_createdonbehalfby"; public const string lk_sdkmessageprocessingstepsecureconfig_modifiedonbehalfby = "lk_sdkmessageprocessingstepsecureconfig_modifiedonbehalfby"; public const string modifiedby_sdkmessageprocessingstepsecureconfig = "modifiedby_sdkmessageprocessingstepsecureconfig"; public const string organization_sdkmessageprocessingstepsecureconfig = "organization_sdkmessageprocessingstepsecureconfig"; } /// <summary> /// Default Constructor. /// </summary> [System.Diagnostics.DebuggerNonUserCode()] public SdkMessageProcessingStepSecureConfig() : base(EntityLogicalName) { } public const string EntityLogicalName = "sdkmessageprocessingstepsecureconfig"; public const int EntityTypeCode = 4616; public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging; [System.Diagnostics.DebuggerNonUserCode()] private void OnPropertyChanged(string propertyName) { if ((this.PropertyChanged != null)) { this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } [System.Diagnostics.DebuggerNonUserCode()] private void OnPropertyChanging(string propertyName) { if ((this.PropertyChanging != null)) { this.PropertyChanging(this, new System.ComponentModel.PropertyChangingEventArgs(propertyName)); } } /// <summary> /// Unique identifier of the user who created the SDK message processing step. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdby")] public Microsoft.Xrm.Sdk.EntityReference CreatedBy { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("createdby"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("CreatedBy"); this.SetAttributeValue("createdby", value); this.OnPropertyChanged("CreatedBy"); } } /// <summary> /// Date and time when the SDK message processing step was created. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdon")] public System.Nullable<System.DateTime> CreatedOn { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.DateTime>>("createdon"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("CreatedOn"); this.SetAttributeValue("createdon", value); this.OnPropertyChanged("CreatedOn"); } } /// <summary> /// Unique identifier of the delegate user who created the sdkmessageprocessingstepsecureconfig. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdonbehalfby")] public Microsoft.Xrm.Sdk.EntityReference CreatedOnBehalfBy { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("createdonbehalfby"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("CreatedOnBehalfBy"); this.SetAttributeValue("createdonbehalfby", value); this.OnPropertyChanged("CreatedOnBehalfBy"); } } /// <summary> /// Customization level of the SDK message processing step secure configuration. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("customizationlevel")] public System.Nullable<int> CustomizationLevel { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<int>>("customizationlevel"); } } /// <summary> /// Unique identifier of the user who last modified the SDK message processing step. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedby")] public Microsoft.Xrm.Sdk.EntityReference ModifiedBy { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("modifiedby"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("ModifiedBy"); this.SetAttributeValue("modifiedby", value); this.OnPropertyChanged("ModifiedBy"); } } /// <summary> /// Date and time when the SDK message processing step was last modified. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedon")] public System.Nullable<System.DateTime> ModifiedOn { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.DateTime>>("modifiedon"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("ModifiedOn"); this.SetAttributeValue("modifiedon", value); this.OnPropertyChanged("ModifiedOn"); } } /// <summary> /// Unique identifier of the delegate user who last modified the sdkmessageprocessingstepsecureconfig. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedonbehalfby")] public Microsoft.Xrm.Sdk.EntityReference ModifiedOnBehalfBy { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("modifiedonbehalfby"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("ModifiedOnBehalfBy"); this.SetAttributeValue("modifiedonbehalfby", value); this.OnPropertyChanged("ModifiedOnBehalfBy"); } } /// <summary> /// Unique identifier of the organization with which the SDK message processing step is associated. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("organizationid")] public Microsoft.Xrm.Sdk.EntityReference OrganizationId { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("organizationid"); } } /// <summary> /// Unique identifier of the SDK message processing step secure configuration. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("sdkmessageprocessingstepsecureconfigid")] public System.Nullable<System.Guid> SdkMessageProcessingStepSecureConfigId { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.Guid>>("sdkmessageprocessingstepsecureconfigid"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("SdkMessageProcessingStepSecureConfigId"); this.SetAttributeValue("sdkmessageprocessingstepsecureconfigid", value); if (value.HasValue) { base.Id = value.Value; } else { base.Id = System.Guid.Empty; } this.OnPropertyChanged("SdkMessageProcessingStepSecureConfigId"); } } [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("sdkmessageprocessingstepsecureconfigid")] public override System.Guid Id { [System.Diagnostics.DebuggerNonUserCode()] get { return base.Id; } [System.Diagnostics.DebuggerNonUserCode()] set { this.SdkMessageProcessingStepSecureConfigId = value; } } /// <summary> /// Unique identifier of the SDK message processing step. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("sdkmessageprocessingstepsecureconfigidunique")] public System.Nullable<System.Guid> SdkMessageProcessingStepSecureConfigIdUnique { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.Guid>>("sdkmessageprocessingstepsecureconfigidunique"); } } /// <summary> /// Secure step-specific configuration for the plug-in type that is passed to the plug-in's constructor at run time. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("secureconfig")] public string SecureConfig { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("secureconfig"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("SecureConfig"); this.SetAttributeValue("secureconfig", value); this.OnPropertyChanged("SecureConfig"); } } /// <summary> /// 1:N sdkmessageprocessingstepsecureconfigid_sdkmessageprocessingstep /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("sdkmessageprocessingstepsecureconfigid_sdkmessageprocessingstep")] public System.Collections.Generic.IEnumerable<Entities.SdkMessageProcessingStep> sdkmessageprocessingstepsecureconfigid_sdkmessageprocessingstep { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<Entities.SdkMessageProcessingStep>("sdkmessageprocessingstepsecureconfigid_sdkmessageprocessingstep", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("sdkmessageprocessingstepsecureconfigid_sdkmessageprocessingstep"); this.SetRelatedEntities<Entities.SdkMessageProcessingStep>("sdkmessageprocessingstepsecureconfigid_sdkmessageprocessingstep", null, value); this.OnPropertyChanged("sdkmessageprocessingstepsecureconfigid_sdkmessageprocessingstep"); } } /// <summary> /// 1:N userentityinstancedata_sdkmessageprocessingstepsecureconfig /// </summary> [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("userentityinstancedata_sdkmessageprocessingstepsecureconfig")] public System.Collections.Generic.IEnumerable<Entities.UserEntityInstanceData> userentityinstancedata_sdkmessageprocessingstepsecureconfig { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntities<Entities.UserEntityInstanceData>("userentityinstancedata_sdkmessageprocessingstepsecureconfig", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("userentityinstancedata_sdkmessageprocessingstepsecureconfig"); this.SetRelatedEntities<Entities.UserEntityInstanceData>("userentityinstancedata_sdkmessageprocessingstepsecureconfig", null, value); this.OnPropertyChanged("userentityinstancedata_sdkmessageprocessingstepsecureconfig"); } } /// <summary> /// N:1 createdby_sdkmessageprocessingstepsecureconfig /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdby")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("createdby_sdkmessageprocessingstepsecureconfig")] public Entities.SystemUser createdby_sdkmessageprocessingstepsecureconfig { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<Entities.SystemUser>("createdby_sdkmessageprocessingstepsecureconfig", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("createdby_sdkmessageprocessingstepsecureconfig"); this.SetRelatedEntity<Entities.SystemUser>("createdby_sdkmessageprocessingstepsecureconfig", null, value); this.OnPropertyChanged("createdby_sdkmessageprocessingstepsecureconfig"); } } /// <summary> /// N:1 lk_sdkmessageprocessingstepsecureconfig_createdonbehalfby /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdonbehalfby")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("lk_sdkmessageprocessingstepsecureconfig_createdonbehalfby")] public Entities.SystemUser lk_sdkmessageprocessingstepsecureconfig_createdonbehalfby { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<Entities.SystemUser>("lk_sdkmessageprocessingstepsecureconfig_createdonbehalfby", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("lk_sdkmessageprocessingstepsecureconfig_createdonbehalfby"); this.SetRelatedEntity<Entities.SystemUser>("lk_sdkmessageprocessingstepsecureconfig_createdonbehalfby", null, value); this.OnPropertyChanged("lk_sdkmessageprocessingstepsecureconfig_createdonbehalfby"); } } /// <summary> /// N:1 lk_sdkmessageprocessingstepsecureconfig_modifiedonbehalfby /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedonbehalfby")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("lk_sdkmessageprocessingstepsecureconfig_modifiedonbehalfby")] public Entities.SystemUser lk_sdkmessageprocessingstepsecureconfig_modifiedonbehalfby { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<Entities.SystemUser>("lk_sdkmessageprocessingstepsecureconfig_modifiedonbehalfby", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("lk_sdkmessageprocessingstepsecureconfig_modifiedonbehalfby"); this.SetRelatedEntity<Entities.SystemUser>("lk_sdkmessageprocessingstepsecureconfig_modifiedonbehalfby", null, value); this.OnPropertyChanged("lk_sdkmessageprocessingstepsecureconfig_modifiedonbehalfby"); } } /// <summary> /// N:1 modifiedby_sdkmessageprocessingstepsecureconfig /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedby")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("modifiedby_sdkmessageprocessingstepsecureconfig")] public Entities.SystemUser modifiedby_sdkmessageprocessingstepsecureconfig { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<Entities.SystemUser>("modifiedby_sdkmessageprocessingstepsecureconfig", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("modifiedby_sdkmessageprocessingstepsecureconfig"); this.SetRelatedEntity<Entities.SystemUser>("modifiedby_sdkmessageprocessingstepsecureconfig", null, value); this.OnPropertyChanged("modifiedby_sdkmessageprocessingstepsecureconfig"); } } /// <summary> /// N:1 organization_sdkmessageprocessingstepsecureconfig /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("organizationid")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("organization_sdkmessageprocessingstepsecureconfig")] public Entities.Organization organization_sdkmessageprocessingstepsecureconfig { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<Entities.Organization>("organization_sdkmessageprocessingstepsecureconfig", null); } } /// <summary> /// Constructor for populating via LINQ queries given a LINQ anonymous type /// <param name="anonymousType">LINQ anonymous type.</param> /// </summary> [System.Diagnostics.DebuggerNonUserCode()] public SdkMessageProcessingStepSecureConfig(object anonymousType) : this() { foreach (var p in anonymousType.GetType().GetProperties()) { var value = p.GetValue(anonymousType, null); var name = p.Name.ToLower(); if (name.EndsWith("enum") && value.GetType().BaseType == typeof(System.Enum)) { value = new Microsoft.Xrm.Sdk.OptionSetValue((int) value); name = name.Remove(name.Length - "enum".Length); } switch (name) { case "id": base.Id = (System.Guid)value; Attributes["sdkmessageprocessingstepsecureconfigid"] = base.Id; break; case "sdkmessageprocessingstepsecureconfigid": var id = (System.Nullable<System.Guid>) value; if(id == null){ continue; } base.Id = id.Value; Attributes[name] = base.Id; break; case "formattedvalues": // Add Support for FormattedValues FormattedValues.AddRange((Microsoft.Xrm.Sdk.FormattedValueCollection)value); break; default: Attributes[name] = value; break; } } } } }
37.363825
178
0.736535
[ "MIT" ]
Bhawk90/DLaB.Xrm.XrmToolBoxTools
DLaB.Xrm.Entities/Entities/SdkMessageProcessingStepSecureConfig.cs
17,972
C#