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.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace JOGAPRAOLX
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 25.62963 | 70 | 0.644509 | [
"MIT"
] | LissaDias/HackaTudo_OLX_2DLV_2021 | JOGAPRAOLX/Program.cs | 692 | C# |
using System.Collections.Generic;
using Samples.Specifications.Data.Contracts.Dto;
using Samples.Specifications.Data.Fake.Containers.Contracts;
namespace Samples.Specifications.Data.Fake.Containers
{
public interface IWarehouseContainer : IDataContainer
{
IEnumerable<WarehouseItemDto> WarehouseItems { get; }
}
public sealed class WarehouseContainer : IWarehouseContainer
{
private readonly List<WarehouseItemDto> _warehouseItems = new List<WarehouseItemDto>();
public IEnumerable<WarehouseItemDto> WarehouseItems => _warehouseItems;
public void UpdateWarehouseItems(IEnumerable<WarehouseItemDto> warehouseItems)
{
_warehouseItems.Clear();
_warehouseItems.AddRange(warehouseItems);
}
}
}
| 33 | 95 | 0.733586 | [
"MIT"
] | dmitrybublik/Samples.Specifications.Core | Samples.Specifications.Data.Fake.Containers/WarehouseContainer.cs | 794 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.239
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MSConvertGUI.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 40.407407 | 152 | 0.567369 | [
"Apache-2.0"
] | shze/pwizard-deb | pwiz_tools/MSConvertGUI/Properties/Settings.Designer.cs | 1,093 | C# |
using System.Data.Common;
using System.Data.Entity.Core.EntityClient;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using System.Data.SqlServerCe;
using MySql.Data.MySqlClient;
using Npgsql;
using Oracle.ManagedDataAccess.Client;
namespace WebMoney.Services.DataAccess.EF
{
internal class ProviderFactoryResolver : IDbProviderFactoryResolver
{
public DbProviderFactory ResolveProviderFactory(DbConnection connection)
{
if (connection is SqlConnection)
return SqlClientFactory.Instance;
if (connection is SqlCeConnection)
return SqlCeProviderFactory.Instance;
if (connection is MySqlConnection)
return MySqlClientFactory.Instance;
if (connection is NpgsqlConnection)
return NpgsqlFactory.Instance;
if (connection is OracleConnection)
return OracleClientFactory.Instance;
if (connection is EntityConnection)
return EntityProviderFactory.Instance;
return null;
}
}
}
| 29.263158 | 80 | 0.678957 | [
"MIT"
] | MarketKernel/webmoney-business-tools | Src/WebMoney.Services/DataAccess.EF/ProviderFactoryResolver.cs | 1,114 | C# |
//
// Copyright 2010-2017 Deveel
//
// 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.Threading.Tasks;
using Deveel.Data.Services;
namespace Deveel.Data.Diagnostics {
public static class ScopeExtensions {
public static void AddEventRegistry<TRegistry>(this IScope scope)
where TRegistry : class, IEventRegistry {
scope.Register<IEventRegistry, TRegistry>();
}
public static void AddRoutingEventRegistry<TEvent>(this IScope scope)
where TEvent : class, IEvent {
scope.AddEventRegistry<RoutingEventRegistry<TEvent>>();
scope.Register<IEventRegistry<TEvent>, RoutingEventRegistry<TEvent>>();
}
public static void AddEventRouter<TRouter>(this IScope scope)
where TRouter : class, IEventRouter {
scope.Register<IEventRouter, TRouter>();
}
public static void AddEventRouter<TEvent>(this IScope scope, Func<TEvent, Task> handler)
where TEvent : class, IEvent {
scope.RegisterInstance<IEventRouter>(new DelegatedEventRouter<TEvent>(handler));
}
public static void AddEventRouter<TEvent>(this IScope scope, Action<TEvent> handler)
where TEvent : class, IEvent
=> scope.AddEventRouter<TEvent>(e => {
handler(e);
return Task.CompletedTask;
});
#region DelegatedEventRouter
class DelegatedEventRouter<TEvent> : IEventRouter where TEvent : class, IEvent {
private readonly Func<TEvent, Task> handler;
public DelegatedEventRouter(Func<TEvent, Task> handler) {
this.handler = handler;
}
public bool CanRoute(IEvent @event) {
return @event is TEvent;
}
public Task RouteEventAsync(IEvent e) {
return handler((TEvent) e);
}
}
#endregion
}
} | 30.273973 | 90 | 0.723529 | [
"Apache-2.0"
] | deveel/deveeldb.core | src/DeveelDb.Core/Data/Diagnostics/ScopeExtensions.cs | 2,212 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** 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.Aws.Ses
{
/// <summary>
/// Provides an SES receipt rule resource
/// </summary>
public partial class ReceiptRule : Pulumi.CustomResource
{
/// <summary>
/// A list of Add Header Action blocks. Documented below.
/// </summary>
[Output("addHeaderActions")]
public Output<ImmutableArray<Outputs.ReceiptRuleAddHeaderAction>> AddHeaderActions { get; private set; } = null!;
/// <summary>
/// The name of the rule to place this rule after
/// </summary>
[Output("after")]
public Output<string?> After { get; private set; } = null!;
/// <summary>
/// A list of Bounce Action blocks. Documented below.
/// </summary>
[Output("bounceActions")]
public Output<ImmutableArray<Outputs.ReceiptRuleBounceAction>> BounceActions { get; private set; } = null!;
/// <summary>
/// If true, the rule will be enabled
/// </summary>
[Output("enabled")]
public Output<bool> Enabled { get; private set; } = null!;
/// <summary>
/// A list of Lambda Action blocks. Documented below.
/// </summary>
[Output("lambdaActions")]
public Output<ImmutableArray<Outputs.ReceiptRuleLambdaAction>> LambdaActions { get; private set; } = null!;
/// <summary>
/// The name of the rule
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// A list of email addresses
/// </summary>
[Output("recipients")]
public Output<ImmutableArray<string>> Recipients { get; private set; } = null!;
/// <summary>
/// The name of the rule set
/// </summary>
[Output("ruleSetName")]
public Output<string> RuleSetName { get; private set; } = null!;
/// <summary>
/// A list of S3 Action blocks. Documented below.
/// </summary>
[Output("s3Actions")]
public Output<ImmutableArray<Outputs.ReceiptRuleS3Action>> S3Actions { get; private set; } = null!;
/// <summary>
/// If true, incoming emails will be scanned for spam and viruses
/// </summary>
[Output("scanEnabled")]
public Output<bool> ScanEnabled { get; private set; } = null!;
/// <summary>
/// A list of SNS Action blocks. Documented below.
/// </summary>
[Output("snsActions")]
public Output<ImmutableArray<Outputs.ReceiptRuleSnsAction>> SnsActions { get; private set; } = null!;
/// <summary>
/// A list of Stop Action blocks. Documented below.
/// </summary>
[Output("stopActions")]
public Output<ImmutableArray<Outputs.ReceiptRuleStopAction>> StopActions { get; private set; } = null!;
/// <summary>
/// Require or Optional
/// </summary>
[Output("tlsPolicy")]
public Output<string> TlsPolicy { get; private set; } = null!;
/// <summary>
/// A list of WorkMail Action blocks. Documented below.
/// </summary>
[Output("workmailActions")]
public Output<ImmutableArray<Outputs.ReceiptRuleWorkmailAction>> WorkmailActions { get; private set; } = null!;
/// <summary>
/// Create a ReceiptRule resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public ReceiptRule(string name, ReceiptRuleArgs args, CustomResourceOptions? options = null)
: base("aws:ses/receiptRule:ReceiptRule", name, args ?? new ReceiptRuleArgs(), MakeResourceOptions(options, ""))
{
}
private ReceiptRule(string name, Input<string> id, ReceiptRuleState? state = null, CustomResourceOptions? options = null)
: base("aws:ses/receiptRule:ReceiptRule", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing ReceiptRule resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static ReceiptRule Get(string name, Input<string> id, ReceiptRuleState? state = null, CustomResourceOptions? options = null)
{
return new ReceiptRule(name, id, state, options);
}
}
public sealed class ReceiptRuleArgs : Pulumi.ResourceArgs
{
[Input("addHeaderActions")]
private InputList<Inputs.ReceiptRuleAddHeaderActionArgs>? _addHeaderActions;
/// <summary>
/// A list of Add Header Action blocks. Documented below.
/// </summary>
public InputList<Inputs.ReceiptRuleAddHeaderActionArgs> AddHeaderActions
{
get => _addHeaderActions ?? (_addHeaderActions = new InputList<Inputs.ReceiptRuleAddHeaderActionArgs>());
set => _addHeaderActions = value;
}
/// <summary>
/// The name of the rule to place this rule after
/// </summary>
[Input("after")]
public Input<string>? After { get; set; }
[Input("bounceActions")]
private InputList<Inputs.ReceiptRuleBounceActionArgs>? _bounceActions;
/// <summary>
/// A list of Bounce Action blocks. Documented below.
/// </summary>
public InputList<Inputs.ReceiptRuleBounceActionArgs> BounceActions
{
get => _bounceActions ?? (_bounceActions = new InputList<Inputs.ReceiptRuleBounceActionArgs>());
set => _bounceActions = value;
}
/// <summary>
/// If true, the rule will be enabled
/// </summary>
[Input("enabled")]
public Input<bool>? Enabled { get; set; }
[Input("lambdaActions")]
private InputList<Inputs.ReceiptRuleLambdaActionArgs>? _lambdaActions;
/// <summary>
/// A list of Lambda Action blocks. Documented below.
/// </summary>
public InputList<Inputs.ReceiptRuleLambdaActionArgs> LambdaActions
{
get => _lambdaActions ?? (_lambdaActions = new InputList<Inputs.ReceiptRuleLambdaActionArgs>());
set => _lambdaActions = value;
}
/// <summary>
/// The name of the rule
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
[Input("recipients")]
private InputList<string>? _recipients;
/// <summary>
/// A list of email addresses
/// </summary>
public InputList<string> Recipients
{
get => _recipients ?? (_recipients = new InputList<string>());
set => _recipients = value;
}
/// <summary>
/// The name of the rule set
/// </summary>
[Input("ruleSetName", required: true)]
public Input<string> RuleSetName { get; set; } = null!;
[Input("s3Actions")]
private InputList<Inputs.ReceiptRuleS3ActionArgs>? _s3Actions;
/// <summary>
/// A list of S3 Action blocks. Documented below.
/// </summary>
public InputList<Inputs.ReceiptRuleS3ActionArgs> S3Actions
{
get => _s3Actions ?? (_s3Actions = new InputList<Inputs.ReceiptRuleS3ActionArgs>());
set => _s3Actions = value;
}
/// <summary>
/// If true, incoming emails will be scanned for spam and viruses
/// </summary>
[Input("scanEnabled")]
public Input<bool>? ScanEnabled { get; set; }
[Input("snsActions")]
private InputList<Inputs.ReceiptRuleSnsActionArgs>? _snsActions;
/// <summary>
/// A list of SNS Action blocks. Documented below.
/// </summary>
public InputList<Inputs.ReceiptRuleSnsActionArgs> SnsActions
{
get => _snsActions ?? (_snsActions = new InputList<Inputs.ReceiptRuleSnsActionArgs>());
set => _snsActions = value;
}
[Input("stopActions")]
private InputList<Inputs.ReceiptRuleStopActionArgs>? _stopActions;
/// <summary>
/// A list of Stop Action blocks. Documented below.
/// </summary>
public InputList<Inputs.ReceiptRuleStopActionArgs> StopActions
{
get => _stopActions ?? (_stopActions = new InputList<Inputs.ReceiptRuleStopActionArgs>());
set => _stopActions = value;
}
/// <summary>
/// Require or Optional
/// </summary>
[Input("tlsPolicy")]
public Input<string>? TlsPolicy { get; set; }
[Input("workmailActions")]
private InputList<Inputs.ReceiptRuleWorkmailActionArgs>? _workmailActions;
/// <summary>
/// A list of WorkMail Action blocks. Documented below.
/// </summary>
public InputList<Inputs.ReceiptRuleWorkmailActionArgs> WorkmailActions
{
get => _workmailActions ?? (_workmailActions = new InputList<Inputs.ReceiptRuleWorkmailActionArgs>());
set => _workmailActions = value;
}
public ReceiptRuleArgs()
{
}
}
public sealed class ReceiptRuleState : Pulumi.ResourceArgs
{
[Input("addHeaderActions")]
private InputList<Inputs.ReceiptRuleAddHeaderActionGetArgs>? _addHeaderActions;
/// <summary>
/// A list of Add Header Action blocks. Documented below.
/// </summary>
public InputList<Inputs.ReceiptRuleAddHeaderActionGetArgs> AddHeaderActions
{
get => _addHeaderActions ?? (_addHeaderActions = new InputList<Inputs.ReceiptRuleAddHeaderActionGetArgs>());
set => _addHeaderActions = value;
}
/// <summary>
/// The name of the rule to place this rule after
/// </summary>
[Input("after")]
public Input<string>? After { get; set; }
[Input("bounceActions")]
private InputList<Inputs.ReceiptRuleBounceActionGetArgs>? _bounceActions;
/// <summary>
/// A list of Bounce Action blocks. Documented below.
/// </summary>
public InputList<Inputs.ReceiptRuleBounceActionGetArgs> BounceActions
{
get => _bounceActions ?? (_bounceActions = new InputList<Inputs.ReceiptRuleBounceActionGetArgs>());
set => _bounceActions = value;
}
/// <summary>
/// If true, the rule will be enabled
/// </summary>
[Input("enabled")]
public Input<bool>? Enabled { get; set; }
[Input("lambdaActions")]
private InputList<Inputs.ReceiptRuleLambdaActionGetArgs>? _lambdaActions;
/// <summary>
/// A list of Lambda Action blocks. Documented below.
/// </summary>
public InputList<Inputs.ReceiptRuleLambdaActionGetArgs> LambdaActions
{
get => _lambdaActions ?? (_lambdaActions = new InputList<Inputs.ReceiptRuleLambdaActionGetArgs>());
set => _lambdaActions = value;
}
/// <summary>
/// The name of the rule
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
[Input("recipients")]
private InputList<string>? _recipients;
/// <summary>
/// A list of email addresses
/// </summary>
public InputList<string> Recipients
{
get => _recipients ?? (_recipients = new InputList<string>());
set => _recipients = value;
}
/// <summary>
/// The name of the rule set
/// </summary>
[Input("ruleSetName")]
public Input<string>? RuleSetName { get; set; }
[Input("s3Actions")]
private InputList<Inputs.ReceiptRuleS3ActionGetArgs>? _s3Actions;
/// <summary>
/// A list of S3 Action blocks. Documented below.
/// </summary>
public InputList<Inputs.ReceiptRuleS3ActionGetArgs> S3Actions
{
get => _s3Actions ?? (_s3Actions = new InputList<Inputs.ReceiptRuleS3ActionGetArgs>());
set => _s3Actions = value;
}
/// <summary>
/// If true, incoming emails will be scanned for spam and viruses
/// </summary>
[Input("scanEnabled")]
public Input<bool>? ScanEnabled { get; set; }
[Input("snsActions")]
private InputList<Inputs.ReceiptRuleSnsActionGetArgs>? _snsActions;
/// <summary>
/// A list of SNS Action blocks. Documented below.
/// </summary>
public InputList<Inputs.ReceiptRuleSnsActionGetArgs> SnsActions
{
get => _snsActions ?? (_snsActions = new InputList<Inputs.ReceiptRuleSnsActionGetArgs>());
set => _snsActions = value;
}
[Input("stopActions")]
private InputList<Inputs.ReceiptRuleStopActionGetArgs>? _stopActions;
/// <summary>
/// A list of Stop Action blocks. Documented below.
/// </summary>
public InputList<Inputs.ReceiptRuleStopActionGetArgs> StopActions
{
get => _stopActions ?? (_stopActions = new InputList<Inputs.ReceiptRuleStopActionGetArgs>());
set => _stopActions = value;
}
/// <summary>
/// Require or Optional
/// </summary>
[Input("tlsPolicy")]
public Input<string>? TlsPolicy { get; set; }
[Input("workmailActions")]
private InputList<Inputs.ReceiptRuleWorkmailActionGetArgs>? _workmailActions;
/// <summary>
/// A list of WorkMail Action blocks. Documented below.
/// </summary>
public InputList<Inputs.ReceiptRuleWorkmailActionGetArgs> WorkmailActions
{
get => _workmailActions ?? (_workmailActions = new InputList<Inputs.ReceiptRuleWorkmailActionGetArgs>());
set => _workmailActions = value;
}
public ReceiptRuleState()
{
}
}
}
| 36.456265 | 139 | 0.593671 | [
"ECL-2.0",
"Apache-2.0"
] | johnktims/pulumi-aws | sdk/dotnet/Ses/ReceiptRule.cs | 15,421 | 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.Collections.Generic;
using Microsoft.AspNetCore.SignalR.Protocol;
namespace Microsoft.AspNetCore.SignalR.StackExchangeRedis.Internal
{
internal readonly struct RedisInvocation
{
/// <summary>
/// Gets a list of connections that should be excluded from this invocation.
/// May be null to indicate that no connections are to be excluded.
/// </summary>
public IReadOnlyList<string>? ExcludedConnectionIds { get; }
/// <summary>
/// Gets the message serialization cache containing serialized payloads for the message.
/// </summary>
public SerializedHubMessage Message { get; }
public RedisInvocation(SerializedHubMessage message, IReadOnlyList<string>? excludedConnectionIds)
{
Message = message;
ExcludedConnectionIds = excludedConnectionIds;
}
}
}
| 36.724138 | 111 | 0.690141 | [
"Apache-2.0"
] | 1175169074/aspnetcore | src/SignalR/server/StackExchangeRedis/src/Internal/RedisInvocation.cs | 1,065 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Requests\IEntityRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The interface IMuteParticipantOperationRequestBuilder.
/// </summary>
public partial interface IMuteParticipantOperationRequestBuilder : ICommsOperationRequestBuilder
{
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
new IMuteParticipantOperationRequest Request();
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
new IMuteParticipantOperationRequest Request(IEnumerable<Option> options);
}
}
| 36.305556 | 153 | 0.589901 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/IMuteParticipantOperationRequestBuilder.cs | 1,307 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace TypedWorkflow.Common
{
internal class TwContainer : ITwContainer
{
private readonly ObjectPool<TwContext> _factory;
private readonly Func<Task<object[]>, object, object[]> _complete;
public TwContainer(ObjectPool<TwContext> factory)
{
_factory = factory;
_complete = Complete;
}
public ValueTask Run(CancellationToken cancellation = default(CancellationToken))
{
var res = Run(new object[] { cancellation });
return res.IsCompletedSuccessfully ? new ValueTask() : new ValueTask(res.AsTask());
}
protected ValueTask<object[]> Run(object[] initial_imports)
{
var context = _factory.Allocate();
var res = context.RunAsync(initial_imports);
if (res.IsCompleted)
{
_complete(null, context);
return res;
}
return new ValueTask<object[]>(res.AsTask().ContinueWith(_complete, context));
}
private object[] Complete(Task<object[]> complete, object state)
{
var context = (TwContext)state;
_factory.Free(context);
if (complete is null)
return null;
if (complete.IsFaulted)
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(complete.Exception).Throw();
if (complete.IsCanceled)
throw new TaskCanceledException(complete);
return complete.Result;
}
}
internal class TwContainer<T> : TwContainer, ITwContainer<T>
{
private readonly Func<T, CancellationToken, object[]> _getInitialImports;
protected Func<T, CancellationToken, object[]> GetInitialImports => _getInitialImports;
public TwContainer(ObjectPool<TwContext> factory, FieldInfo[] initial_tuple_fields) : base(factory)
{
if (typeof(T) == typeof(Option.Void))
_getInitialImports = (e, c) => new object[] { c };
else if (initial_tuple_fields == null)
_getInitialImports = GetInitialImportsImpl;
else
_getInitialImports = (v, c) => GetInitialImportsImpl(v, initial_tuple_fields, c);
}
public ValueTask Run(T initial_imports, CancellationToken cancellation = default(CancellationToken))
{
var res = Run(GetInitialImports(initial_imports, cancellation));
return res.IsCompletedSuccessfully ? new ValueTask() : new ValueTask(res.AsTask());
}
private object[] GetInitialImportsImpl(T initial_imports, CancellationToken cancellation)
=> new object[] { initial_imports, cancellation };
private object[] GetInitialImportsImpl(T initial_imports, FieldInfo[] initial_tuple_fields, CancellationToken cancellation)
{
var initialImports = new object[initial_tuple_fields.Length + 1];
for (int i = 0; i < initial_tuple_fields.Length; ++i)
initialImports[i] = initial_tuple_fields[i].GetValue(initial_imports);
initialImports[initial_tuple_fields.Length] = cancellation;
return initialImports;
}
}
internal class TwContainer<T, Tr> : TwContainer<T>, ITwContainer<T, Tr>
{
private readonly ConstructorInfo _resultTupleConstructor;
private readonly Func<Task<object[]>, Tr> _success;
public TwContainer(ObjectPool<TwContext> factory, FieldInfo[] initial_tuple_fields, Type[] result_tuple_types)
: base(factory, initial_tuple_fields)
{
_success = Success;
if (result_tuple_types != null)
{
var genericType = Type.GetType("System.ValueTuple`" + result_tuple_types.Length);
_resultTupleConstructor = genericType.MakeGenericType(result_tuple_types).GetConstructor(result_tuple_types);
}
}
public ValueTask<Tr> Run(T initial_imports, CancellationToken cancellation = default(CancellationToken))
=> RunImpl(initial_imports, cancellation);
protected ValueTask<Tr> RunImpl(T initial_imports, CancellationToken cancellation)
{
var res = Run(GetInitialImports(initial_imports, cancellation));
if (res.IsCompletedSuccessfully)
return new ValueTask<Tr>(GetResult(res.Result));
var t = res.AsTask().ContinueWith(_success, TaskContinuationOptions.OnlyOnRanToCompletion);
return new ValueTask<Tr>(t);
}
private Tr Success(Task<object[]> successed_task)
=> GetResult(successed_task.Result);
private Tr GetResult(object[] result)
{
if (_resultTupleConstructor != null)
return (Tr)_resultTupleConstructor.Invoke(result);
if (result.Length > 1)
throw new InvalidCastException("Many result values");
return (Tr)result[0];
}
}
internal class TwContainerWithCache<T, Tr> : TwContainer<T,Tr>, ITwContainer<T, Tr>
{
private readonly ProactiveCache.ProCache<T, Tr> _cache;
public TwContainerWithCache(ObjectPool<TwContext> factory, FieldInfo[] initial_tuple_fields, Type[] result_tuple_types, ProCacheFactory.Options<T, Tr> cache_options)
: base(factory, initial_tuple_fields, result_tuple_types)
{
_cache = cache_options.CreateCache(RunImpl);
}
public new ValueTask<Tr> Run(T initial_imports, CancellationToken cancellation)
=> _cache.Get(initial_imports, cancellation);
}
internal class TwContainerWithCacheBatch<T, Tr> : TwContainer<IEnumerable<T>, IEnumerable<KeyValuePair<T, Tr>>>, ITwContainer<IEnumerable<T>, IEnumerable<KeyValuePair<T,Tr>>>
{
private readonly ProactiveCache.ProCacheBatch<T, Tr> _cache;
public TwContainerWithCacheBatch(ObjectPool<TwContext> factory, FieldInfo[] initial_tuple_fields, Type[] result_tuple_types, ProCacheFactory.Options<T, Tr> cache_options)
: base(factory, initial_tuple_fields, result_tuple_types)
{
_cache = cache_options.CreateCache(RunImpl);
}
public new ValueTask<IEnumerable<KeyValuePair<T, Tr>>> Run(IEnumerable<T> initial_imports, CancellationToken cancellation = default)
=> _cache.Get(initial_imports, cancellation);
}
} | 39.136095 | 178 | 0.647415 | [
"MIT"
] | bopohaa/TypedWorkflow | TypedWorkflow/Common/TwContainer.cs | 6,616 | C# |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using NUnit.Framework;
namespace Newtonsoft.Json.Tests
{
[TestFixture]
public abstract class TestFixtureBase
{
[SetUp]
protected void TestSetup()
{
//CultureInfo turkey = CultureInfo.CreateSpecificCulture("tr");
//Thread.CurrentThread.CurrentCulture = turkey;
//Thread.CurrentThread.CurrentUICulture = turkey;
}
//public string GetOffset(DateTime value)
//{
// TimeSpan utcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(value.ToLocalTime());
// return utcOffset.Hours.ToString("+00;-00") + utcOffset.Minutes.ToString("00;00");
//}
protected void WriteEscapedJson(string json)
{
Console.WriteLine(EscapeJson(json));
}
protected string EscapeJson(string json)
{
return @"@""" + json.Replace(@"""", @"""""") + @"""";
}
}
}
| 33.538462 | 90 | 0.699083 | [
"MIT"
] | thirumg/Avro.NET | lang/dotnet/src/contrib/Json35r6/Src/Newtonsoft.Json.Tests/TestFixtureBase.cs | 2,182 | C# |
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using Rebus.Activation;
using Rebus.Config;
using Rebus.Persistence.InMem;
using Rebus.Tests.Contracts;
using Rebus.Tests.Contracts.Extensions;
using Rebus.Transport.InMem;
#pragma warning disable 1998
namespace Rebus.Tests.Timeouts
{
[TestFixture]
public class TestInternalTimeoutManager : FixtureBase
{
readonly string _queueName = TestConfig.GetName("timeouts");
[Test]
public async Task WorksOutOfTheBoxWithInternalTimeoutManager_WhenInMemTimeoutsIsConfigure()
{
using (var activator = new BuiltinHandlerActivator())
{
var gotTheMessage = new ManualResetEvent(false);
activator.Handle<string>(async str => gotTheMessage.Set());
Configure.With(activator)
.Transport(t => t.UseInMemoryTransport(new InMemNetwork(), _queueName))
.Timeouts(t => t.StoreInMemory())
.Start();
var stopwatch = Stopwatch.StartNew();
await activator.Bus.DeferLocal(TimeSpan.FromSeconds(5), "hej med dig min ven!");
gotTheMessage.WaitOrDie(TimeSpan.FromSeconds(6.5),
"Message was not received within 6,5 seconds (which it should have been since it was only deferred 5 seconds)");
Assert.That(stopwatch.Elapsed, Is.GreaterThan(TimeSpan.FromSeconds(5)),
"It must take more than 5 second to get the message back");
}
}
}
} | 33.895833 | 132 | 0.64413 | [
"MIT"
] | AndoxADX/Rebus | Rebus.Tests/Timeouts/TestInternalTimeoutManager.cs | 1,629 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Utilities;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Input
{
/// <summary>
/// Animated cursor is a cursor driven using an animator to inject state information
/// and animate accordingly
/// </summary>
public class AnimatedCursor : BaseCursor
{
[SerializeField]
[Header("Animated Cursor State Data")]
[Tooltip("Cursor state data to use for its various states.")]
private AnimatedCursorStateData[] cursorStateData = null;
[SerializeField]
[Header("Animated Cursor Context Data")]
[Tooltip("Cursor context data to use for its various contextual states.")]
private AnimatedCursorContextData[] cursorContextData = null;
[SerializeField]
[Tooltip("Animator parameter to set when input is enabled.")]
private AnimatorParameter inputEnabledParameter = default(AnimatorParameter);
[SerializeField]
[Tooltip("Animator parameter to set when input is disabled.")]
private AnimatorParameter inputDisabledParameter = default(AnimatorParameter);
[SerializeField]
[Tooltip("Animator for the cursor")]
private Animator cursorAnimator = null;
/// <summary>
/// Change animation state when enabling input.
/// </summary>
public override void OnInputEnabled()
{
base.OnInputEnabled();
SetAnimatorParameter(inputEnabledParameter);
}
/// <summary>
/// Change animation state when disabling input.
/// </summary>
public override void OnInputDisabled()
{
base.OnInputDisabled();
SetAnimatorParameter(inputDisabledParameter);
}
/// <summary>
/// Override to set the cursor animation trigger.
/// </summary>
public override void OnFocusChanged(FocusEventData eventData)
{
base.OnFocusChanged(eventData);
if (((Pointer is UnityEngine.Object) ? ((Pointer as UnityEngine.Object) != null) : (Pointer != null)) && Pointer.CursorModifier != null)
{
if ((Pointer.CursorModifier.CursorParameters != null) && (Pointer.CursorModifier.CursorParameters.Length > 0))
{
OnCursorStateChange(CursorStateEnum.Contextual);
for (var i = 0; i < Pointer.CursorModifier.CursorParameters.Length; i++)
{
SetAnimatorParameter(Pointer.CursorModifier.CursorParameters[i]);
}
}
}
else
{
OnCursorStateChange(CursorStateEnum.None);
}
}
/// <summary>
/// Override OnCursorState change to set the correct animation state for the cursor.
/// </summary>
/// <param name="state"></param>
public override void OnCursorStateChange(CursorStateEnum state)
{
base.OnCursorStateChange(state);
if (state == CursorStateEnum.Contextual) { return; }
for (int i = 0; i < cursorStateData.Length; i++)
{
if (cursorStateData[i].CursorState == state)
{
SetAnimatorParameter(cursorStateData[i].Parameter);
}
}
}
/// <summary>
/// Override OnCursorContext change to set the correct animation state for the cursor.
/// </summary>
/// <param name="context"></param>
public override void OnCursorContextChange(CursorContextEnum context)
{
base.OnCursorContextChange(context);
if (context == CursorContextEnum.Contextual) { return; }
for (int i = 0; i < cursorContextData.Length; i++)
{
if (cursorContextData[i].CursorState == context)
{
SetAnimatorParameter(cursorContextData[i].Parameter);
}
}
}
/// <summary>
/// Based on the type of animator state info pass it through to the animator
/// </summary>
/// <param name="animationParameter"></param>
private void SetAnimatorParameter(AnimatorParameter animationParameter)
{
// Return if we do not have an animator
if (cursorAnimator == null || !cursorAnimator.isInitialized)
{
return;
}
switch (animationParameter.ParameterType)
{
case AnimatorControllerParameterType.Bool:
cursorAnimator.SetBool(animationParameter.NameHash, animationParameter.DefaultBool);
break;
case AnimatorControllerParameterType.Float:
cursorAnimator.SetFloat(animationParameter.NameHash, animationParameter.DefaultFloat);
break;
case AnimatorControllerParameterType.Int:
cursorAnimator.SetInteger(animationParameter.NameHash, animationParameter.DefaultInt);
break;
case AnimatorControllerParameterType.Trigger:
cursorAnimator.SetTrigger(animationParameter.NameHash);
break;
}
}
}
} | 37.482993 | 148 | 0.586751 | [
"MIT"
] | ActiveNick/HoloBot | Assets/MixedRealityToolkit.SDK/Features/UX/Scripts/Cursors/AnimatedCursor.cs | 5,512 | 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.GoogleNative.Dialogflow.V2Beta1.Outputs
{
/// <summary>
/// The collection of suggestions.
/// </summary>
[OutputType]
public sealed class GoogleCloudDialogflowV2beta1IntentMessageSuggestionsResponse
{
/// <summary>
/// The list of suggested replies.
/// </summary>
public readonly ImmutableArray<Outputs.GoogleCloudDialogflowV2beta1IntentMessageSuggestionResponse> Suggestions;
[OutputConstructor]
private GoogleCloudDialogflowV2beta1IntentMessageSuggestionsResponse(ImmutableArray<Outputs.GoogleCloudDialogflowV2beta1IntentMessageSuggestionResponse> suggestions)
{
Suggestions = suggestions;
}
}
}
| 32.967742 | 173 | 0.727984 | [
"Apache-2.0"
] | AaronFriel/pulumi-google-native | sdk/dotnet/Dialogflow/V2Beta1/Outputs/GoogleCloudDialogflowV2beta1IntentMessageSuggestionsResponse.cs | 1,022 | C# |
/*
MIT License
Copyright (c) 2019 Jeff Campbell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace JCMG.AssetValidator.Editor
{
/// <summary>
/// Helper methods for dealing with Unity project assets and folder.
/// </summary>
public static class ProjectTools
{
/// <summary>
/// Has the user set their preference for debugging to true or false?
/// </summary>
internal static bool IsDebugging
{
get { return EditorPrefs.GetBool(ASSET_VALIDATOR_IS_DEBUGGING, false); }
set { EditorPrefs.SetBool(ASSET_VALIDATOR_IS_DEBUGGING, value); }
}
private const string ASSET_VALIDATOR_IS_DEBUGGING = "ASSET_VALIDATOR_IS_DEBUGGING";
private const string SceneAssetExtension = ".unity";
private const string ProjectSearchFilterForScenes = "t:scene";
/// <summary>
/// Returns a read-only list of scene paths based on the passed <see cref="SceneValidationMode"/>
/// <paramref name="validationMode"/>.
/// </summary>
/// <param name="validationMode"></param>
/// <returns></returns>
public static IReadOnlyList<string> GetScenePaths(SceneValidationMode validationMode)
{
switch (validationMode)
{
case SceneValidationMode.None:
return new string[0];
case SceneValidationMode.ActiveScene:
return new[] {SceneManager.GetActiveScene().path};
case SceneValidationMode.AllScenes:
return GetAllScenePathsInProject();
case SceneValidationMode.AllBuildScenes:
return GetAllScenePathsInBuildSettings();
case SceneValidationMode.AllBuildAndAssetBundleScenes:
var finalScenes = GetAllScenePathsInAssetBundles();
finalScenes.AddRange(GetAllScenePathsInBuildSettings());
return finalScenes;
default:
throw new ArgumentOutOfRangeException(Enum.GetName(typeof(SceneValidationMode), validationMode));
}
}
/// <summary>
/// Returns a list of scene paths in relative path format from the Unity Assets folder for all
/// <see cref="SceneAsset"/>(s) in the project.
/// </summary>
/// <returns></returns>
public static List<string> GetAllScenePathsInProject()
{
var scenePaths = new List<string>();
var assetPaths = AssetDatabase.FindAssets(ProjectSearchFilterForScenes);
for (var i = 0; i < assetPaths.Length; i++)
{
scenePaths.Add(AssetDatabase.GUIDToAssetPath(assetPaths[i]));
}
return scenePaths;
}
/// <summary>
/// Returns a list of scene paths in relative path format from the Unity Assets folder for all
/// <see cref="SceneAsset"/>(s) included in <see cref="AssetBundle"/>(s).
/// </summary>
/// <returns></returns>
public static List<string> GetAllScenePathsInAssetBundles()
{
var sceneNames = new List<string>();
var allAssetBundleNames = AssetDatabase.GetAllAssetBundleNames();
for (var i = 0; i < allAssetBundleNames.Length; i++)
{
var assetNames = AssetDatabase.GetAssetPathsFromAssetBundle(allAssetBundleNames[i]);
for (var j = 0; j < assetNames.Length; j++)
{
if (assetNames[j].Contains(SceneAssetExtension))
{
sceneNames.Add(assetNames[j]);
}
}
}
return sceneNames;
}
/// <summary>
/// Returns a list of scene paths in relative path format from the Unity Assets folder for all
/// <see cref="SceneAsset"/>(s) included in the build settings.
/// </summary>
/// <returns></returns>
public static List<string> GetAllScenePathsInBuildSettings()
{
return EditorBuildSettings.scenes.Select(x => x.path).ToList();
}
/// <summary>
/// Returns a human-readable string description for the passed <see cref="Type"/> <paramref name="type"/>
/// based on its decorated <see cref="ValidatorDescriptionAttribute"/>.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static string GetValidatorDescription(Type type)
{
var vType = typeof(ValidatorDescriptionAttribute);
var attrs = type.GetCustomAttributes(vType, false) as ValidatorDescriptionAttribute[];
return attrs != null && attrs.Length > 0
? attrs[0].Description
: string.Empty;
}
/// <summary>
/// Attempts to ping an <see cref="UnityEngine.Object"/> instance in the current scene or project window
/// based on the passed <see cref="ValidationLog"/> <paramref name="log"/>.
/// </summary>
/// <param name="log"></param>
internal static void TryPingObject(ValidationLog log)
{
UnityEngine.Object obj = null;
if (log.source == LogSource.Scene)
{
obj = GameObject.Find(log.objectPath);
}
else if (log.source == LogSource.Project)
{
obj = AssetDatabase.LoadAssetAtPath(log.objectPath, typeof(UnityEngine.Object));
}
if (obj != null)
{
EditorGUIUtility.PingObject(obj);
}
else
{
Debug.LogWarningFormat(EditorConstants.CouldNotPingObjectWarning, log.objectPath);
}
}
/// <summary>
/// Returns true if the passed asset path includes a magic Unity Resources folder as a part of it,
/// otherwise returns false.
/// </summary>
/// <param name="assetPath"></param>
/// <returns></returns>
public static bool IsInResourcesFolder(string assetPath)
{
var splitPath = assetPath.Split(EditorConstants.ForwardSlashChar);
for (var i = 0; i < splitPath.Length; i++)
{
if (splitPath[i].ToLowerInvariant() == EditorConstants.ResourcesFolderName)
{
return true;
}
}
return false;
}
}
}
| 32.517588 | 107 | 0.713955 | [
"MIT"
] | jeffcampbellmakesgames/unity-asset-validator | Unity/Assets/JCMG/AssetValidator/Editor/Tools/ProjectTools.cs | 6,473 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Muebles_JJ.Infrastructure.Data;
using Muebles_JJ.Infrastructure;
using Microsoft.AspNetCore.Http;
using Muebles_JJ.Web.Models;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace Muebles_JJ.Web.Controllers
{
public class InsumoController : Controller
{
private readonly Muebles_JJDbContext _context;
public InsumoController(Muebles_JJDbContext context)
{
_context = context;
}
//GET: Insumo
public async Task<IActionResult> Index()
{
if (HttpContext.Session.GetString("Logueo") != "Si")
{
HttpContext.Session.SetString("MensajeError", "Su sesión expiró.");
return RedirectToAction("Login", "Home");
}
InsumoModel model = new InsumoModel();
model.listInsumo = await _context.Insumo.ToListAsync();
model.listUnidadmedida = await _context.Unidadmedida.ToListAsync();
return View(model);
}
//GET: Insumo/Create
public async Task<IActionResult> Create()
{
if (HttpContext.Session.GetString("Logueo") != "Si")
{
HttpContext.Session.SetString("MensajeError", "Su sesión expiró.");
return RedirectToAction("Login", "Home");
}
ViewData["UnidadMedida"] = new SelectList(_context.Unidadmedida, "IdMedida", "NombreLargo");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AgregarInsumo(InsumoModel model)
{
if (HttpContext.Session.GetString("Logueo") != "Si")
{
HttpContext.Session.SetString("MensajeError", "Su sesión expiró.");
return RedirectToAction("Login", "Home");
}
_context.Add(model.oInsumo);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
//GET: Insumo/Edit
public async Task<IActionResult> Edit(int IdInsumo)
{
if (HttpContext.Session.GetString("Logueo") != "Si")
{
HttpContext.Session.SetString("MensajeError", "Su sesión expiró.");
return RedirectToAction("Login", "Home");
}
InsumoModel model = new InsumoModel();
model.oInsumo = await _context.Insumo.FindAsync(IdInsumo);
ViewData["UnidadMedida"] = new SelectList(_context.Unidadmedida, "IdMedida", "NombreLargo");
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditarInsumo(InsumoModel model)
{
if (HttpContext.Session.GetString("Logueo") != "Si")
{
HttpContext.Session.SetString("MensajeError", "Su sesión expiró.");
return RedirectToAction("Login", "Home");
}
_context.Update(model.oInsumo);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
//GET: Insumo/EliminarInsumo
public async Task<IActionResult> EliminarInsumo(int IdInsumo)
{
if (HttpContext.Session.GetString("Logueo") != "Si")
{
HttpContext.Session.SetString("MensajeError", "Su sesión expiró.");
return RedirectToAction("Login", "Home");
}
Insumo model = await _context.Insumo.FindAsync(IdInsumo);
_context.Insumo.Remove(model);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
}
| 36.11215 | 104 | 0.593168 | [
"MIT"
] | Juancholaya/Muebles_JJ | Muebles_JJ/src/Muebles_JJ.Web/Controllers/InsumoController.cs | 3,878 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Linq;
using Microsoft.Practices.Unity.TestSupport;
using Microsoft.Practices.Unity.Utility;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Practices.Unity.InterceptionExtension.Tests
{
[TestClass]
public class ParameterCollectionFixture
{
[TestMethod]
public void CanAccessNonFilteredParameters()
{
var collection =
new ParameterCollection(
new object[] { 10, 20, 30, 40, 50 },
StaticReflection.GetMethodInfo(() => TestMethod(null, null, null, null, null)).GetParameters(),
pi => true);
Assert.AreEqual(5, collection.Count);
CollectionAssertExtensions.AreEqual(
new[] { 10, 20, 30, 40, 50 },
collection);
CollectionAssertExtensions.AreEqual(
new[] { 50, 20, 40, 30, 10 },
new[] { 4, 1, 3, 2, 0 }.Select(i => collection[i]).ToArray());
CollectionAssertExtensions.AreEqual(
new[] { 50, 20, 40, 30, 10 },
new[] { "param5", "param2", "param4", "param3", "param1" }.Select(i => collection[i]).ToArray());
CollectionAssertExtensions.AreEqual(
new[] { "param1", "param2", "param3", "param4", "param5" },
Enumerable.Range(0, 5).Select(i => collection.ParameterName(i)).ToArray());
CollectionAssertExtensions.AreEqual(
new[] { "param1", "param2", "param3", "param4", "param5" },
Enumerable.Range(0, 5).Select(i => collection.GetParameterInfo(i).Name).ToArray());
}
[TestMethod]
public void CanAccessFilteredParameters()
{
var param = 1;
var collection =
new ParameterCollection(
new object[] { 10, 20, 30, 40, 50 },
StaticReflection.GetMethodInfo(() => TestMethod(null, null, null, null, null)).GetParameters(),
pi => param++ % 2 == 1);
Assert.AreEqual(3, collection.Count);
CollectionAssertExtensions.AreEqual(
new[] { 10, 30, 50 },
collection);
CollectionAssertExtensions.AreEqual(
new[] { 50, 30, 10 },
new[] { 2, 1, 0 }.Select(i => collection[i]).ToArray());
CollectionAssertExtensions.AreEqual(
new[] { 50, 30, 10 },
new[] { "param5", "param3", "param1" }.Select(i => collection[i]).ToArray());
CollectionAssertExtensions.AreEqual(
new[] { "param1", "param3", "param5" },
Enumerable.Range(0, 3).Select(i => collection.ParameterName(i)).ToArray());
CollectionAssertExtensions.AreEqual(
new[] { "param1", "param3", "param5" },
Enumerable.Range(0, 3).Select(i => collection.GetParameterInfo(i).Name).ToArray());
}
[TestMethod]
public void FilteredCollectionReturnsRightParameterByName()
{
object dummy;
object dummy2;
var inputsCollection =
new ParameterCollection(new object[] { "one", "two", "three", "four" },
StaticReflection.GetMethodInfo(() => MethodWithOuts(out dummy, null, out dummy2, null)).GetParameters(),
pi => !pi.IsOut);
Assert.AreEqual(2, inputsCollection.Count);
CollectionAssertExtensions.AreEqual(new object[] { "two", "four" }, inputsCollection);
Assert.AreEqual("two", inputsCollection["param2"]);
Assert.AreEqual("four", inputsCollection["param4"]);
}
[TestMethod]
public void WhenParameterValueIsNull()
{
var collection =
new ParameterCollection(
new object[] { null },
StaticReflection.GetMethodInfo(() => TestMethod(null, null, null, null, null)).GetParameters(),
p => true);
var result = collection.Contains(null);
Assert.IsTrue(result);
}
[TestMethod]
public void ContainsParameterWorksAsExpected()
{
var collection =
new ParameterCollection(
new object[] { null },
StaticReflection.GetMethodInfo(() => TestMethod(null, null, null, null, null)).GetParameters(),
p => true);
Assert.IsTrue(new[] { "param1", "param2", "param3", "param4", "param5" }.All(collection.ContainsParameter));
Assert.IsTrue(new[] { "someOtherParam", "notThisOneEither" }.All(p => !collection.ContainsParameter(p)));
}
public static void TestMethod(object param1, object param2, object param3, object param4, object param5)
{
}
public static void MethodWithOuts(out object param1, object param2, out object param3, object param4)
{
param1 = null;
param3 = null;
}
}
}
| 42.614754 | 124 | 0.55126 | [
"Apache-2.0",
"MIT"
] | drcarver/unity | source/Unity.Interception/Tests/Tests.Unity.Interception/ParameterCollectionFixture.cs | 5,201 | C# |
using Terraria.ID;
using Terraria.ModLoader;
namespace tsorcRevamp.Items.Weapons.Melee {
public class CobaltZweihander : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Cobalt Zweihander");
Tooltip.SetDefault("");
}
public override void SetDefaults()
{
item.autoReuse = true;
//item.prefixType=483;
item.rare = ItemRarityID.LightRed;
item.damage = 38;
item.width = 56;
item.height = 56;
item.knockBack = (float)4.85;
item.maxStack = 1;
item.melee = true;
item.scale = (float)1;
item.useAnimation = 32;
item.UseSound = SoundID.Item1;
item.useStyle = ItemUseStyleID.SwingThrow;
item.useTime = 21;
item.value = 96600;
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.CobaltBar, 14);
recipe.AddIngredient(mod.GetItem("DarkSoul"), 1300);
recipe.AddTile(TileID.DemonAltar);
recipe.SetResult(this, 1);
recipe.AddRecipe();
}
}
}
| 24.666667 | 64 | 0.547695 | [
"MIT"
] | RecursiveCollapse/tsorcRevamp | Items/Weapons/Melee/CobaltZweihander.cs | 1,258 | C# |
using System;
using System.Collections.Generic;
namespace ate.Templating
{
public class RenderContext
{
public object CurrentObject { get; set; }
public string CurrentDirectory { get; set; }
public string CurrentFile { get; set; }
public string CurrentText { get; set; }
}
public class CompileContext
{
// public Class Class { get; set; }
public Template Template { get; set; }
//public Type Type { get; set; }
public Stack<ISegment> Stack = new Stack<ISegment>();
//public ISegment TopSegment { get; set; }
}
} | 23.703704 | 62 | 0.584375 | [
"MIT"
] | DavidPeterWatson/ate | src/Templating/Context.cs | 640 | C# |
using System;
using GovApi.Core.Converters;
using Newtonsoft.Json;
namespace GovApi.FoodDataCentral.Search
{
public class Food
{
/// <summary>
/// Unique ID of the food. Pass this to the Detail endpoint
/// </summary>
[JsonProperty("fdcId")]
public long FdcId { get; set; }
/// <summary>
/// The description of the food.
/// </summary>
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("dataType")]
public string DataType { get; set; }
/// <summary>
/// GTIN or UPC code identifying the food.
/// </summary>
[JsonProperty("gtinUpc", NullValueHandling = NullValueHandling.Ignore)]
public string Upc { get; set; }
/// <summary>
/// Date the item was published to FDC.
/// </summary>
[JsonProperty("publishedDate")]
public DateTimeOffset PublishedDate { get; set; }
/// <summary>
/// Brand owner for the food.
/// </summary>
[JsonProperty("brandOwner", NullValueHandling = NullValueHandling.Ignore)]
public string BrandOwner { get; set; }
/// <summary>
/// The list of ingredients (as it appears on the product label).
/// </summary>
[JsonProperty("ingredients", NullValueHandling = NullValueHandling.Ignore)]
public string Ingredients { get; set; }
/// <summary>
/// Fields that were found matching the criteria.
/// </summary>
[JsonProperty("allHighlightFields")]
public string AllHighlightFields { get; set; }
/// <summary>
/// Relative score indicating how well the food matches the search criteria.
/// </summary>
[JsonProperty("score")]
public double Score { get; set; }
/// <summary>
/// The scientific name of the food.
/// </summary>
[JsonProperty("scientificName", NullValueHandling = NullValueHandling.Ignore)]
public string ScientificName { get; set; }
/// <summary>
/// Unique number assigned for foundation foods.
/// </summary>
[JsonProperty("ndbNumber", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(ParseStringConverter))]
public long? NdbNumber { get; set; }
/// <summary>
/// Any additional descriptions of the food.
/// </summary>
[JsonProperty("additionalDescriptions", NullValueHandling = NullValueHandling.Ignore)]
public string AdditionalDescriptions { get; set; }
/// <summary>
/// A unique ID identifying the food within FNDDS.
/// </summary>
[JsonProperty("foodCode", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(ParseStringConverter))]
public long? FoodCode { get; set; }
}
} | 34.034884 | 94 | 0.591391 | [
"MIT"
] | Eonasdan/GovApi.Net | GovApi/GovApi.FoodDataCenteral/Search/Food.cs | 2,929 | 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.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
namespace System.Net.Http.Headers
{
public class TransferCodingHeaderValue : ICloneable
{
// Use ObjectCollection<T> since we may have multiple parameters with the same name.
private ObjectCollection<NameValueHeaderValue>? _parameters;
private string _value = null!; // empty constructor only used internally and value set with non null
public string Value
{
get { return _value; }
}
public ICollection<NameValueHeaderValue> Parameters => _parameters ??= new ObjectCollection<NameValueHeaderValue>();
internal TransferCodingHeaderValue()
{
}
protected TransferCodingHeaderValue(TransferCodingHeaderValue source)
{
Debug.Assert(source != null);
_value = source._value;
_parameters = source._parameters.Clone();
}
public TransferCodingHeaderValue(string value)
{
HeaderUtilities.CheckValidToken(value, nameof(value));
_value = value;
}
public static TransferCodingHeaderValue Parse(string? input)
{
int index = 0;
return (TransferCodingHeaderValue)TransferCodingHeaderParser.SingleValueParser.ParseValue(
input, null, ref index);
}
public static bool TryParse([NotNullWhen(true)] string? input, [NotNullWhen(true)] out TransferCodingHeaderValue? parsedValue)
{
int index = 0;
parsedValue = null;
if (TransferCodingHeaderParser.SingleValueParser.TryParseValue(input, null, ref index, out object? output))
{
parsedValue = (TransferCodingHeaderValue)output!;
return true;
}
return false;
}
internal static int GetTransferCodingLength(string input, int startIndex,
Func<TransferCodingHeaderValue> transferCodingCreator, out TransferCodingHeaderValue? parsedValue)
{
Debug.Assert(transferCodingCreator != null);
Debug.Assert(startIndex >= 0);
parsedValue = null;
if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
{
return 0;
}
// Caller must remove leading whitespace. If not, we'll return 0.
int valueLength = HttpRuleParser.GetTokenLength(input, startIndex);
if (valueLength == 0)
{
return 0;
}
string value = input.Substring(startIndex, valueLength);
int current = startIndex + valueLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
TransferCodingHeaderValue transferCodingHeader;
// If we're not done and we have a parameter delimiter, then we have a list of parameters.
if ((current < input.Length) && (input[current] == ';'))
{
transferCodingHeader = transferCodingCreator();
transferCodingHeader._value = value;
current++; // skip delimiter.
int parameterLength = NameValueHeaderValue.GetNameValueListLength(input, current, ';',
(ObjectCollection<NameValueHeaderValue>)transferCodingHeader.Parameters);
if (parameterLength == 0)
{
return 0;
}
parsedValue = transferCodingHeader;
return current + parameterLength - startIndex;
}
// We have a transfer coding without parameters.
transferCodingHeader = transferCodingCreator();
transferCodingHeader._value = value;
parsedValue = transferCodingHeader;
return current - startIndex;
}
public override string ToString()
{
StringBuilder sb = StringBuilderCache.Acquire();
sb.Append(_value);
NameValueHeaderValue.ToString(_parameters, ';', true, sb);
return StringBuilderCache.GetStringAndRelease(sb);
}
public override bool Equals([NotNullWhen(true)] object? obj)
{
TransferCodingHeaderValue? other = obj as TransferCodingHeaderValue;
if (other == null)
{
return false;
}
return string.Equals(_value, other._value, StringComparison.OrdinalIgnoreCase) &&
HeaderUtilities.AreEqualCollections(_parameters, other._parameters);
}
public override int GetHashCode()
{
// The value string is case-insensitive.
return StringComparer.OrdinalIgnoreCase.GetHashCode(_value) ^ NameValueHeaderValue.GetHashCode(_parameters);
}
// Implement ICloneable explicitly to allow derived types to "override" the implementation.
object ICloneable.Clone()
{
return new TransferCodingHeaderValue(this);
}
}
}
| 35.530201 | 134 | 0.610314 | [
"MIT"
] | 3DCloud/runtime | src/libraries/System.Net.Http/src/System/Net/Http/Headers/TransferCodingHeaderValue.cs | 5,294 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CRM.Areas.AppPage.Controllers
{
public class DatosAfiliadosController : Controller
{
// GET: AppPage/DatosAfiliados
public ActionResult Index(string RutBuscar)
{
return View();
}
}
} | 21 | 54 | 0.666667 | [
"MIT"
] | cmunoz780/MDN | CRM/Areas/AppPage/Controllers/DatosAfiliadosController.cs | 359 | C# |
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace IO.TelstraTPN.Model {
/// <summary>
///
/// </summary>
[DataContract]
public class Link66 {
/// <summary>
/// Identifier of a link
/// </summary>
/// <value>Identifier of a link</value>
[DataMember(Name="linkid", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "linkid")]
public string Linkid { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="vport", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "vport")]
public List<string> Vport { get; set; }
/// <summary>
/// Get the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString() {
var sb = new StringBuilder();
sb.Append("class Link66 {\n");
sb.Append(" Linkid: ").Append(Linkid).Append("\n");
sb.Append(" Vport: ").Append(Vport).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Get the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
}
| 26.090909 | 68 | 0.620906 | [
"Apache-2.0"
] | telstra/Programmable-Network-SDK-dotnet | src/main/CsharpDotNet2/IO/TelstraTPN/Model/Link66.cs | 1,435 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SEIDR.Doc
{
public partial class DocSorter<G>
{
class sortInfoCache
{
public List<CacheEntry> list { get; private set; }
List<int> pages = new List<int>();
public IEnumerable<int> GetPagesUsed()
{
foreach (var pageNum in pages)
yield return pageNum;
yield break;
//return (from e in list
// select e.Info.Page).Distinct().OrderBy(p => p);
}
public sortInfoCache(DocReader<sortInfo> index, long startLine, long endLine)
{
list = new List<CacheEntry>();
for(; startLine < endLine; startLine++)
{
var info = index[startLine];
if (info.Page < 0) //dupe
continue;
if (!pages.Contains(info.Page))
pages.Add(info.Page);
list.Add(new CacheEntry(startLine, info));
}
pages.Sort();
}
public sortInfoCache(IList<sortInfo> index, long startLine)
{
list = new List<CacheEntry>();
for(int i = 0; i < index.Count; i++, startLine++)
{
var info = index[i];
if (info.Page < 0)
continue; //dupe
if (!pages.Contains(info.Page))
pages.Add(info.Page);
list.Add(new CacheEntry(startLine, info));
}
pages.Sort();
}
public List<CacheEntry> PullInfo(int page)
{
List<CacheEntry> ret = new List<CacheEntry>();
int idx = 0;
while(idx < list.Count)
{
var e = list[idx];
if (e.Info.Page == page)
{
ret.Add(e);
list.RemoveAt(idx);
continue;
}
idx++;
}
return ret;
}
public class CacheEntry
{
public readonly long FileLine;
public readonly sortInfo Info;
public CacheEntry(long LineNumber, sortInfo value)
{
FileLine = LineNumber;
Info = value;
}
}
}
class pageCache
{
public void Clear() => entryList.Clear();
LinkedList<cacheEntry> entryList;
readonly int CacheSize = 2;
public pageCache(int cacheSize)
{
CacheSize = cacheSize;
entryList = new LinkedList<cacheEntry>();
}
public bool CheckCache(int page)
{
return entryList.Exists(chk => chk.PageNumber == page);
}
public cacheEntry Get(int page, DocReader<G> source)
{
cacheEntry e;
if (entryList.Count == 0)
{
e = new cacheEntry(page, source.GetPage(page));
entryList.AddFirst(e);
return e;
}
else if (entryList.First.Value.PageNumber == page)
return entryList.First.Value;
e = entryList.FirstOrDefault(chk => chk.PageNumber == page);
if (e != null)
{
if (e.PageNumber != entryList.First.Value.PageNumber)
{
entryList.Remove(e);
entryList.AddFirst(e);
}
}
else
{
//Not found.
e = new cacheEntry(page, source.GetPage(page));
if (entryList.Count >= CacheSize)
entryList.RemoveLast();
entryList.AddFirst(e);
}
return e;
}
public class cacheEntry
{
List<G> Page;
public readonly int PageNumber;
public cacheEntry(int pageNumber, List<G> page)
{
Page = page;
PageNumber = pageNumber;
}
public G this[int line]
{
get
{
return Page[line];
}
}
}
}
}
}
| 33.283784 | 89 | 0.394438 | [
"MIT"
] | maron6/SEIDR | SEIDR/Doc/DocSorter.Cache.cs | 4,928 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
// 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("WinRTOutlookLockscreen")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WinRTOutlookLockscreen")]
[assembly: AssemblyCopyright("Copyright © 2013 Christopher Schleiden")]
[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("d2508668-3d36-4a38-9c7c-c299ad57e797")]
// 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.487179 | 85 | 0.732845 | [
"MIT"
] | cschleiden/outlock | WinRTLockscreen/Properties/AssemblyInfo.cs | 1,504 | C# |
using BepuPhysics.Collidables;
using BepuUtilities;
using System.Numerics;
namespace BepuPhysics.CollisionDetection.SweepTasks
{
public struct CapsulePairDistanceTester : IPairDistanceTester<CapsuleWide, CapsuleWide>
{
public void Test(in CapsuleWide a, in CapsuleWide b, in Vector3Wide offsetB, in QuaternionWide orientationA, in QuaternionWide orientationB, in Vector<int> inactiveLanes,
out Vector<int> intersected, out Vector<float> distance, out Vector3Wide closestA, out Vector3Wide normal)
{
//Compute the closest points between the two line segments. No clamping to begin with.
//We want to minimize distance = ||(a + da * ta) - (b + db * tb)||.
//Taking the derivative with respect to ta and doing some algebra (taking into account ||da|| == ||db|| == 1) to solve for ta yields:
//ta = (da * (b - a) + (db * (a - b)) * (da * db)) / (1 - ((da * db) * (da * db))
var da = QuaternionWide.TransformUnitY(orientationA);
var db = QuaternionWide.TransformUnitY(orientationB);
Vector3Wide.Dot(da, offsetB, out var daOffsetB);
Vector3Wide.Dot(db, offsetB, out var dbOffsetB);
Vector3Wide.Dot(da, db, out var dadb);
//Note potential division by zero when the axes are parallel. Arbitrarily clamp; near zero values will instead produce extreme values which get clamped to reasonable results.
var ta = (daOffsetB - dbOffsetB * dadb) / Vector.Max(new Vector<float>(1e-15f), Vector<float>.One - dadb * dadb);
//tb = ta * (da * db) - db * (b - a)
var tb = ta * dadb - dbOffsetB;
//We cannot simply clamp the ta and tb values to the capsule line segments. Instead, project each line segment onto the other line segment, clamping against the target's interval.
//That new clamped projected interval is the valid solution space on that line segment. We can clamp the t value by that interval to get the correctly bounded solution.
//The projected intervals are:
//B onto A: +-BHalfLength * (da * db) + da * offsetB
//A onto B: +-AHalfLength * (da * db) - db * offsetB
var absdadb = Vector.Abs(dadb);
var bOntoAOffset = b.HalfLength * absdadb;
var aOntoBOffset = a.HalfLength * absdadb;
var aMin = Vector.Max(-a.HalfLength, Vector.Min(a.HalfLength, daOffsetB - bOntoAOffset));
var aMax = Vector.Min(a.HalfLength, Vector.Max(-a.HalfLength, daOffsetB + bOntoAOffset));
var bMin = Vector.Max(-b.HalfLength, Vector.Min(b.HalfLength, -aOntoBOffset - dbOffsetB));
var bMax = Vector.Min(b.HalfLength, Vector.Max(-b.HalfLength, aOntoBOffset - dbOffsetB));
ta = Vector.Min(Vector.Max(ta, aMin), aMax);
tb = Vector.Min(Vector.Max(tb, bMin), bMax);
Vector3Wide.Scale(da, ta, out closestA);
Vector3Wide.Scale(db, tb, out var closestB);
Vector3Wide.Add(closestB, offsetB, out closestB);
Vector3Wide.Subtract(closestA, closestB, out normal);
Vector3Wide.Length(normal, out distance);
var inverseDistance = Vector<float>.One / distance;
Vector3Wide.Scale(normal, inverseDistance, out normal);
Vector3Wide.Scale(normal, a.Radius, out var aOffset);
Vector3Wide.Subtract(closestA, aOffset, out closestA);
distance = distance - a.Radius - b.Radius;
intersected = Vector.LessThanOrEqual(distance, Vector<float>.Zero);
}
}
}
| 63.368421 | 191 | 0.639812 | [
"Apache-2.0"
] | TraistaRafael/bepuphysics2 | BepuPhysics/CollisionDetection/SweepTasks/CapsulePairDistanceTester.cs | 3,614 | C# |
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.Azure.IoTSolutions.AsaManager.Services.Diagnostics;
using Microsoft.Azure.IoTSolutions.AsaManager.Services.Exceptions;
using Microsoft.Extensions.Configuration;
namespace Microsoft.Azure.IoTSolutions.AsaManager.Services.Runtime
{
public interface IConfigData
{
string GetString(string key, string defaultValue = "");
bool GetBool(string key, bool defaultValue = false);
int GetInt(string key, int defaultValue = 0);
}
public class ConfigData : IConfigData
{
private readonly IConfigurationRoot configuration;
private readonly ILogger log;
public ConfigData(ILogger logger)
{
this.log = logger;
// More info about configuration at
// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration
var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddIniFile("appsettings.ini", optional: true, reloadOnChange: true);
this.configuration = configurationBuilder.Build();
}
public string GetString(string key, string defaultValue = "")
{
var value = this.configuration.GetValue(key, defaultValue);
this.ReplaceEnvironmentVariables(ref value, defaultValue);
return value;
}
public bool GetBool(string key, bool defaultValue = false)
{
var value = this.GetString(key, defaultValue.ToString()).ToLowerInvariant();
var knownTrue = new HashSet<string> { "true", "t", "yes", "y", "1", "-1" };
var knownFalse = new HashSet<string> { "false", "f", "no", "n", "0" };
if (knownTrue.Contains(value)) return true;
if (knownFalse.Contains(value)) return false;
return defaultValue;
}
public int GetInt(string key, int defaultValue = 0)
{
try
{
return Convert.ToInt32(this.GetString(key, defaultValue.ToString()));
}
catch (Exception e)
{
throw new InvalidConfigurationException($"Unable to load configuration value for '{key}'", e);
}
}
private void ReplaceEnvironmentVariables(ref string value, string defaultValue = "")
{
if (string.IsNullOrEmpty(value)) return;
this.ProcessMandatoryPlaceholders(ref value);
this.ProcessOptionalPlaceholders(ref value, out bool notFound);
if (notFound && string.IsNullOrEmpty(value))
{
value = defaultValue;
}
}
private void ProcessMandatoryPlaceholders(ref string value)
{
// Pattern for mandatory replacements: ${VAR_NAME}
const string PATTERN = @"\${([a-zA-Z_][a-zA-Z0-9_]*)}";
// Search
var keys = (from Match m in Regex.Matches(value, PATTERN)
select m.Groups[1].Value).Distinct().ToArray();
// Replace
foreach (DictionaryEntry x in Environment.GetEnvironmentVariables())
{
if (keys.Contains(x.Key))
{
value = value.Replace("${" + x.Key + "}", x.Value.ToString());
}
}
// Non replaced placeholders cause an exception
keys = (from Match m in Regex.Matches(value, PATTERN)
select m.Groups[1].Value).ToArray();
if (keys.Length > 0)
{
var varsNotFound = keys.Aggregate(", ", (current, k) => current + k);
this.log.Error("Environment variables not found", () => new { varsNotFound });
throw new InvalidConfigurationException("Environment variables not found: " + varsNotFound);
}
}
private void ProcessOptionalPlaceholders(ref string value, out bool notFound)
{
notFound = false;
// Pattern for optional replacements: ${?VAR_NAME}
const string PATTERN = @"\${\?([a-zA-Z_][a-zA-Z0-9_]*)}";
// Search
var keys = (from Match m in Regex.Matches(value, PATTERN)
select m.Groups[1].Value).Distinct().ToArray();
// Replace
foreach (DictionaryEntry x in Environment.GetEnvironmentVariables())
{
if (keys.Contains(x.Key))
{
value = value.Replace("${?" + x.Key + "}", x.Value.ToString());
}
}
// Non replaced placeholders cause an exception
keys = (from Match m in Regex.Matches(value, PATTERN)
select m.Groups[1].Value).ToArray();
if (keys.Length > 0)
{
// Remove placeholders
value = keys.Aggregate(value, (current, k) => current.Replace("${?" + k + "}", string.Empty));
var varsNotFound = keys.Aggregate(", ", (current, k) => current + k);
this.log.Warn("Environment variables not found", () => new { varsNotFound });
notFound = true;
}
}
}
}
| 36.181208 | 110 | 0.563346 | [
"MIT"
] | Azure-Samples/AI-Video-Intelligence-Solution-Accelerator | pcs/services/asa-manager/Services/Runtime/ConfigData.cs | 5,391 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
namespace Core.Linq.Memory
{
class Grouping<TKey,TElement> : IGrouping<TKey,TElement>
{
IEnumerable<TElement> elements;
TKey key;
internal Grouping(TKey key, IEnumerable<TElement> elements)
{
this.elements = elements;
this.key = key;
}
public IEnumerator<TElement> GetEnumerator()
{
return elements.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public TKey Key
{
get { return key; }
}
}
}
| 20.411765 | 67 | 0.560519 | [
"MIT"
] | HolisticWare/HolisticWare.Core.Linq | source/HolisticWare.Core.LINQ/netstandard1.1/Core/Linq/Memory/Grouping.cs | 696 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
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.Monitor.Models;
using Azure.ResourceManager.Resources;
namespace Azure.ResourceManager.Monitor
{
/// <summary>
/// A Class representing a DataCollectionRule along with the instance operations that can be performed on it.
/// If you have a <see cref="ResourceIdentifier" /> you can construct a <see cref="DataCollectionRuleResource" />
/// from an instance of <see cref="ArmClient" /> using the GetDataCollectionRuleResource method.
/// Otherwise you can get one from its parent resource <see cref="ResourceGroupResource" /> using the GetDataCollectionRule method.
/// </summary>
public partial class DataCollectionRuleResource : ArmResource
{
/// <summary> Generate the resource identifier of a <see cref="DataCollectionRuleResource"/> instance. </summary>
public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string dataCollectionRuleName)
{
var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}";
return new ResourceIdentifier(resourceId);
}
private readonly ClientDiagnostics _dataCollectionRuleClientDiagnostics;
private readonly DataCollectionRulesRestOperations _dataCollectionRuleRestClient;
private readonly ClientDiagnostics _dataCollectionRuleAssociationClientDiagnostics;
private readonly DataCollectionRuleAssociationsRestOperations _dataCollectionRuleAssociationRestClient;
private readonly DataCollectionRuleData _data;
/// <summary> Initializes a new instance of the <see cref="DataCollectionRuleResource"/> class for mocking. </summary>
protected DataCollectionRuleResource()
{
}
/// <summary> Initializes a new instance of the <see cref = "DataCollectionRuleResource"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="data"> The resource that is the target of operations. </param>
internal DataCollectionRuleResource(ArmClient client, DataCollectionRuleData data) : this(client, data.Id)
{
HasData = true;
_data = data;
}
/// <summary> Initializes a new instance of the <see cref="DataCollectionRuleResource"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal DataCollectionRuleResource(ArmClient client, ResourceIdentifier id) : base(client, id)
{
_dataCollectionRuleClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Monitor", ResourceType.Namespace, Diagnostics);
TryGetApiVersion(ResourceType, out string dataCollectionRuleApiVersion);
_dataCollectionRuleRestClient = new DataCollectionRulesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, dataCollectionRuleApiVersion);
_dataCollectionRuleAssociationClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Monitor", DataCollectionRuleAssociationResource.ResourceType.Namespace, Diagnostics);
TryGetApiVersion(DataCollectionRuleAssociationResource.ResourceType, out string dataCollectionRuleAssociationApiVersion);
_dataCollectionRuleAssociationRestClient = new DataCollectionRuleAssociationsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, dataCollectionRuleAssociationApiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Gets the resource type for the operations. </summary>
public static readonly ResourceType ResourceType = "Microsoft.Insights/dataCollectionRules";
/// <summary> Gets whether or not the current instance has data. </summary>
public virtual bool HasData { get; }
/// <summary> Gets the data representing this Feature. </summary>
/// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
public virtual DataCollectionRuleData Data
{
get
{
if (!HasData)
throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
return _data;
}
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id));
}
/// <summary>
/// Returns the specified data collection rule.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}
/// Operation Id: DataCollectionRules_Get
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<DataCollectionRuleResource>> GetAsync(CancellationToken cancellationToken = default)
{
using var scope = _dataCollectionRuleClientDiagnostics.CreateScope("DataCollectionRuleResource.Get");
scope.Start();
try
{
var response = await _dataCollectionRuleRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new DataCollectionRuleResource(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Returns the specified data collection rule.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}
/// Operation Id: DataCollectionRules_Get
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<DataCollectionRuleResource> Get(CancellationToken cancellationToken = default)
{
using var scope = _dataCollectionRuleClientDiagnostics.CreateScope("DataCollectionRuleResource.Get");
scope.Start();
try
{
var response = _dataCollectionRuleRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new DataCollectionRuleResource(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Deletes a data collection rule.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}
/// Operation Id: DataCollectionRules_Delete
/// </summary>
/// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<ArmOperation> DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default)
{
using var scope = _dataCollectionRuleClientDiagnostics.CreateScope("DataCollectionRuleResource.Delete");
scope.Start();
try
{
var response = await _dataCollectionRuleRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false);
var operation = new MonitorArmOperation(response);
if (waitUntil == WaitUntil.Completed)
await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Deletes a data collection rule.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}
/// Operation Id: DataCollectionRules_Delete
/// </summary>
/// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default)
{
using var scope = _dataCollectionRuleClientDiagnostics.CreateScope("DataCollectionRuleResource.Delete");
scope.Start();
try
{
var response = _dataCollectionRuleRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken);
var operation = new MonitorArmOperation(response);
if (waitUntil == WaitUntil.Completed)
operation.WaitForCompletionResponse(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Updates part of a data collection rule.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}
/// Operation Id: DataCollectionRules_Update
/// </summary>
/// <param name="body"> The payload. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="body"/> is null. </exception>
public virtual async Task<Response<DataCollectionRuleResource>> UpdateAsync(ResourceForUpdate body, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(body, nameof(body));
using var scope = _dataCollectionRuleClientDiagnostics.CreateScope("DataCollectionRuleResource.Update");
scope.Start();
try
{
var response = await _dataCollectionRuleRestClient.UpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, body, cancellationToken).ConfigureAwait(false);
return Response.FromValue(new DataCollectionRuleResource(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Updates part of a data collection rule.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}
/// Operation Id: DataCollectionRules_Update
/// </summary>
/// <param name="body"> The payload. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="body"/> is null. </exception>
public virtual Response<DataCollectionRuleResource> Update(ResourceForUpdate body, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(body, nameof(body));
using var scope = _dataCollectionRuleClientDiagnostics.CreateScope("DataCollectionRuleResource.Update");
scope.Start();
try
{
var response = _dataCollectionRuleRestClient.Update(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, body, cancellationToken);
return Response.FromValue(new DataCollectionRuleResource(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Lists associations for the specified data collection rule.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}/associations
/// Operation Id: DataCollectionRuleAssociations_ListByRule
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="DataCollectionRuleAssociationResource" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<DataCollectionRuleAssociationResource> GetDataCollectionRuleAssociationsByRuleAsync(CancellationToken cancellationToken = default)
{
async Task<Page<DataCollectionRuleAssociationResource>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _dataCollectionRuleAssociationClientDiagnostics.CreateScope("DataCollectionRuleResource.GetDataCollectionRuleAssociationsByRule");
scope.Start();
try
{
var response = await _dataCollectionRuleAssociationRestClient.ListByRuleAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new DataCollectionRuleAssociationResource(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<DataCollectionRuleAssociationResource>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _dataCollectionRuleAssociationClientDiagnostics.CreateScope("DataCollectionRuleResource.GetDataCollectionRuleAssociationsByRule");
scope.Start();
try
{
var response = await _dataCollectionRuleAssociationRestClient.ListByRuleNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new DataCollectionRuleAssociationResource(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Lists associations for the specified data collection rule.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}/associations
/// Operation Id: DataCollectionRuleAssociations_ListByRule
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="DataCollectionRuleAssociationResource" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<DataCollectionRuleAssociationResource> GetDataCollectionRuleAssociationsByRule(CancellationToken cancellationToken = default)
{
Page<DataCollectionRuleAssociationResource> FirstPageFunc(int? pageSizeHint)
{
using var scope = _dataCollectionRuleAssociationClientDiagnostics.CreateScope("DataCollectionRuleResource.GetDataCollectionRuleAssociationsByRule");
scope.Start();
try
{
var response = _dataCollectionRuleAssociationRestClient.ListByRule(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new DataCollectionRuleAssociationResource(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<DataCollectionRuleAssociationResource> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _dataCollectionRuleAssociationClientDiagnostics.CreateScope("DataCollectionRuleResource.GetDataCollectionRuleAssociationsByRule");
scope.Start();
try
{
var response = _dataCollectionRuleAssociationRestClient.ListByRuleNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new DataCollectionRuleAssociationResource(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Add a tag to the current resource.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}
/// Operation Id: DataCollectionRules_Get
/// </summary>
/// <param name="key"> The key for the tag. </param>
/// <param name="value"> The value for the tag. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="key"/> or <paramref name="value"/> is null. </exception>
public virtual async Task<Response<DataCollectionRuleResource>> AddTagAsync(string key, string value, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(key, nameof(key));
Argument.AssertNotNull(value, nameof(value));
using var scope = _dataCollectionRuleClientDiagnostics.CreateScope("DataCollectionRuleResource.AddTag");
scope.Start();
try
{
var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false);
originalTags.Value.Data.TagValues[key] = value;
await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false);
var originalResponse = await _dataCollectionRuleRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false);
return Response.FromValue(new DataCollectionRuleResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Add a tag to the current resource.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}
/// Operation Id: DataCollectionRules_Get
/// </summary>
/// <param name="key"> The key for the tag. </param>
/// <param name="value"> The value for the tag. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="key"/> or <paramref name="value"/> is null. </exception>
public virtual Response<DataCollectionRuleResource> AddTag(string key, string value, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(key, nameof(key));
Argument.AssertNotNull(value, nameof(value));
using var scope = _dataCollectionRuleClientDiagnostics.CreateScope("DataCollectionRuleResource.AddTag");
scope.Start();
try
{
var originalTags = GetTagResource().Get(cancellationToken);
originalTags.Value.Data.TagValues[key] = value;
GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken);
var originalResponse = _dataCollectionRuleRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken);
return Response.FromValue(new DataCollectionRuleResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Replace the tags on the resource with the given set.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}
/// Operation Id: DataCollectionRules_Get
/// </summary>
/// <param name="tags"> The set of tags to use as replacement. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="tags"/> is null. </exception>
public virtual async Task<Response<DataCollectionRuleResource>> SetTagsAsync(IDictionary<string, string> tags, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(tags, nameof(tags));
using var scope = _dataCollectionRuleClientDiagnostics.CreateScope("DataCollectionRuleResource.SetTags");
scope.Start();
try
{
await GetTagResource().DeleteAsync(WaitUntil.Completed, cancellationToken: cancellationToken).ConfigureAwait(false);
var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false);
originalTags.Value.Data.TagValues.ReplaceWith(tags);
await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false);
var originalResponse = await _dataCollectionRuleRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false);
return Response.FromValue(new DataCollectionRuleResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Replace the tags on the resource with the given set.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}
/// Operation Id: DataCollectionRules_Get
/// </summary>
/// <param name="tags"> The set of tags to use as replacement. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="tags"/> is null. </exception>
public virtual Response<DataCollectionRuleResource> SetTags(IDictionary<string, string> tags, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(tags, nameof(tags));
using var scope = _dataCollectionRuleClientDiagnostics.CreateScope("DataCollectionRuleResource.SetTags");
scope.Start();
try
{
GetTagResource().Delete(WaitUntil.Completed, cancellationToken: cancellationToken);
var originalTags = GetTagResource().Get(cancellationToken);
originalTags.Value.Data.TagValues.ReplaceWith(tags);
GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken);
var originalResponse = _dataCollectionRuleRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken);
return Response.FromValue(new DataCollectionRuleResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Removes a tag by key from the resource.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}
/// Operation Id: DataCollectionRules_Get
/// </summary>
/// <param name="key"> The key for the tag. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="key"/> is null. </exception>
public virtual async Task<Response<DataCollectionRuleResource>> RemoveTagAsync(string key, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(key, nameof(key));
using var scope = _dataCollectionRuleClientDiagnostics.CreateScope("DataCollectionRuleResource.RemoveTag");
scope.Start();
try
{
var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false);
originalTags.Value.Data.TagValues.Remove(key);
await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false);
var originalResponse = await _dataCollectionRuleRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false);
return Response.FromValue(new DataCollectionRuleResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Removes a tag by key from the resource.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionRules/{dataCollectionRuleName}
/// Operation Id: DataCollectionRules_Get
/// </summary>
/// <param name="key"> The key for the tag. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="key"/> is null. </exception>
public virtual Response<DataCollectionRuleResource> RemoveTag(string key, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(key, nameof(key));
using var scope = _dataCollectionRuleClientDiagnostics.CreateScope("DataCollectionRuleResource.RemoveTag");
scope.Start();
try
{
var originalTags = GetTagResource().Get(cancellationToken);
originalTags.Value.Data.TagValues.Remove(key);
GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken);
var originalResponse = _dataCollectionRuleRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken);
return Response.FromValue(new DataCollectionRuleResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
| 58.462136 | 488 | 0.666036 | [
"MIT"
] | ChenTanyi/azure-sdk-for-net | sdk/monitor/Azure.ResourceManager.Monitor/src/Generated/DataCollectionRuleResource.cs | 30,108 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Swashbuckle.AspNetCore.Swagger.ExportExtension.Models
{
internal class ResponseModelInfo : BaseModelInfo
{
}
}
| 18.363636 | 63 | 0.772277 | [
"MIT"
] | Snuger/Swashbuckle.AspNetCore.Swagger.ExportExtension | src/Swashbuckle.AspNetCore.Swagger.ExportExtension/Models/ResponseModelInfo.cs | 204 | C# |
//
// Copyright (C) 2010 Novell Inc. http://novell.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Markup;
using System.Xaml;
using System.Xaml.Schema;
using System.Xml;
using NUnit.Framework;
using CategoryAttribute = NUnit.Framework.CategoryAttribute;
// Some test result remarks:
// - TypeExtension: [ConstructorArgument] -> PositionalParameters
// - StaticExtension: almost identical to TypeExtension
// - Reference: [ConstructorArgument], [ContentProperty] -> only ordinal member.
// - ArrayExtension: [ConstrutorArgument], [ContentProperty] -> no PositionalParameters, Items.
// - NullExtension: no member.
// - MyExtension: [ConstructorArgument] -> only ordinal members...hmm?
namespace MonoTests.System.Xaml
{
public partial class XamlReaderTestBase
{
protected void Read_String (XamlReader r)
{
Assert.AreEqual (XamlNodeType.None, r.NodeType, "#1");
Assert.IsNull (r.Member, "#2");
Assert.IsNull (r.Namespace, "#3");
Assert.IsNull (r.Member, "#4");
Assert.IsNull (r.Type, "#5");
Assert.IsNull (r.Value, "#6");
Assert.IsTrue (r.Read (), "#11");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
Assert.IsNotNull (r.Namespace, "#13");
Assert.AreEqual ("x", r.Namespace.Prefix, "#13-2");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#13-3");
Assert.IsTrue (r.Read (), "#21");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#22");
Assert.IsNotNull (r.Type, "#23");
Assert.AreEqual (new XamlType (typeof (string), r.SchemaContext), r.Type, "#23-2");
Assert.IsNull (r.Namespace, "#25");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "#31");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#32");
Assert.IsNotNull (r.Member, "#33");
Assert.AreEqual (XamlLanguage.Initialization, r.Member, "#33-2");
Assert.IsNull (r.Type, "#34");
Assert.IsTrue (r.Read (), "#41");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#42");
Assert.AreEqual ("foo", r.Value, "#43");
Assert.IsNull (r.Member, "#44");
Assert.IsTrue (r.Read (), "#51");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#52");
Assert.IsNull (r.Type, "#53");
Assert.IsNull (r.Member, "#54");
Assert.IsTrue (r.Read (), "#61");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#62");
Assert.IsNull (r.Type, "#63");
Assert.IsFalse (r.Read (), "#71");
Assert.IsTrue (r.IsEof, "#72");
}
protected void WriteNullMemberAsObject (XamlReader r, Action validateNullInstance)
{
Assert.AreEqual (XamlNodeType.None, r.NodeType, "#1");
Assert.IsTrue (r.Read (), "#6");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#7");
Assert.AreEqual (String.Empty, r.Namespace.Prefix, "#7-2");
Assert.AreEqual ("clr-namespace:MonoTests.System.Xaml;assembly=" + GetType ().Assembly.GetName ().Name, r.Namespace.Namespace, "#7-3");
Assert.IsTrue (r.Read (), "#11");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
Assert.AreEqual ("x", r.Namespace.Prefix, "#12-2");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#12-3");
Assert.IsTrue (r.Read (), "#16");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#17");
var xt = new XamlType (typeof (TestClass4), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "#17-2");
// Assert.IsTrue (r.Instance is TestClass4, "#17-3");
Assert.AreEqual (2, xt.GetAllMembers ().Count, "#17-4");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "#21");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#22");
Assert.AreEqual (xt.GetMember ("Bar"), r.Member, "#22-2");
Assert.IsTrue (r.Read (), "#26");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#27");
Assert.AreEqual (XamlLanguage.Null, r.Type, "#27-2");
if (validateNullInstance != null)
validateNullInstance ();
Assert.IsTrue (r.Read (), "#31");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#32");
Assert.IsTrue (r.Read (), "#36");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#37");
Assert.IsTrue (r.Read (), "#41");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#42");
Assert.AreEqual (xt.GetMember ("Foo"), r.Member, "#42-2");
Assert.IsTrue (r.Read (), "#43");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#43-2");
Assert.AreEqual (XamlLanguage.Null, r.Type, "#43-3");
if (validateNullInstance != null)
validateNullInstance ();
Assert.IsTrue (r.Read (), "#44");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#44-2");
Assert.IsTrue (r.Read (), "#46");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#47");
Assert.IsTrue (r.Read (), "#51");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#52");
Assert.IsFalse (r.Read (), "#56");
Assert.IsTrue (r.IsEof, "#57");
}
protected void StaticMember (XamlReader r)
{
Assert.AreEqual (XamlNodeType.None, r.NodeType, "#1");
Assert.IsTrue (r.Read (), "#6");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#7");
Assert.AreEqual (String.Empty, r.Namespace.Prefix, "#7-2");
Assert.AreEqual ("clr-namespace:MonoTests.System.Xaml;assembly=" + GetType ().Assembly.GetName ().Name, r.Namespace.Namespace, "#7-3");
Assert.IsTrue (r.Read (), "#11");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
Assert.AreEqual ("x", r.Namespace.Prefix, "#12-2");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#12-3");
Assert.IsTrue (r.Read (), "#16");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#17");
var xt = new XamlType (typeof (TestClass5), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "#17-2");
// Assert.IsTrue (r.Instance is TestClass5, "#17-3");
Assert.AreEqual (2, xt.GetAllMembers ().Count, "#17-4");
Assert.IsTrue (xt.GetAllMembers ().Any (xm => xm.Name == "Bar"), "#17-5");
Assert.IsTrue (xt.GetAllMembers ().Any (xm => xm.Name == "Baz"), "#17-6");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "#21");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#22");
Assert.AreEqual (xt.GetMember ("Bar"), r.Member, "#22-2");
Assert.IsTrue (r.Read (), "#26");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#27");
Assert.AreEqual (XamlLanguage.Null, r.Type, "#27-2");
// Assert.IsNull (r.Instance, "#27-3");
Assert.IsTrue (r.Read (), "#31");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#32");
Assert.IsTrue (r.Read (), "#36");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#37");
// static Foo is not included in GetAllXembers() return value.
// ReadOnly is not included in GetAllMembers() return value neither.
// nonpublic Baz is a member, but does not appear in the reader.
Assert.IsTrue (r.Read (), "#51");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#52");
Assert.IsFalse (r.Read (), "#56");
Assert.IsTrue (r.IsEof, "#57");
}
protected void Skip (XamlReader r)
{
r.Skip ();
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#1");
r.Skip ();
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#2");
r.Skip ();
Assert.IsTrue (r.IsEof, "#3");
}
protected void Skip2 (XamlReader r)
{
r.Read (); // NamespaceDeclaration
r.Read (); // Type
if (r is XamlXmlReader)
ReadBase (r);
r.Read (); // Member (Initialization)
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#1");
r.Skip ();
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#2");
r.Skip ();
Assert.IsTrue (r.IsEof, "#3");
}
protected void Read_XmlDocument (XamlReader r)
{
for (int i = 0; i < 3; i++) {
r.Read ();
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#1-" + i);
}
r.Read ();
Assert.AreEqual (new XamlType (typeof (XmlDocument), r.SchemaContext), r.Type, "#2");
r.Read ();
var l = new List<XamlMember> ();
while (r.NodeType == XamlNodeType.StartMember) {
// It depends on XmlDocument's implenentation details. It fails on mono only because XmlDocument.SchemaInfo overrides both getter and setter.
//for (int i = 0; i < 5; i++) {
// Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#3-" + i);
l.Add (r.Member);
r.Skip ();
}
Assert.IsNotNull (l.FirstOrDefault (m => m.Name == "Value"), "#4-1");
Assert.IsNotNull (l.FirstOrDefault (m => m.Name == "InnerXml"), "#4-2");
Assert.IsNotNull (l.FirstOrDefault (m => m.Name == "Prefix"), "#4-3");
Assert.IsNotNull (l.FirstOrDefault (m => m.Name == "PreserveWhitespace"), "#4-4");
Assert.IsNotNull (l.FirstOrDefault (m => m.Name == "Schemas"), "#4-5");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#5");
Assert.IsFalse (r.Read (), "#6");
}
protected void Read_NonPrimitive (XamlReader r)
{
Assert.AreEqual (XamlNodeType.None, r.NodeType, "#1");
Assert.IsTrue (r.Read (), "#6");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#7");
Assert.AreEqual (String.Empty, r.Namespace.Prefix, "#7-2");
Assert.AreEqual ("clr-namespace:MonoTests.System.Xaml;assembly=" + GetType ().Assembly.GetName ().Name, r.Namespace.Namespace, "#7-3");
Assert.IsTrue (r.Read (), "#11");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
Assert.AreEqual ("x", r.Namespace.Prefix, "#12-2");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#12-3");
Assert.IsTrue (r.Read (), "#16");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#17");
var xt = new XamlType (typeof (TestClass3), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "#17-2");
// Assert.IsTrue (r.Instance is TestClass3, "#17-3");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "#21");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#22");
Assert.AreEqual (xt.GetMember ("Nested"), r.Member, "#22-2");
Assert.IsTrue (r.Read (), "#26");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#27");
Assert.AreEqual (XamlLanguage.Null, r.Type, "#27-2");
// Assert.IsNull (r.Instance, "#27-3");
Assert.IsTrue (r.Read (), "#31");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#32");
Assert.IsTrue (r.Read (), "#36");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#37");
Assert.IsTrue (r.Read (), "#41");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#42");
Assert.IsFalse (r.Read (), "#46");
Assert.IsTrue (r.IsEof, "#47");
}
protected void Read_TypeOrTypeExtension (XamlReader r, Action validateInstance, XamlMember ctorArgMember)
{
Assert.IsTrue (r.Read (), "#11");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
Assert.IsNotNull (r.Namespace, "#13");
Assert.AreEqual ("x", r.Namespace.Prefix, "#13-2");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#13-3");
// Assert.IsNull (r.Instance, "#14");
Assert.IsTrue (r.Read (), "#21");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#22");
Assert.IsNotNull (r.Type, "#23");
Assert.AreEqual (XamlLanguage.Type, r.Type, "#23-2");
Assert.IsNull (r.Namespace, "#25");
if (validateInstance != null)
validateInstance ();
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "#31");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#32");
Assert.IsNotNull (r.Member, "#33");
Assert.AreEqual (ctorArgMember, r.Member, "#33-2");
Assert.IsNull (r.Type, "#34");
// Assert.IsNull (r.Instance, "#35");
Assert.IsTrue (r.Read (), "#41");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#42");
Assert.IsNotNull (r.Value, "#43");
Assert.AreEqual ("x:Int32", r.Value, "#43-2");
Assert.IsNull (r.Member, "#44");
// Assert.IsNull (r.Instance, "#45");
Assert.IsTrue (r.Read (), "#51");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#52");
Assert.IsNull (r.Type, "#53");
Assert.IsNull (r.Member, "#54");
// Assert.IsNull (r.Instance, "#55");
Assert.IsTrue (r.Read (), "#61");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#62");
Assert.IsNull (r.Type, "#63");
Assert.IsFalse (r.Read (), "#71");
Assert.IsTrue (r.IsEof, "#72");
}
protected void Read_TypeOrTypeExtension2 (XamlReader r, Action validateInstance, XamlMember ctorArgMember)
{
Assert.IsTrue (r.Read (), "#11");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
var defns = "clr-namespace:MonoTests.System.Xaml;assembly=" + GetType ().Assembly.GetName ().Name;
Assert.AreEqual (String.Empty, r.Namespace.Prefix, "#13-2");
Assert.AreEqual (defns, r.Namespace.Namespace, "#13-3:" + r.Namespace.Prefix);
Assert.IsTrue (r.Read (), "#16");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#17");
Assert.IsNotNull (r.Namespace, "#18");
Assert.AreEqual ("x", r.Namespace.Prefix, "#18-2");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#18-3:" + r.Namespace.Prefix);
Assert.IsTrue (r.Read (), "#21");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#22");
Assert.AreEqual (new XamlType (typeof (TypeExtension), r.SchemaContext), r.Type, "#23-2");
if (validateInstance != null)
validateInstance ();
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "#31");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#32");
Assert.AreEqual (ctorArgMember, r.Member, "#33-2");
Assert.IsTrue (r.Read (), "#41");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#42");
Assert.AreEqual ("TestClass1", r.Value, "#43-2");
Assert.IsTrue (r.Read (), "#51");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#52");
Assert.IsTrue (r.Read (), "#61");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#62");
Assert.IsFalse (r.Read (), "#71");
Assert.IsTrue (r.IsEof, "#72");
}
protected void Read_Reference (XamlReader r)
{
Assert.IsTrue (r.Read (), "#11");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
Assert.AreEqual ("x", r.Namespace.Prefix, "#13-2");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#13-3");
Assert.IsTrue (r.Read (), "#21");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#22");
var xt = new XamlType (typeof (Reference), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "#23-2");
// Assert.IsTrue (r.Instance is Reference, "#26");
Assert.IsNotNull (XamlLanguage.Type.SchemaContext, "#23-3");
Assert.IsNotNull (r.SchemaContext, "#23-4");
Assert.AreNotEqual (XamlLanguage.Type.SchemaContext, r.SchemaContext, "#23-5");
Assert.AreNotEqual (XamlLanguage.Reference.SchemaContext, xt.SchemaContext, "#23-6");
Assert.AreEqual (XamlLanguage.Reference, xt, "#23-7");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "#31");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#32");
// unlike TypeExtension there is no PositionalParameters.
Assert.AreEqual (xt.GetMember ("Name"), r.Member, "#33-2");
// It is a ContentProperty (besides [ConstructorArgument])
Assert.IsTrue (r.Read (), "#41");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#42");
Assert.AreEqual ("FooBar", r.Value, "#43-2");
Assert.IsTrue (r.Read (), "#51");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#52");
Assert.IsTrue (r.Read (), "#61");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#62");
Assert.IsFalse (r.Read (), "#71");
Assert.IsTrue (r.IsEof, "#72");
}
protected void Read_NullOrNullExtension (XamlReader r, Action validateInstance)
{
Assert.IsTrue (r.Read (), "#11");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
Assert.IsNotNull (r.Namespace, "#13");
Assert.AreEqual ("x", r.Namespace.Prefix, "#13-2");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#13-3");
// Assert.IsNull (r.Instance, "#14");
Assert.IsTrue (r.Read (), "#21");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#22");
Assert.AreEqual (new XamlType (typeof (NullExtension), r.SchemaContext), r.Type, "#23-2");
if (validateInstance != null)
validateInstance ();
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "#61");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#62");
Assert.IsFalse (r.Read (), "#71");
Assert.IsTrue (r.IsEof, "#72");
}
// almost identical to TypeExtension (only type/instance difference)
protected void Read_StaticExtension (XamlReader r, XamlMember ctorArgMember)
{
Assert.IsTrue (r.Read (), "#11");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
Assert.IsNotNull (r.Namespace, "#13");
Assert.AreEqual ("x", r.Namespace.Prefix, "#13-2");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#13-3");
// Assert.IsNull (r.Instance, "#14");
Assert.IsTrue (r.Read (), "#21");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#22");
Assert.AreEqual (new XamlType (typeof (StaticExtension), r.SchemaContext), r.Type, "#23-2");
// Assert.IsTrue (r.Instance is StaticExtension, "#26");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "#31");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#32");
Assert.AreEqual (ctorArgMember, r.Member, "#33-2");
Assert.IsTrue (r.Read (), "#41");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#42");
Assert.AreEqual ("FooBar", r.Value, "#43-2");
Assert.IsTrue (r.Read (), "#51");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#52");
Assert.IsTrue (r.Read (), "#61");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#62");
Assert.IsFalse (r.Read (), "#71");
Assert.IsTrue (r.IsEof, "#72");
}
protected void Read_ListInt32 (XamlReader r, Action validateInstance, List<int> obj)
{
Assert.IsTrue (r.Read (), "ns#1-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#1-2");
var defns = "clr-namespace:System.Collections.Generic;assembly=mscorlib";
Assert.AreEqual (String.Empty, r.Namespace.Prefix, "ns#1-3");
Assert.AreEqual (defns, r.Namespace.Namespace, "ns#1-4");
Assert.IsTrue (r.Read (), "#11");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
Assert.IsNotNull (r.Namespace, "#13");
Assert.AreEqual ("x", r.Namespace.Prefix, "#13-2");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#13-3");
Assert.IsTrue (r.Read (), "#21");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#22");
var xt = new XamlType (typeof (List<int>), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "#23");
Assert.IsTrue (xt.IsCollection, "#27");
if (validateInstance != null)
validateInstance ();
// This assumption on member ordering ("Type" then "Items") is somewhat wrong, and we might have to adjust it in the future.
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "#31");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#32");
Assert.AreEqual (xt.GetMember ("Capacity"), r.Member, "#33");
Assert.IsTrue (r.Read (), "#41");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#42");
// The value is implementation details, not testable.
//Assert.AreEqual ("3", r.Value, "#43");
Assert.IsTrue (r.Read (), "#51");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#52");
if (obj.Count > 0) { // only when items exist.
Assert.IsTrue (r.Read (), "#72");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#72-2");
Assert.AreEqual (XamlLanguage.Items, r.Member, "#72-3");
string [] values = {"5", "-3", "2147483647", "0"};
for (int i = 0; i < 4; i++) {
Assert.IsTrue (r.Read (), i + "#73");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, i + "#73-2");
Assert.IsTrue (r.Read (), i + "#74");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, i + "#74-2");
Assert.AreEqual (XamlLanguage.Initialization, r.Member, i + "#74-3");
Assert.IsTrue (r.Read (), i + "#75");
Assert.IsNotNull (r.Value, i + "#75-2");
Assert.AreEqual (values [i], r.Value, i + "#73-3");
Assert.IsTrue (r.Read (), i + "#74");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, i + "#74-2");
Assert.IsTrue (r.Read (), i + "#75");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, i + "#75-2");
}
Assert.IsTrue (r.Read (), "#81");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#82"); // XamlLanguage.Items
} // end of "if count > 0".
Assert.IsTrue (r.Read (), "#87");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#88");
Assert.IsFalse (r.Read (), "#89");
}
protected void Read_ListType (XamlReader r, bool isObjectReader)
{
Assert.IsTrue (r.Read (), "ns#1-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#1-2");
var defns = "clr-namespace:System.Collections.Generic;assembly=mscorlib";
var defns2 = "clr-namespace:System;assembly=mscorlib";
var defns3 = "clr-namespace:System.Xaml;assembly=System.Xaml";
Assert.AreEqual (String.Empty, r.Namespace.Prefix, "ns#1-3");
Assert.AreEqual (defns, r.Namespace.Namespace, "ns#1-4");
Assert.IsTrue (r.Read (), "ns#2-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#2-2");
Assert.IsNotNull (r.Namespace, "ns#2-3");
Assert.AreEqual ("s", r.Namespace.Prefix, "ns#2-3-2");
Assert.AreEqual (defns2, r.Namespace.Namespace, "ns#2-3-3");
Assert.IsTrue (r.Read (), "ns#3-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#3-2");
Assert.IsNotNull (r.Namespace, "ns#3-3");
Assert.AreEqual ("sx", r.Namespace.Prefix, "ns#3-3-2");
Assert.AreEqual (defns3, r.Namespace.Namespace, "ns#3-3-3");
Assert.IsTrue (r.Read (), "#11");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
Assert.IsNotNull (r.Namespace, "#13");
Assert.AreEqual ("x", r.Namespace.Prefix, "#13-2");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#13-3");
Assert.IsTrue (r.Read (), "#21");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#22");
var xt = new XamlType (typeof (List<Type>), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "#23");
Assert.IsTrue (xt.IsCollection, "#27");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "#31");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#32");
Assert.AreEqual (xt.GetMember ("Capacity"), r.Member, "#33");
Assert.IsTrue (r.Read (), "#41");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#42");
Assert.AreEqual ("2", r.Value, "#43");
Assert.IsTrue (r.Read (), "#51");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#52");
Assert.IsTrue (r.Read (), "#72");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#72-2");
Assert.AreEqual (XamlLanguage.Items, r.Member, "#72-3");
string [] values = {"x:Int32", "Dictionary(s:Type, sx:XamlType)"};
for (int i = 0; i < 2; i++) {
Assert.IsTrue (r.Read (), i + "#73");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, i + "#73-2");
Assert.IsTrue (r.Read (), i + "#74");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, i + "#74-2");
// Here XamlObjectReader and XamlXmlReader significantly differs. (Lucky we can make this test conditional so simply)
if (isObjectReader)
Assert.AreEqual (XamlLanguage.PositionalParameters, r.Member, i + "#74-3");
else
Assert.AreEqual (XamlLanguage.Type.GetMember ("Type"), r.Member, i + "#74-3");
Assert.IsTrue (r.Read (), i + "#75");
Assert.IsNotNull (r.Value, i + "#75-2");
Assert.AreEqual (values [i], r.Value, i + "#73-3");
Assert.IsTrue (r.Read (), i + "#74");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, i + "#74-2");
Assert.IsTrue (r.Read (), i + "#75");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, i + "#75-2");
}
Assert.IsTrue (r.Read (), "#81");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#82"); // XamlLanguage.Items
Assert.IsTrue (r.Read (), "#87");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#88");
Assert.IsFalse (r.Read (), "#89");
}
protected void Read_ListArray (XamlReader r)
{
Assert.IsTrue (r.Read (), "ns#1-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#1-2");
var defns = "clr-namespace:System.Collections.Generic;assembly=mscorlib";
var defns2 = "clr-namespace:System;assembly=mscorlib";
var defns3 = "clr-namespace:System.Xaml;assembly=System.Xaml";
Assert.AreEqual (String.Empty, r.Namespace.Prefix, "ns#1-3");
Assert.AreEqual (defns, r.Namespace.Namespace, "ns#1-4");
Assert.IsTrue (r.Read (), "ns#2-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#2-2");
Assert.IsNotNull (r.Namespace, "ns#2-3");
Assert.AreEqual ("s", r.Namespace.Prefix, "ns#2-3-2");
Assert.AreEqual (defns2, r.Namespace.Namespace, "ns#2-3-3");
Assert.IsTrue (r.Read (), "#11");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
Assert.IsNotNull (r.Namespace, "#13");
Assert.AreEqual ("x", r.Namespace.Prefix, "#13-2");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#13-3");
Assert.IsTrue (r.Read (), "#21");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#22");
var xt = new XamlType (typeof (List<Array>), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "#23");
Assert.IsTrue (xt.IsCollection, "#27");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "#31");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#32");
Assert.AreEqual (xt.GetMember ("Capacity"), r.Member, "#33");
Assert.IsTrue (r.Read (), "#41");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#42");
Assert.AreEqual ("2", r.Value, "#43");
Assert.IsTrue (r.Read (), "#51");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#52");
Assert.IsTrue (r.Read (), "#72");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#72-2");
Assert.AreEqual (XamlLanguage.Items, r.Member, "#72-3");
string [] values = {"x:Int32", "x:String"};
for (int i = 0; i < 2; i++) {
Assert.IsTrue (r.Read (), i + "#73");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, i + "#73-2");
Assert.AreEqual (XamlLanguage.Array, r.Type, i + "#73-3");
Assert.IsTrue (r.Read (), i + "#74");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, i + "#74-2");
Assert.AreEqual (XamlLanguage.Array.GetMember ("Type"), r.Member, i + "#74-3");
Assert.IsTrue (r.Read (), i + "#75");
Assert.IsNotNull (r.Value, i + "#75-2");
Assert.AreEqual (values [i], r.Value, i + "#73-3");
Assert.IsTrue (r.Read (), i + "#74");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, i + "#74-2");
Assert.IsTrue (r.Read (), i + "#75");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, i + "#75-2");
Assert.AreEqual (XamlLanguage.Array.GetMember ("Items"), r.Member, i + "#75-3");
Assert.IsTrue (r.Read (), i + "#75-4");
Assert.AreEqual (XamlNodeType.GetObject, r.NodeType, i + "#75-5");
Assert.IsTrue (r.Read (), i + "#75-7");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, i + "#75-8");
Assert.AreEqual (XamlLanguage.Items, r.Member, i + "#75-9");
for (int j = 0; j < 3; j++) {
Assert.IsTrue (r.Read (), i + "#76-" + j);
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, i + "#76-2"+ "-" + j);
Assert.IsTrue (r.Read (), i + "#76-3"+ "-" + j);
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, i + "#76-4"+ "-" + j);
Assert.IsTrue (r.Read (), i + "#76-5"+ "-" + j);
Assert.AreEqual (XamlNodeType.Value, r.NodeType, i + "#76-6"+ "-" + j);
Assert.IsTrue (r.Read (), i + "#76-7"+ "-" + j);
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, i + "#76-8"+ "-" + j);
Assert.IsTrue (r.Read (), i + "#76-9"+ "-" + j);
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, i + "#76-10"+ "-" + j);
}
Assert.IsTrue (r.Read (), i + "#77");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, i + "#77-2");
Assert.IsTrue (r.Read (), i + "#78");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, i + "#78-2");
Assert.IsTrue (r.Read (), i + "#79");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, i + "#79-2");
Assert.IsTrue (r.Read (), i + "#80");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, i + "#80-2");
}
Assert.IsTrue (r.Read (), "#81");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#82"); // XamlLanguage.Items
Assert.IsTrue (r.Read (), "#87");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#88");
Assert.IsFalse (r.Read (), "#89");
}
protected void Read_ArrayList (XamlReader r)
{
Assert.IsTrue (r.Read (), "ns#1-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#1-2");
var defns = "clr-namespace:System.Collections;assembly=mscorlib";
Assert.AreEqual (String.Empty, r.Namespace.Prefix, "ns#1-3");
Assert.AreEqual (defns, r.Namespace.Namespace, "ns#1-4");
Assert.IsTrue (r.Read (), "#11");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
Assert.IsNotNull (r.Namespace, "#13");
Assert.AreEqual ("x", r.Namespace.Prefix, "#13-2");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#13-3");
Assert.IsTrue (r.Read (), "#21");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#22");
var xt = new XamlType (typeof (ArrayList), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "#23");
// Assert.AreEqual (obj, r.Instance, "#26");
Assert.IsTrue (xt.IsCollection, "#27");
if (r is XamlXmlReader)
ReadBase (r);
// This assumption on member ordering ("Type" then "Items") is somewhat wrong, and we might have to adjust it in the future.
Assert.IsTrue (r.Read (), "#31");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#32");
Assert.AreEqual (xt.GetMember ("Capacity"), r.Member, "#33");
Assert.IsTrue (r.Read (), "#41");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#42");
// The value is implementation details, not testable.
//Assert.AreEqual ("3", r.Value, "#43");
Assert.IsTrue (r.Read (), "#51");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#52");
Assert.IsTrue (r.Read (), "#72");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#72-2");
Assert.AreEqual (XamlLanguage.Items, r.Member, "#72-3");
string [] values = {"5", "-3", "0"};
for (int i = 0; i < 3; i++) {
Assert.IsTrue (r.Read (), i + "#73");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, i + "#73-2");
Assert.IsTrue (r.Read (), i + "#74");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, i + "#74-2");
Assert.AreEqual (XamlLanguage.Initialization, r.Member, i + "#74-3");
Assert.IsTrue (r.Read (), i + "#75");
Assert.IsNotNull (r.Value, i + "#75-2");
Assert.AreEqual (values [i], r.Value, i + "#73-3");
Assert.IsTrue (r.Read (), i + "#74");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, i + "#74-2");
Assert.IsTrue (r.Read (), i + "#75");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, i + "#75-2");
}
Assert.IsTrue (r.Read (), "#81");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#82"); // XamlLanguage.Items
Assert.IsTrue (r.Read (), "#87");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#88");
Assert.IsFalse (r.Read (), "#89");
}
protected void Read_ArrayOrArrayExtensionOrMyArrayExtension (XamlReader r, Action validateInstance, Type extType)
{
if (extType == typeof (MyArrayExtension)) {
Assert.IsTrue (r.Read (), "#1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#2");
Assert.IsNotNull (r.Namespace, "#3");
Assert.AreEqual (String.Empty, r.Namespace.Prefix, "#3-2");
}
Assert.IsTrue (r.Read (), "#11");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
Assert.IsNotNull (r.Namespace, "#13");
Assert.AreEqual ("x", r.Namespace.Prefix, "#13-2");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#13-3");
Assert.IsTrue (r.Read (), "#21");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#22");
var xt = new XamlType (extType, r.SchemaContext);
Assert.AreEqual (xt, r.Type, "#23");
if (validateInstance != null)
validateInstance ();
if (r is XamlXmlReader)
ReadBase (r);
// This assumption on member ordering ("Type" then "Items") is somewhat wrong, and we might have to adjust it in the future.
Assert.IsTrue (r.Read (), "#31");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#32");
Assert.AreEqual (xt.GetMember ("Type"), r.Member, "#33");
Assert.IsTrue (r.Read (), "#41");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#42");
Assert.AreEqual ("x:Int32", r.Value, "#43");
Assert.IsTrue (r.Read (), "#51");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#52");
Assert.IsTrue (r.Read (), "#61");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#62");
Assert.AreEqual (xt.GetMember ("Items"), r.Member, "#63");
Assert.IsTrue (r.Read (), "#71");
Assert.AreEqual (XamlNodeType.GetObject, r.NodeType, "#71-2");
Assert.IsNull (r.Type, "#71-3");
Assert.IsNull (r.Member, "#71-4");
Assert.IsNull (r.Value, "#71-5");
Assert.IsTrue (r.Read (), "#72");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#72-2");
Assert.AreEqual (XamlLanguage.Items, r.Member, "#72-3");
string [] values = {"5", "-3", "0"};
for (int i = 0; i < 3; i++) {
Assert.IsTrue (r.Read (), i + "#73");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, i + "#73-2");
Assert.IsTrue (r.Read (), i + "#74");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, i + "#74-2");
Assert.AreEqual (XamlLanguage.Initialization, r.Member, i + "#74-3");
Assert.IsTrue (r.Read (), i + "#75");
Assert.IsNotNull (r.Value, i + "#75-2");
Assert.AreEqual (values [i], r.Value, i + "#73-3");
Assert.IsTrue (r.Read (), i + "#74");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, i + "#74-2");
Assert.IsTrue (r.Read (), i + "#75");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, i + "#75-2");
}
Assert.IsTrue (r.Read (), "#81");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#82"); // XamlLanguage.Items
Assert.IsTrue (r.Read (), "#83");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#84"); // GetObject
Assert.IsTrue (r.Read (), "#85");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#86"); // ArrayExtension.Items
Assert.IsTrue (r.Read (), "#87");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#88"); // ArrayExtension
Assert.IsFalse (r.Read (), "#89");
}
// It gives Type member, not PositionalParameters... and no Items member here.
protected void Read_ArrayExtension2 (XamlReader r)
{
Assert.IsTrue (r.Read (), "#11");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
Assert.IsNotNull (r.Namespace, "#13");
Assert.AreEqual ("x", r.Namespace.Prefix, "#13-2");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#13-3");
// Assert.IsNull (r.Instance, "#14");
Assert.IsTrue (r.Read (), "#21");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#22");
var xt = new XamlType (typeof (ArrayExtension), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "#23-2");
// Assert.IsTrue (r.Instance is ArrayExtension, "#26");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "#31");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#32");
Assert.AreEqual (xt.GetMember ("Type"), r.Member, "#33-2");
Assert.IsTrue (r.Read (), "#41");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#42");
Assert.AreEqual ("x:Int32", r.Value, "#43-2");
Assert.IsTrue (r.Read (), "#51");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#52");
Assert.IsTrue (r.Read (), "#61");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#62");
Assert.IsFalse (r.Read (), "#71");
Assert.IsTrue (r.IsEof, "#72");
}
protected void Read_CustomMarkupExtension (XamlReader r)
{
r.Read (); // ns
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#1");
r.Read (); // ns
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#1-2");
r.Read ();
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#2-0");
Assert.IsFalse (r.IsEof, "#1");
var xt = r.Type;
if (r is XamlXmlReader)
ReadBase (r);
r.Read ();
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#2-1");
Assert.IsFalse (r.IsEof, "#2-2");
Assert.AreEqual (xt.GetMember ("Bar"), r.Member, "#2-3");
Assert.IsTrue (r.Read (), "#2-4");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#2-5");
Assert.AreEqual ("v2", r.Value, "#2-6");
Assert.IsTrue (r.Read (), "#2-7");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#2-8");
r.Read ();
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#3-1");
Assert.IsFalse (r.IsEof, "#3-2");
Assert.AreEqual (xt.GetMember ("Baz"), r.Member, "#3-3");
Assert.IsTrue (r.Read (), "#3-4");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#3-5");
Assert.AreEqual ("v7", r.Value, "#3-6");
Assert.IsTrue (r.Read (), "#3-7");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#3-8");
r.Read ();
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#4-1");
Assert.IsFalse (r.IsEof, "#4-2");
Assert.AreEqual (xt.GetMember ("Foo"), r.Member, "#4-3");
Assert.IsTrue (r.Read (), "#4-4");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#4-5");
Assert.AreEqual ("x:Int32", r.Value, "#4-6");
Assert.IsTrue (r.Read (), "#4-7");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#4-8");
Assert.IsTrue (r.Read (), "#5");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#5-2");
Assert.IsFalse (r.Read (), "#6");
}
protected void Read_CustomMarkupExtension2 (XamlReader r)
{
r.Read (); // ns
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#1");
r.Read (); // note that there wasn't another NamespaceDeclaration.
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#2-0");
var xt = r.Type;
Assert.AreEqual (r.SchemaContext.GetXamlType (typeof (MyExtension2)), xt, "#2");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "#3");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#3-2");
Assert.AreEqual (XamlLanguage.Initialization, r.Member, "#4");
Assert.IsTrue (r.Read (), "#5");
Assert.AreEqual ("MonoTests.System.Xaml.MyExtension2", r.Value, "#6");
Assert.IsTrue (r.Read (), "#7"); // EndMember
Assert.IsTrue (r.Read (), "#8"); // EndObject
Assert.IsFalse (r.Read (), "#9");
}
protected void Read_CustomMarkupExtension3 (XamlReader r)
{
r.Read (); // ns
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#1");
r.Read (); // note that there wasn't another NamespaceDeclaration.
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#2-0");
var xt = r.Type;
Assert.AreEqual (r.SchemaContext.GetXamlType (typeof (MyExtension3)), xt, "#2");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "#3");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#3-2");
Assert.AreEqual (XamlLanguage.Initialization, r.Member, "#4");
Assert.IsTrue (r.Read (), "#5");
Assert.AreEqual ("MonoTests.System.Xaml.MyExtension3", r.Value, "#6");
Assert.IsTrue (r.Read (), "#7"); // EndMember
Assert.IsTrue (r.Read (), "#8"); // EndObject
Assert.IsFalse (r.Read (), "#9");
}
protected void Read_CustomMarkupExtension4 (XamlReader r)
{
r.Read (); // ns
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#1");
r.Read (); // note that there wasn't another NamespaceDeclaration.
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#2-0");
var xt = r.Type;
Assert.AreEqual (r.SchemaContext.GetXamlType (typeof (MyExtension4)), xt, "#2");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "#3");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#3-2");
Assert.AreEqual (XamlLanguage.Initialization, r.Member, "#4");
Assert.IsTrue (r.Read (), "#5");
Assert.AreEqual ("MonoTests.System.Xaml.MyExtension4", r.Value, "#6");
Assert.IsTrue (r.Read (), "#7"); // EndMember
Assert.IsTrue (r.Read (), "#8"); // EndObject
Assert.IsFalse (r.Read (), "#9");
}
protected void Read_CustomMarkupExtension5 (XamlReader r)
{
r.Read (); // ns
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#1");
r.Read (); // note that there wasn't another NamespaceDeclaration.
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#2-0");
var xt = r.Type;
Assert.AreEqual (r.SchemaContext.GetXamlType (typeof (MyExtension5)), xt, "#2");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "#3");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#3-2");
Assert.AreEqual (XamlLanguage.PositionalParameters, r.Member, "#4");
Assert.IsTrue (r.Read (), "#5");
Assert.AreEqual ("foo", r.Value, "#6");
Assert.IsTrue (r.Read (), "#7");
Assert.AreEqual ("bar", r.Value, "#8");
Assert.IsTrue (r.Read (), "#9");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#10");
Assert.IsTrue (r.Read (), "#11");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#12");
Assert.IsFalse (r.Read (), "#13");
}
protected void Read_CustomMarkupExtension6 (XamlReader r)
{
r.Read (); // ns
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#1");
r.Read (); // note that there wasn't another NamespaceDeclaration.
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#2-0");
var xt = r.Type;
Assert.AreEqual (r.SchemaContext.GetXamlType (typeof (MyExtension6)), xt, "#2");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "#3");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#3-2");
Assert.AreEqual (xt.GetMember ("Foo"), r.Member, "#4"); // this is the difference between MyExtension5 and MyExtension6: it outputs constructor arguments as normal members
Assert.IsTrue (r.Read (), "#5");
Assert.AreEqual ("foo", r.Value, "#6");
Assert.IsTrue (r.Read (), "#7"); // EndMember
Assert.IsTrue (r.Read (), "#8"); // EndObject
Assert.IsFalse (r.Read (), "#9");
}
protected void Read_ArgumentAttributed (XamlReader r, object obj)
{
Read_CommonClrType (r, obj, new KeyValuePair<string,string> ("x", XamlLanguage.Xaml2006Namespace));
if (r is XamlXmlReader)
ReadBase (r);
var args = Read_AttributedArguments_String (r, new string [] {"arg1", "arg2"});
Assert.AreEqual ("foo", args [0], "#1");
Assert.AreEqual ("bar", args [1], "#2");
}
protected void Read_Dictionary (XamlReader r)
{
Assert.IsTrue (r.Read (), "ns#1-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#1-2");
Assert.IsNotNull (r.Namespace, "ns#1-3");
Assert.AreEqual (String.Empty, r.Namespace.Prefix, "ns#1-4");
Assert.AreEqual ("clr-namespace:System.Collections.Generic;assembly=mscorlib", r.Namespace.Namespace, "ns#1-5");
Assert.IsTrue (r.Read (), "ns#2-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#2-2");
Assert.IsNotNull (r.Namespace, "ns#2-3");
Assert.AreEqual ("x", r.Namespace.Prefix, "ns#2-4");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "ns#2-5");
Assert.IsTrue (r.Read (), "so#1-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#1-2");
var xt = new XamlType (typeof (Dictionary<string,object>), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "so#1-3");
// Assert.AreEqual (obj, r.Instance, "so#1-4");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "smitems#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "smitems#2");
Assert.AreEqual (XamlLanguage.Items, r.Member, "smitems#3");
for (int i = 0; i < 2; i++) {
// start of an item
Assert.IsTrue (r.Read (), "soi#1-1." + i);
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "soi#1-2." + i);
var xt2 = new XamlType (typeof (double), r.SchemaContext);
Assert.AreEqual (xt2, r.Type, "soi#1-3." + i);
Assert.IsTrue (r.Read (), "smi#1-1." + i);
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "smi#1-2." + i);
Assert.AreEqual (XamlLanguage.Key, r.Member, "smi#1-3." + i);
Assert.IsTrue (r.Read (), "svi#1-1." + i);
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "svi#1-2." + i);
Assert.AreEqual (i == 0 ? "Foo" : "Bar", r.Value, "svi#1-3." + i);
Assert.IsTrue (r.Read (), "emi#1-1." + i);
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "emi#1-2." + i);
Assert.IsTrue (r.Read (), "smi#2-1." + i);
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "smi#2-2." + i);
Assert.AreEqual (XamlLanguage.Initialization, r.Member, "smi#2-3." + i);
Assert.IsTrue (r.Read (), "svi#2-1." + i);
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "svi#2-2." + i);
Assert.AreEqual (i == 0 ? "5" : "-6.5", r.Value, "svi#2-3." + i); // converted to string(!)
Assert.IsTrue (r.Read (), "emi#2-1." + i);
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "emi#2-2." + i);
Assert.IsTrue (r.Read (), "eoi#1-1." + i);
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eoi#1-2." + i);
// end of an item
}
Assert.IsTrue (r.Read (), "emitems#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "emitems#2"); // XamlLanguage.Items
Assert.IsTrue (r.Read (), "eo#1-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#1-2"); // Dictionary
Assert.IsFalse (r.Read (), "end");
}
protected void Read_Dictionary2 (XamlReader r, XamlMember ctorArgMember)
{
Assert.IsTrue (r.Read (), "ns#1-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#1-2");
Assert.IsNotNull (r.Namespace, "ns#1-3");
Assert.AreEqual (String.Empty, r.Namespace.Prefix, "ns#1-4");
Assert.AreEqual ("clr-namespace:System.Collections.Generic;assembly=mscorlib", r.Namespace.Namespace, "ns#1-5");
Assert.IsTrue (r.Read (), "ns#2-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#2-2");
Assert.IsNotNull (r.Namespace, "ns#2-3");
Assert.AreEqual ("s", r.Namespace.Prefix, "ns#2-4");
Assert.AreEqual ("clr-namespace:System;assembly=mscorlib", r.Namespace.Namespace, "ns#2-5");
Assert.IsTrue (r.Read (), "ns#3-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#3-2");
Assert.IsNotNull (r.Namespace, "ns#3-3");
Assert.AreEqual ("sx", r.Namespace.Prefix, "ns#3-4");
Assert.AreEqual ("clr-namespace:System.Xaml;assembly=System.Xaml", r.Namespace.Namespace, "ns#3-5");
Assert.IsTrue (r.Read (), "ns#4-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#4-2");
Assert.IsNotNull (r.Namespace, "ns#4-3");
Assert.AreEqual ("x", r.Namespace.Prefix, "ns#4-4");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "ns#4-5");
Assert.IsTrue (r.Read (), "so#1-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#1-2");
var xt = new XamlType (typeof (Dictionary<string,Type>), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "so#1-3");
// Assert.AreEqual (obj, r.Instance, "so#1-4");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "smitems#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "smitems#2");
Assert.AreEqual (XamlLanguage.Items, r.Member, "smitems#3");
for (int i = 0; i < 2; i++) {
// start of an item
Assert.IsTrue (r.Read (), "soi#1-1." + i);
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "soi#1-2." + i);
var xt2 = XamlLanguage.Type;
Assert.AreEqual (xt2, r.Type, "soi#1-3." + i);
if (r is XamlObjectReader) {
Read_Dictionary2_ConstructorArgument (r, ctorArgMember, i);
Read_Dictionary2_Key (r, i);
} else {
Read_Dictionary2_Key (r, i);
Read_Dictionary2_ConstructorArgument (r, ctorArgMember, i);
}
Assert.IsTrue (r.Read (), "eoi#1-1." + i);
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eoi#1-2." + i);
// end of an item
}
Assert.IsTrue (r.Read (), "emitems#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "emitems#2"); // XamlLanguage.Items
Assert.IsTrue (r.Read (), "eo#1-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#1-2"); // Dictionary
Assert.IsFalse (r.Read (), "end");
}
void Read_Dictionary2_ConstructorArgument (XamlReader r, XamlMember ctorArgMember, int i)
{
Assert.IsTrue (r.Read (), "smi#1-1." + i);
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "smi#1-2." + i);
Assert.AreEqual (ctorArgMember, r.Member, "smi#1-3." + i);
Assert.IsTrue (r.Read (), "svi#1-1." + i);
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "svi#1-2." + i);
Assert.AreEqual (i == 0 ? "x:Int32" : "Dictionary(s:Type, sx:XamlType)", r.Value, "svi#1-3." + i);
Assert.IsTrue (r.Read (), "emi#1-1." + i);
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "emi#1-2." + i);
}
void Read_Dictionary2_Key (XamlReader r, int i)
{
Assert.IsTrue (r.Read (), "smi#2-1." + i);
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "smi#2-2." + i);
Assert.AreEqual (XamlLanguage.Key, r.Member, "smi#2-3." + i);
Assert.IsTrue (r.Read (), "svi#2-1." + i);
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "svi#2-2." + i);
Assert.AreEqual (i == 0 ? "Foo" : "Bar", r.Value, "svi#2-3." + i);
Assert.IsTrue (r.Read (), "emi#2-1." + i);
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "emi#2-2." + i);
}
protected void PositionalParameters1 (XamlReader r)
{
// ns1 > T:PositionalParametersClass1 > M:_PositionalParameters > foo > 5 > EM:_PositionalParameters > ET:PositionalParametersClass1
Assert.IsTrue (r.Read (), "ns#1-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#1-2");
Assert.IsNotNull (r.Namespace, "ns#1-3");
Assert.AreEqual (String.Empty, r.Namespace.Prefix, "ns#1-4");
Assert.AreEqual ("clr-namespace:MonoTests.System.Xaml;assembly=" + GetType ().Assembly.GetName ().Name, r.Namespace.Namespace, "ns#1-5");
Assert.IsTrue (r.Read (), "so#1-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#1-2");
var xt = new XamlType (typeof (PositionalParametersClass1), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "so#1-3");
// Assert.AreEqual (obj, r.Instance, "so#1-4");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "sposprm#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sposprm#2");
Assert.AreEqual (XamlLanguage.PositionalParameters, r.Member, "sposprm#3");
Assert.IsTrue (r.Read (), "sva#1-1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "sva#1-2");
Assert.AreEqual ("foo", r.Value, "sva#1-3");
Assert.IsTrue (r.Read (), "sva#2-1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "sva#2-2");
Assert.AreEqual ("5", r.Value, "sva#2-3");
Assert.IsTrue (r.Read (), "eposprm#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "eposprm#2"); // XamlLanguage.PositionalParameters
Assert.IsTrue (r.Read (), "eo#1-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#1-2");
Assert.IsFalse (r.Read (), "end");
}
protected void PositionalParameters2 (XamlReader r)
{
// ns1 > T:PositionalParametersWrapper > M:Body > T:PositionalParametersClass1 > M:_PositionalParameters > foo > 5 > EM:_PositionalParameters > ET:PositionalParametersClass1
Assert.IsTrue (r.Read (), "ns#1-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#1-2");
Assert.IsNotNull (r.Namespace, "ns#1-3");
Assert.AreEqual (String.Empty, r.Namespace.Prefix, "ns#1-4");
Assert.AreEqual ("clr-namespace:MonoTests.System.Xaml;assembly=" + GetType ().Assembly.GetName ().Name, r.Namespace.Namespace, "ns#1-5");
Assert.IsTrue (r.Read (), "so#1-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#1-2");
var xt = new XamlType (typeof (PositionalParametersWrapper), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "so#1-3");
// Assert.AreEqual (obj, r.Instance, "so#1-4");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "sm#1-1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sm#1-2");
Assert.AreEqual (xt.GetMember ("Body"), r.Member, "sm#1-3");
xt = new XamlType (typeof (PositionalParametersClass1), r.SchemaContext);
Assert.IsTrue (r.Read (), "so#2-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#2-2");
Assert.AreEqual (xt, r.Type, "so#2-3");
// Assert.AreEqual (obj.Body, r.Instance, "so#2-4");
Assert.IsTrue (r.Read (), "sposprm#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sposprm#2");
Assert.AreEqual (XamlLanguage.PositionalParameters, r.Member, "sposprm#3");
Assert.IsTrue (r.Read (), "sva#1-1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "sva#1-2");
Assert.AreEqual ("foo", r.Value, "sva#1-3");
Assert.IsTrue (r.Read (), "sva#2-1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "sva#2-2");
Assert.AreEqual ("5", r.Value, "sva#2-3");
Assert.IsTrue (r.Read (), "eposprm#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "eposprm#2"); // XamlLanguage.PositionalParameters
Assert.IsTrue (r.Read (), "eo#2-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#2-2");
Assert.IsTrue (r.Read (), "em#1-1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "eo#1-2");
Assert.IsTrue (r.Read (), "eo#1-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#1-2");
Assert.IsFalse (r.Read (), "end");
}
protected void ComplexPositionalParameters (XamlReader r)
{
Assert.IsTrue (r.Read (), "ns#1-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#1-2");
Assert.IsNotNull (r.Namespace, "ns#1-3");
Assert.AreEqual (String.Empty, r.Namespace.Prefix, "ns#1-4");
Assert.AreEqual ("clr-namespace:MonoTests.System.Xaml;assembly=" + GetType ().Assembly.GetName ().Name, r.Namespace.Namespace, "ns#1-5");
Assert.IsTrue (r.Read (), "ns#2-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#2-2");
Assert.IsNotNull (r.Namespace, "ns#2-3");
Assert.AreEqual ("x", r.Namespace.Prefix, "ns#2-4");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "ns#2-5");
Assert.IsTrue (r.Read (), "so#1-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#1-2");
var xt = new XamlType (typeof (ComplexPositionalParameterWrapper), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "so#1-3");
// Assert.AreEqual (obj, r.Instance, "so#1-4");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "sm#1-1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sm#1-2");
Assert.AreEqual (xt.GetMember ("Param"), r.Member, "sm#1-3");
xt = r.SchemaContext.GetXamlType (typeof (ComplexPositionalParameterClass));
Assert.IsTrue (r.Read (), "so#2-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#2-2");
Assert.AreEqual (xt, r.Type, "so#2-3");
// Assert.AreEqual (obj.Param, r.Instance, "so#2-4");
Assert.IsTrue (r.Read (), "sarg#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sarg#2");
Assert.AreEqual (XamlLanguage.Arguments, r.Member, "sarg#3");
Assert.IsTrue (r.Read (), "so#3-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#3-2");
xt = r.SchemaContext.GetXamlType (typeof (ComplexPositionalParameterValue));
Assert.AreEqual (xt, r.Type, "so#3-3");
Assert.IsTrue (r.Read (), "sm#3-1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sm#3-2");
Assert.AreEqual (xt.GetMember ("Foo"), r.Member, "sm#3-3");
Assert.IsTrue (r.Read (), "v#3-1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "v#3-2");
Assert.AreEqual ("foo", r.Value, "v#3-3");
Assert.IsTrue (r.Read (), "em#3-1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "em#3-2");
Assert.IsTrue (r.Read (), "eo#3-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#3-2");
Assert.IsTrue (r.Read (), "earg#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "earg#2"); // XamlLanguage.Arguments
Assert.IsTrue (r.Read (), "eo#2-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#2-2");
Assert.IsTrue (r.Read (), "em#1-1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "eo#1-2");
Assert.IsTrue (r.Read (), "eo#1-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#1-2");
Assert.IsFalse (r.Read (), "end");
}
protected void Read_ListWrapper (XamlReader r)
{
Assert.IsTrue (r.Read (), "#1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#2");
Assert.IsNotNull (r.Namespace, "#3");
Assert.AreEqual (String.Empty, r.Namespace.Prefix, "#3-2");
Assert.IsTrue (r.Read (), "#11");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
Assert.IsNotNull (r.Namespace, "#13");
Assert.AreEqual ("x", r.Namespace.Prefix, "#13-2");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#13-3");
Assert.IsTrue (r.Read (), "#21");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#22");
var xt = new XamlType (typeof (ListWrapper), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "#23");
// Assert.AreEqual (obj, r.Instance, "#26");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "#61");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#62");
Assert.AreEqual (xt.GetMember ("Items"), r.Member, "#63");
Assert.IsTrue (r.Read (), "#71");
Assert.AreEqual (XamlNodeType.GetObject, r.NodeType, "#71-2");
Assert.IsNull (r.Type, "#71-3");
Assert.IsNull (r.Member, "#71-4");
Assert.IsNull (r.Value, "#71-5");
Assert.IsTrue (r.Read (), "#72");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#72-2");
Assert.AreEqual (XamlLanguage.Items, r.Member, "#72-3");
string [] values = {"5", "-3", "0"};
for (int i = 0; i < 3; i++) {
Assert.IsTrue (r.Read (), i + "#73");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, i + "#73-2");
Assert.IsTrue (r.Read (), i + "#74");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, i + "#74-2");
Assert.AreEqual (XamlLanguage.Initialization, r.Member, i + "#74-3");
Assert.IsTrue (r.Read (), i + "#75");
Assert.IsNotNull (r.Value, i + "#75-2");
Assert.AreEqual (values [i], r.Value, i + "#73-3");
Assert.IsTrue (r.Read (), i + "#74");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, i + "#74-2");
Assert.IsTrue (r.Read (), i + "#75");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, i + "#75-2");
}
Assert.IsTrue (r.Read (), "#81");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#82"); // XamlLanguage.Items
Assert.IsTrue (r.Read (), "#83");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#84"); // GetObject
Assert.IsTrue (r.Read (), "#85");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#86"); // ListWrapper.Items
Assert.IsTrue (r.Read (), "#87");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#88"); // ListWrapper
Assert.IsFalse (r.Read (), "#89");
}
protected void Read_ListWrapper2 (XamlReader r)
{
Assert.IsTrue (r.Read (), "#1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#2");
Assert.IsNotNull (r.Namespace, "#3");
Assert.AreEqual (String.Empty, r.Namespace.Prefix, "#3-2");
Assert.IsTrue (r.Read (), "#6");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#7");
Assert.IsNotNull (r.Namespace, "#8");
Assert.AreEqual ("scg", r.Namespace.Prefix, "#8-2");
Assert.AreEqual ("clr-namespace:System.Collections.Generic;assembly=mscorlib", r.Namespace.Namespace, "#8-3");
Assert.IsTrue (r.Read (), "#11");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
Assert.IsNotNull (r.Namespace, "#13");
Assert.AreEqual ("x", r.Namespace.Prefix, "#13-2");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#13-3");
Assert.IsTrue (r.Read (), "#21");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#22");
var xt = new XamlType (typeof (ListWrapper2), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "#23");
// Assert.AreEqual (obj, r.Instance, "#26");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "#61");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#62");
Assert.AreEqual (xt.GetMember ("Items"), r.Member, "#63");
Assert.IsTrue (r.Read (), "#71");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#71-2");
xt = r.SchemaContext.GetXamlType (typeof (List<int>));
Assert.AreEqual (xt, r.Type, "#71-3");
Assert.IsNull (r.Member, "#71-4");
Assert.IsNull (r.Value, "#71-5");
// Capacity
Assert.IsTrue (r.Read (), "#31");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#32");
Assert.AreEqual (xt.GetMember ("Capacity"), r.Member, "#33");
Assert.IsTrue (r.Read (), "#41");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#42");
// The value is implementation details, not testable.
//Assert.AreEqual ("3", r.Value, "#43");
Assert.IsTrue (r.Read (), "#51");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#52");
// Items
Assert.IsTrue (r.Read (), "#72");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#72-2");
Assert.AreEqual (XamlLanguage.Items, r.Member, "#72-3");
string [] values = {"5", "-3", "0"};
for (int i = 0; i < 3; i++) {
Assert.IsTrue (r.Read (), i + "#73");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, i + "#73-2");
Assert.IsTrue (r.Read (), i + "#74");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, i + "#74-2");
Assert.AreEqual (XamlLanguage.Initialization, r.Member, i + "#74-3");
Assert.IsTrue (r.Read (), i + "#75");
Assert.IsNotNull (r.Value, i + "#75-2");
Assert.AreEqual (values [i], r.Value, i + "#73-3");
Assert.IsTrue (r.Read (), i + "#74");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, i + "#74-2");
Assert.IsTrue (r.Read (), i + "#75");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, i + "#75-2");
}
Assert.IsTrue (r.Read (), "#81");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#82"); // XamlLanguage.Items
Assert.IsTrue (r.Read (), "#83");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#84"); // StartObject(of List<int>)
Assert.IsTrue (r.Read (), "#85");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#86"); // ListWrapper.Items
Assert.IsTrue (r.Read (), "#87");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#88"); // ListWrapper
Assert.IsFalse (r.Read (), "#89");
}
protected void Read_ContentIncluded (XamlReader r)
{
Assert.IsTrue (r.Read (), "ns#1-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#1-2");
Assert.IsNotNull (r.Namespace, "ns#1-3");
Assert.AreEqual (String.Empty, r.Namespace.Prefix, "ns#1-4");
Assert.AreEqual ("clr-namespace:MonoTests.System.Xaml;assembly=" + GetType ().Assembly.GetName ().Name, r.Namespace.Namespace, "ns#1-5");
Assert.IsTrue (r.Read (), "so#1-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#1-2");
var xt = new XamlType (typeof (ContentIncludedClass), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "so#1-3");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "sposprm#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sposprm#2");
Assert.AreEqual (xt.GetMember ("Content"), r.Member, "sposprm#3");
Assert.IsTrue (r.Read (), "sva#1-1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "sva#1-2");
Assert.AreEqual ("foo", r.Value, "sva#1-3");
Assert.IsTrue (r.Read (), "eposprm#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "eposprm#2");
Assert.IsTrue (r.Read (), "eo#1-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#1-2");
Assert.IsFalse (r.Read (), "end");
}
protected void Read_PropertyDefinition (XamlReader r)
{
Assert.IsTrue (r.Read (), "ns#1-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#1-2");
Assert.IsNotNull (r.Namespace, "ns#1-3");
Assert.AreEqual ("x", r.Namespace.Prefix, "ns#1-4");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "ns#1-5");
Assert.IsTrue (r.Read (), "so#1-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#1-2");
var xt = new XamlType (typeof (PropertyDefinition), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "so#1-3");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "smod#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "smod#2");
Assert.AreEqual (xt.GetMember ("Modifier"), r.Member, "smod#3");
Assert.IsTrue (r.Read (), "vmod#1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vmod#2");
Assert.AreEqual ("protected", r.Value, "vmod#3");
Assert.IsTrue (r.Read (), "emod#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "emod#2");
Assert.IsTrue (r.Read (), "sname#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sname#2");
Assert.AreEqual (xt.GetMember ("Name"), r.Member, "sname#3");
Assert.IsTrue (r.Read (), "vname#1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vname#2");
Assert.AreEqual ("foo", r.Value, "vname#3");
Assert.IsTrue (r.Read (), "ename#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "ename#2");
Assert.IsTrue (r.Read (), "stype#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "stype#2");
Assert.AreEqual (xt.GetMember ("Type"), r.Member, "stype#3");
Assert.IsTrue (r.Read (), "vtype#1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vtype#2");
Assert.AreEqual ("x:String", r.Value, "vtype#3");
Assert.IsTrue (r.Read (), "etype#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "etype#2");
Assert.IsTrue (r.Read (), "eo#1-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#1-2");
Assert.IsFalse (r.Read (), "end");
}
protected void Read_StaticExtensionWrapper (XamlReader r)
{
Assert.IsTrue (r.Read (), "ns#1-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#1-2");
Assert.IsNotNull (r.Namespace, "ns#1-3");
Assert.AreEqual ("", r.Namespace.Prefix, "ns#1-4");
Assert.AreEqual ("clr-namespace:MonoTests.System.Xaml;assembly=" + GetType ().Assembly.GetName ().Name, r.Namespace.Namespace, "ns#1-5");
Assert.IsTrue (r.Read (), "ns#2-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#2-2");
Assert.IsNotNull (r.Namespace, "ns#2-3");
Assert.AreEqual ("x", r.Namespace.Prefix, "ns#2-4");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "ns#2-5");
Assert.IsTrue (r.Read (), "so#1-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#1-2");
var xt = new XamlType (typeof (StaticExtensionWrapper), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "so#1-3");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "sprm#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sprm#2");
Assert.AreEqual (xt.GetMember ("Param"), r.Member, "sprm#3");
Assert.IsTrue (r.Read (), "so#2-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#2-2");
xt = new XamlType (typeof (StaticExtension), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "so#2-3");
Assert.IsTrue (r.Read (), "smbr#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "smbr#2");
Assert.AreEqual (XamlLanguage.PositionalParameters, r.Member, "smbr#3");
Assert.IsTrue (r.Read (), "vmbr#1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vmbr#2");
Assert.AreEqual ("StaticExtensionWrapper.Foo", r.Value, "vmbr#3");
Assert.IsTrue (r.Read (), "embr#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "embr#2");
Assert.IsTrue (r.Read (), "eo#2-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#2-2");
Assert.IsTrue (r.Read (), "emod#1-1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "emod#1-2");
Assert.IsTrue (r.Read (), "eo#1-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#1-2");
Assert.IsFalse (r.Read (), "end");
}
protected void Read_TypeExtensionWrapper (XamlReader r)
{
Assert.IsTrue (r.Read (), "ns#1-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#1-2");
Assert.IsNotNull (r.Namespace, "ns#1-3");
Assert.AreEqual ("", r.Namespace.Prefix, "ns#1-4");
Assert.AreEqual ("clr-namespace:MonoTests.System.Xaml;assembly=" + GetType ().Assembly.GetName ().Name, r.Namespace.Namespace, "ns#1-5");
Assert.IsTrue (r.Read (), "ns#2-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#2-2");
Assert.IsNotNull (r.Namespace, "ns#2-3");
Assert.AreEqual ("x", r.Namespace.Prefix, "ns#2-4");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "ns#2-5");
Assert.IsTrue (r.Read (), "so#1-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#1-2");
var xt = new XamlType (typeof (TypeExtensionWrapper), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "so#1-3");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "sprm#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sprm#2");
Assert.AreEqual (xt.GetMember ("Param"), r.Member, "sprm#3");
Assert.IsTrue (r.Read (), "so#2-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#2-2");
xt = new XamlType (typeof (TypeExtension), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "so#2-3");
Assert.IsTrue (r.Read (), "smbr#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "smbr#2");
Assert.AreEqual (XamlLanguage.PositionalParameters, r.Member, "smbr#3");
Assert.IsTrue (r.Read (), "vmbr#1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vmbr#2");
Assert.AreEqual (String.Empty, r.Value, "vmbr#3");
Assert.IsTrue (r.Read (), "embr#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "embr#2");
Assert.IsTrue (r.Read (), "eo#2-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#2-2");
Assert.IsTrue (r.Read (), "emod#1-1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "emod#1-2");
Assert.IsTrue (r.Read (), "eo#1-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#1-2");
Assert.IsFalse (r.Read (), "end");
}
protected void Read_EventContainer (XamlReader r)
{
Assert.IsTrue (r.Read (), "ns#1-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#1-2");
Assert.IsNotNull (r.Namespace, "ns#1-3");
Assert.AreEqual ("", r.Namespace.Prefix, "ns#1-4");
Assert.AreEqual ("clr-namespace:MonoTests.System.Xaml;assembly=" + GetType ().Assembly.GetName ().Name, r.Namespace.Namespace, "ns#1-5");
Assert.IsTrue (r.Read (), "so#1-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#1-2");
var xt = new XamlType (typeof (EventContainer), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "so#1-3");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "eo#1-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#1-2");
Assert.IsFalse (r.Read (), "end");
}
protected void Read_NamedItems (XamlReader r, bool isObjectReader)
{
Assert.IsTrue (r.Read (), "ns#1-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#1-2");
Assert.IsNotNull (r.Namespace, "ns#1-3");
Assert.AreEqual ("", r.Namespace.Prefix, "ns#1-4");
Assert.AreEqual ("clr-namespace:MonoTests.System.Xaml;assembly=" + GetType ().Assembly.GetName ().Name, r.Namespace.Namespace, "ns#1-5");
Assert.IsTrue (r.Read (), "ns#2-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#2-2");
Assert.IsNotNull (r.Namespace, "ns#2-3");
Assert.AreEqual ("x", r.Namespace.Prefix, "ns#2-4");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "ns#2-5");
var xt = new XamlType (typeof (NamedItem), r.SchemaContext);
// foo
Assert.IsTrue (r.Read (), "so#1-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#1-2");
Assert.AreEqual (xt, r.Type, "so#1-3");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "sxname#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sxname#2");
Assert.AreEqual (XamlLanguage.Name, r.Member, "sxname#3");
Assert.IsTrue (r.Read (), "vxname#1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vxname#2");
Assert.AreEqual ("__ReferenceID0", r.Value, "vxname#3");
Assert.IsTrue (r.Read (), "exname#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "exname#2");
Assert.IsTrue (r.Read (), "sname#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sname#2");
Assert.AreEqual (xt.GetMember ("ItemName"), r.Member, "sname#3");
Assert.IsTrue (r.Read (), "vname#1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vname#2");
Assert.AreEqual ("foo", r.Value, "vname#3");
Assert.IsTrue (r.Read (), "ename#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "ename#2");
Assert.IsTrue (r.Read (), "sItems#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sItems#2");
Assert.AreEqual (xt.GetMember ("References"), r.Member, "sItems#3");
Assert.IsTrue (r.Read (), "goc#1-1");
Assert.AreEqual (XamlNodeType.GetObject, r.NodeType, "goc#1-2");
Assert.IsTrue (r.Read (), "smbr#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "smbr#2");
Assert.AreEqual (XamlLanguage.Items, r.Member, "smbr#3");
// bar
Assert.IsTrue (r.Read (), "soc#1-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "soc#1-2");
Assert.AreEqual (xt, r.Type, "soc#1-3");
Assert.IsTrue (r.Read (), "smbrc#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "smbrc#2");
Assert.AreEqual (xt.GetMember ("ItemName"), r.Member, "smbrc#3");
Assert.IsTrue (r.Read (), "vmbrc#1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vmbrc#2");
Assert.AreEqual ("bar", r.Value, "vmbrc#3");
Assert.IsTrue (r.Read (), "embrc#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "embrc#2");
Assert.IsTrue (r.Read (), "sItemsc#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sItemsc#2");
Assert.AreEqual (xt.GetMember ("References"), r.Member, "sItemsc#3");
Assert.IsTrue (r.Read (), "god#2-1");
Assert.AreEqual (XamlNodeType.GetObject, r.NodeType, "god#2-2");
Assert.IsTrue (r.Read (), "smbrd#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "smbrd#2");
Assert.AreEqual (XamlLanguage.Items, r.Member, "smbrd#3");
Assert.IsTrue (r.Read (), "sod#1-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "sod#1-2");
Assert.AreEqual (XamlLanguage.Reference, r.Type, "sod#1-3");
Assert.IsTrue (r.Read (), "smbrd#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "smbrd#2");
if (isObjectReader)
Assert.AreEqual (XamlLanguage.PositionalParameters, r.Member, "smbrd#3");
else
Assert.AreEqual (XamlLanguage.Reference.GetMember ("Name"), r.Member, "smbrd#3");
Assert.IsTrue (r.Read (), "vmbrd#1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vmbrd#2");
Assert.AreEqual ("__ReferenceID0", r.Value, "vmbrd#3");
Assert.IsTrue (r.Read (), "embrd#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "embrd#2");
Assert.IsTrue (r.Read (), "eod#2-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eod#2-2");
Assert.IsTrue (r.Read (), "eItemsc#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "eItemsc#2");
Assert.IsTrue (r.Read (), "eoc#2-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eoc#2-2");
Assert.IsTrue (r.Read (), "emod#1-1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "emod#1-2");
Assert.IsTrue (r.Read (), "eo#1-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#1-2");
// baz
Assert.IsTrue (r.Read (), "so3#1-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so3#1-2");
Assert.AreEqual (xt, r.Type, "so3#1-3");
Assert.IsTrue (r.Read (), "sname3#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sname3#2");
Assert.AreEqual (xt.GetMember ("ItemName"), r.Member, "sname3#3");
Assert.IsTrue (r.Read (), "vname3#1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vname3#2");
Assert.AreEqual ("baz", r.Value, "vname3#3");
Assert.IsTrue (r.Read (), "ename3#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "ename3#2");
Assert.IsTrue (r.Read (), "eo3#1-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo3#1-2");
Assert.IsTrue (r.Read (), "em2#1-1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "em2#1-2");
Assert.IsTrue (r.Read (), "eo2#1-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo2#1-2");
Assert.IsTrue (r.Read (), "em#1-1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "em#1-2");
Assert.IsTrue (r.Read (), "eo#1-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#1-2");
Assert.IsFalse (r.Read (), "end");
}
protected void Read_NamedItems2 (XamlReader r, bool isObjectReader)
{
Assert.IsTrue (r.Read (), "ns#1-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#1-2");
Assert.IsNotNull (r.Namespace, "ns#1-3");
Assert.AreEqual ("", r.Namespace.Prefix, "ns#1-4");
Assert.AreEqual ("clr-namespace:MonoTests.System.Xaml;assembly=" + GetType ().Assembly.GetName ().Name, r.Namespace.Namespace, "ns#1-5");
Assert.IsTrue (r.Read (), "ns#2-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#2-2");
Assert.IsNotNull (r.Namespace, "ns#2-3");
Assert.AreEqual ("x", r.Namespace.Prefix, "ns#2-4");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "ns#2-5");
var xt = new XamlType (typeof (NamedItem2), r.SchemaContext);
// i1
Assert.IsTrue (r.Read (), "so1#1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so1#2");
Assert.AreEqual (xt, r.Type, "so1#3");
if (r is XamlXmlReader)
ReadBase (r);
Assert.IsTrue (r.Read (), "sm1#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sm1#2");
Assert.AreEqual (xt.GetMember ("ItemName"), r.Member, "sm1#3");
Assert.IsTrue (r.Read (), "v1#1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "v1#2");
Assert.AreEqual ("i1", r.Value, "v1#3");
Assert.IsTrue (r.Read (), "em1#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "em1#2");
Assert.IsTrue (r.Read (), "srefs1#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "srefs1#2");
Assert.AreEqual (xt.GetMember ("References"), r.Member, "srefs1#3");
Assert.IsTrue (r.Read (), "go1#1");
Assert.AreEqual (XamlNodeType.GetObject, r.NodeType, "go1#2");
Assert.IsTrue (r.Read (), "sitems1#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sitems1#2");
Assert.AreEqual (XamlLanguage.Items, r.Member, "sitems1#3");
// i2
Assert.IsTrue (r.Read (), "so2#1-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so2#1-2");
Assert.AreEqual (xt, r.Type, "so2#1-3");
Assert.IsTrue (r.Read (), "sm2#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sm2#2");
Assert.AreEqual (xt.GetMember ("ItemName"), r.Member, "sm2#3");
Assert.IsTrue (r.Read (), "v2#1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "v2#2");
Assert.AreEqual ("i2", r.Value, "v2#3");
Assert.IsTrue (r.Read (), "em2#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "em2#2");
Assert.IsTrue (r.Read (), "srefs2#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "srefs2#2");
Assert.AreEqual (xt.GetMember ("References"), r.Member, "srefs2#3");
Assert.IsTrue (r.Read (), "go2#1");
Assert.AreEqual (XamlNodeType.GetObject, r.NodeType, "go2#2");
Assert.IsTrue (r.Read (), "sItems1#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sItems1#2");
Assert.AreEqual (XamlLanguage.Items, r.Member, "sItems1#3");
Assert.IsTrue (r.Read (), "so3#1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so3#2");
Assert.AreEqual (xt, r.Type, "so3#3");
Assert.IsTrue (r.Read (), "sm3#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sm3#2");
Assert.AreEqual (xt.GetMember ("ItemName"), r.Member, "sm3#3");
Assert.IsTrue (r.Read (), "v3#1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "v3#2");
Assert.AreEqual ("i3", r.Value, "v3#3");
Assert.IsTrue (r.Read (), "em3#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "em3#2");
Assert.IsTrue (r.Read (), "eo3#1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo3#2");
Assert.IsTrue (r.Read (), "eitems2#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "eitems2#2");
Assert.IsTrue (r.Read (), "ego2#1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "ego2#2");
Assert.IsTrue (r.Read (), "erefs2#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "erefs2#2");
Assert.IsTrue (r.Read (), "eo2#1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo2#2");
// i4
Assert.IsTrue (r.Read (), "so4#1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so4#2");
Assert.AreEqual (xt, r.Type, "so4#3");
Assert.IsTrue (r.Read (), "sm4#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sm4#2");
Assert.AreEqual (xt.GetMember ("ItemName"), r.Member, "sm4#3");
Assert.IsTrue (r.Read (), "v4#1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "v4#2");
Assert.AreEqual ("i4", r.Value, "v4#3");
Assert.IsTrue (r.Read (), "em4#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "em4#2");
Assert.IsTrue (r.Read (), "srefs4#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "srefs4#2");
Assert.AreEqual (xt.GetMember ("References"), r.Member, "srefs4#3");
Assert.IsTrue (r.Read (), "go4#1");
Assert.AreEqual (XamlNodeType.GetObject, r.NodeType, "go4#2");
Assert.IsTrue (r.Read (), "sitems4#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sitems4#2");
Assert.AreEqual (XamlLanguage.Items, r.Member, "sitems4#3");
Assert.IsTrue (r.Read (), "sor1#1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "sor1#2");
Assert.AreEqual (XamlLanguage.Reference, r.Type, "sor1#3");
Assert.IsTrue (r.Read (), "smr1#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "smr1#2");
if (isObjectReader)
Assert.AreEqual (XamlLanguage.PositionalParameters, r.Member, "smr1#3");
else
Assert.AreEqual (XamlLanguage.Reference.GetMember ("Name"), r.Member, "smr1#3");
Assert.IsTrue (r.Read (), "vr1#1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vr1#2");
Assert.AreEqual ("i3", r.Value, "vr1#3");
Assert.IsTrue (r.Read (), "emr1#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "emr1#2");
Assert.IsTrue (r.Read (), "eor#1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eor#2");
Assert.IsTrue (r.Read (), "eitems4#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "eitems4#2");
Assert.IsTrue (r.Read (), "ego4#1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "ego4#2");
Assert.IsTrue (r.Read (), "erefs4#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "erefs4#2");
Assert.IsTrue (r.Read (), "eo4#1-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo4#1-2");
Assert.IsTrue (r.Read (), "eitems1#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "eitems1#2");
Assert.IsTrue (r.Read (), "ego1#1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "ego1#2");
Assert.IsTrue (r.Read (), "erefs1#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "erefs1#2");
Assert.IsTrue (r.Read (), "eo1#1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo1#2");
Assert.IsFalse (r.Read (), "end");
}
protected void Read_XmlSerializableWrapper (XamlReader r, bool isObjectReader)
{
Assert.IsTrue (r.Read (), "ns#1-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#1-2");
Assert.IsNotNull (r.Namespace, "ns#1-3");
Assert.AreEqual ("", r.Namespace.Prefix, "ns#1-4");
var assns = "clr-namespace:MonoTests.System.Xaml;assembly=" + GetType ().Assembly.GetName ().Name;
Assert.AreEqual (assns, r.Namespace.Namespace, "ns#1-5");
Assert.IsTrue (r.Read (), "ns#2-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#2-2");
Assert.IsNotNull (r.Namespace, "ns#2-3");
Assert.AreEqual ("x", r.Namespace.Prefix, "ns#2-4");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "ns#2-5");
// t:XmlSerializableWrapper
Assert.IsTrue (r.Read (), "so#1-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#1-2");
var xt = new XamlType (typeof (XmlSerializableWrapper), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "so#1-3");
if (r is XamlXmlReader)
ReadBase (r);
// m:Value
Assert.IsTrue (r.Read (), "sm1#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sm1#2");
Assert.AreEqual (xt.GetMember ("Value"), r.Member, "sm1#3");
// x:XData
Assert.IsTrue (r.Read (), "so#2-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#2-2");
Assert.AreEqual (XamlLanguage.XData, r.Type, "so#2-3");
if (r is XamlObjectReader)
Assert.IsNull (((XamlObjectReader) r).Instance, "xdata-instance");
Assert.IsTrue (r.Read (), "sm2#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sm2#2");
Assert.AreEqual (XamlLanguage.XData.GetMember ("Text"), r.Member, "sm2#3");
Assert.IsTrue (r.Read (), "v1#1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "v1#2");
var val = isObjectReader ? "<root />" : "<root xmlns=\"" + assns + "\" />";
Assert.AreEqual (val, r.Value, "v1#3");
Assert.IsTrue (r.Read (), "em2#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "em2#2");
Assert.IsTrue (r.Read (), "eo#2-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#2-2");
Assert.IsTrue (r.Read (), "em1#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "em1#2");
// /t:XmlSerializableWrapper
Assert.IsTrue (r.Read (), "eo#1-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#1-2");
Assert.IsFalse (r.Read (), "end");
}
protected void Read_XmlSerializable (XamlReader r)
{
Assert.IsTrue (r.Read (), "ns#1-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#1-2");
Assert.IsNotNull (r.Namespace, "ns#1-3");
Assert.AreEqual ("", r.Namespace.Prefix, "ns#1-4");
var assns = "clr-namespace:MonoTests.System.Xaml;assembly=" + GetType ().Assembly.GetName ().Name;
Assert.AreEqual (assns, r.Namespace.Namespace, "ns#1-5");
// t:XmlSerializable
Assert.IsTrue (r.Read (), "so#1-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#1-2");
var xt = new XamlType (typeof (XmlSerializable), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "so#1-3");
if (r is XamlXmlReader)
ReadBase (r);
// /t:XmlSerializable
Assert.IsTrue (r.Read (), "eo#1-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#1-2");
Assert.IsFalse (r.Read (), "end");
}
protected void Read_ListXmlSerializable (XamlReader r)
{
while (true) {
r.Read ();
if (r.Member == XamlLanguage.Items)
break;
if (r.IsEof)
Assert.Fail ("Items did not appear");
}
// t:XmlSerializable (yes...it is not XData!)
Assert.IsTrue (r.Read (), "so#1-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#1-2");
var xt = new XamlType (typeof (XmlSerializable), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "so#1-3");
// /t:XmlSerializable
Assert.IsTrue (r.Read (), "eo#1-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#1-2");
r.Close ();
}
protected void Read_AttachedProperty (XamlReader r)
{
var at = new XamlType (typeof (Attachable), r.SchemaContext);
Assert.IsTrue (r.Read (), "ns#1-1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#1-2");
Assert.IsNotNull (r.Namespace, "ns#1-3");
Assert.AreEqual ("", r.Namespace.Prefix, "ns#1-4");
var assns = "clr-namespace:MonoTests.System.Xaml;assembly=" + GetType ().Assembly.GetName ().Name;
Assert.AreEqual (assns, r.Namespace.Namespace, "ns#1-5");
// t:AttachedWrapper
Assert.IsTrue (r.Read (), "so#1-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#1-2");
var xt = new XamlType (typeof (AttachedWrapper), r.SchemaContext);
Assert.AreEqual (xt, r.Type, "so#1-3");
if (r is XamlXmlReader)
ReadBase (r);
ReadAttachedProperty (r, at.GetAttachableMember ("Foo"), "x", "x");
// m:Value
Assert.IsTrue (r.Read (), "sm#2-1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#sm#2-2");
Assert.AreEqual (xt.GetMember ("Value"), r.Member, "sm#2-3");
// t:Attached
Assert.IsTrue (r.Read (), "so#2-1");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#so#2-2");
Assert.AreEqual (r.SchemaContext.GetXamlType (typeof (Attached)), r.Type, "so#2-3");
ReadAttachedProperty (r, at.GetAttachableMember ("Foo"), "y", "y");
Assert.IsTrue (r.Read (), "eo#2-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#eo#2-2");
// /m:Value
Assert.IsTrue (r.Read (), "em#2-1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#em#2-2");
// /t:AttachedWrapper
Assert.IsTrue (r.Read (), "eo#1-1");
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#1-2");
Assert.IsFalse (r.Read (), "end");
}
void ReadAttachedProperty (XamlReader r, XamlMember xm, string value, string label)
{
Assert.IsTrue (r.Read (), label + "#1-1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, label + "#1-2");
Assert.AreEqual (xm, r.Member, label + "#1-3");
Assert.IsTrue (r.Read (), label + "#2-1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, label + "#2-2");
Assert.AreEqual (value, r.Value, label + "2-3");
Assert.IsTrue (r.Read (), label + "#3-1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, label + "#3-2");
}
protected void Read_CommonXamlPrimitive (object obj)
{
var r = new XamlObjectReader (obj);
Read_CommonXamlType (r);
Read_Initialization (r, obj);
}
// from StartMember of Initialization to EndMember
protected string Read_Initialization (XamlReader r, object comparableValue)
{
Assert.IsTrue (r.Read (), "init#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "init#2");
Assert.IsNotNull (r.Member, "init#3");
Assert.AreEqual (XamlLanguage.Initialization, r.Member, "init#3-2");
Assert.IsTrue (r.Read (), "init#4");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "init#5");
Assert.AreEqual (typeof (string), r.Value.GetType (), "init#6");
string ret = (string) r.Value;
if (comparableValue != null)
Assert.AreEqual (comparableValue.ToString (), r.Value, "init#6-2");
Assert.IsTrue (r.Read (), "init#7");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "init#8");
return ret;
}
protected object [] Read_AttributedArguments_String (XamlReader r, string [] argNames) // valid only for string arguments.
{
object [] ret = new object [argNames.Length];
Assert.IsTrue (r.Read (), "attarg.Arguments.Start1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "attarg.Arguments.Start2");
Assert.IsNotNull (r.Member, "attarg.Arguments.Start3");
Assert.AreEqual (XamlLanguage.Arguments, r.Member, "attarg.Arguments.Start4");
for (int i = 0; i < argNames.Length; i++) {
string arg = argNames [i];
Assert.IsTrue (r.Read (), "attarg.ArgStartObject1." + arg);
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "attarg.ArgStartObject2." + arg);
Assert.AreEqual (typeof (string), r.Type.UnderlyingType, "attarg.ArgStartObject3." + arg);
Assert.IsTrue (r.Read (), "attarg.ArgStartMember1." + arg);
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "attarg.ArgStartMember2." + arg);
Assert.AreEqual (XamlLanguage.Initialization, r.Member, "attarg.ArgStartMember3." + arg); // (as the argument is string here by definition)
Assert.IsTrue (r.Read (), "attarg.ArgValue1." + arg);
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "attarg.ArgValue2." + arg);
Assert.AreEqual (typeof (string), r.Value.GetType (), "attarg.ArgValue3." + arg);
ret [i] = r.Value;
Assert.IsTrue (r.Read (), "attarg.ArgEndMember1." + arg);
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "attarg.ArgEndMember2." + arg);
Assert.IsTrue (r.Read (), "attarg.ArgEndObject1." + arg);
Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "attarg.ArgEndObject2." + arg);
}
Assert.IsTrue (r.Read (), "attarg.Arguments.End1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "attarg.Arguments.End2");
return ret;
}
// from initial to StartObject
protected void Read_CommonXamlType (XamlObjectReader r)
{
Read_CommonXamlType (r, delegate {
Assert.IsNull (r.Instance, "ct#4");
});
}
protected void Read_CommonXamlType (XamlReader r, Action validateInstance)
{
Assert.IsTrue (r.Read (), "ct#1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ct#2");
Assert.IsNotNull (r.Namespace, "ct#3");
Assert.AreEqual ("x", r.Namespace.Prefix, "ct#3-2");
Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "ct#3-3");
if (validateInstance != null)
validateInstance ();
Assert.IsTrue (r.Read (), "ct#5");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "ct#6");
}
// from initial to StartObject
protected void Read_CommonClrType (XamlReader r, object obj, params KeyValuePair<string,string> [] additionalNamespaces)
{
Assert.IsTrue (r.Read (), "ct#1");
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ct#2");
Assert.IsNotNull (r.Namespace, "ct#3");
Assert.AreEqual (String.Empty, r.Namespace.Prefix, "ct#3-2");
Assert.AreEqual ("clr-namespace:" + obj.GetType ().Namespace + ";assembly=" + obj.GetType ().Assembly.GetName ().Name, r.Namespace.Namespace, "ct#3-3");
foreach (var kvp in additionalNamespaces) {
Assert.IsTrue (r.Read (), "ct#4." + kvp.Key);
Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ct#5." + kvp.Key);
Assert.IsNotNull (r.Namespace, "ct#6." + kvp.Key);
Assert.AreEqual (kvp.Key, r.Namespace.Prefix, "ct#6-2." + kvp.Key);
Assert.AreEqual (kvp.Value, r.Namespace.Namespace, "ct#6-3." + kvp.Key);
}
Assert.IsTrue (r.Read (), "ct#7");
Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "ct#8");
}
protected void ReadBase (XamlReader r)
{
Assert.IsTrue (r.Read (), "sbase#1");
Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sbase#2");
Assert.AreEqual (XamlLanguage.Base, r.Member, "sbase#3");
Assert.IsTrue (r.Read (), "vbase#1");
Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vbase#2");
Assert.IsTrue (r.Value is string, "vbase#3");
Assert.IsTrue (r.Read (), "ebase#1");
Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "ebase#2");
}
}
}
| 40.119379 | 176 | 0.653243 | [
"Apache-2.0"
] | dvmarshall/mono | mcs/class/System.Xaml/Test/System.Xaml/XamlReaderTestBase.cs | 98,132 | 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 JetBrains.Annotations;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace Microsoft.AspNetCore.ApiVersioning.Swashbuckle
{
[UsedImplicitly(ImplicitUseKindFlags.InstantiatedWithFixedConstructorSignature)]
internal class VersioningOperationFilter : IOperationFilter
{
private readonly ISwaggerVersioningScheme _scheme;
public VersioningOperationFilter(ISwaggerVersioningScheme scheme)
{
_scheme = scheme;
}
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
string version = context.ApiDescription.ActionDescriptor.RouteValues["version"];
_scheme.Apply(operation, context, version);
}
}
}
| 34.724138 | 92 | 0.744786 | [
"MIT"
] | AlitzelMendez/arcade-services | src/Maestro/Microsoft.AspNetCore.ApiVersioning.Swashbuckle/VersioningOperationFilter.cs | 1,007 | C# |
using System;
using Machine.Fakes;
using Machine.Specifications;
namespace SpeakEasy.Specifications
{
[Subject(typeof(ResourceMerger))]
class ResourceMergerSpecs : WithSubject<ResourceMerger>
{
static Resource resource;
static Resource merged;
static Exception exception;
class with_resource_with_parameter
{
Establish context = () =>
{
resource = Resource.Create("company/:name");
Subject.NamingConvention = new DefaultNamingConvention();
};
class when_merging_segments
{
Because of = () =>
merged = Subject.Merge(resource, new { name = "company-name" });
It should_merge_values_into_resource = () =>
merged.Path.ShouldEqual("company/company-name");
}
class when_merging_segments_with_null_value
{
Because of = () =>
exception = Catch.Exception(() => Subject.Merge(resource, new { name = (string)null }));
It should_throw_exception = () =>
exception.ShouldBeOfExactType<ArgumentException>();
}
class when_merging_segments_of_different_case
{
Because of = () =>
merged = Subject.Merge(resource, new { Name = "company-name" });
It should_merge_values_into_resource = () =>
merged.Path.ShouldEqual("company/company-name");
}
}
class with_multiple_resource_with_parameters
{
Establish context = () =>
{
resource = Resource.Create("company/:name/:companyType");
Subject.NamingConvention = new DefaultNamingConvention();
};
class when_merging_multiple_segments
{
Because of = () =>
merged = Subject.Merge(resource, new { name = "company-name", companyType = "public" });
It should_merge_values_into_resource = () =>
merged.Path.ShouldEqual("company/company-name/public");
}
}
class when_merging_null_segments
{
Establish context = () =>
resource = Resource.Create("company");
Because of = () =>
merged = Subject.Merge(resource, null);
It should_return_resource = () =>
merged.Path.ShouldEqual("company");
}
class when_merging_null_segments_when_resource_has_segments
{
Establish context = () =>
resource = Resource.Create("company/:id");
Because of = () =>
exception = Catch.Exception(() => Subject.Merge(resource, null));
It should_throw_exception = () =>
exception.ShouldBeOfExactType<ArgumentException>();
}
class when_merging_segments_as_parameters_when_no_segment_names_in_path
{
Establish context = () =>
{
Subject.NamingConvention = new DefaultNamingConvention();
resource = Resource.Create("companies");
};
Because of = () =>
merged = Subject.Merge(resource, new { Filter = "nasdaq" });
It should_add_parameters = () =>
merged.HasParameter("Filter").ShouldBeTrue();
}
class when_merging_extra_segments_add_as_parameters
{
Establish context = () =>
{
Subject.NamingConvention = new DefaultNamingConvention();
resource = Resource.Create("company/:id");
};
Because of = () =>
merged = Subject.Merge(resource, new { id = 5, Filter = "ftse" });
It should_merge_url_segments = () =>
merged.Path.ShouldEqual("company/5");
It should_have_parameter_with_original_casing = () =>
merged.HasParameter("Filter").ShouldBeTrue();
It should_only_merge_in_given_parameters = () =>
merged.NumParameters.ShouldEqual(1);
}
}
}
| 32.287879 | 108 | 0.533787 | [
"Apache-2.0"
] | hhansell/SpeakEasy | src/SpeakEasy.Specifications/ResourceMergerSpecs.cs | 4,262 | C# |
using System;
using System.Xml.Serialization;
namespace Aop.Api.Domain
{
/// <summary>
/// AlipayFinancialnetAuthEcsignDataprepareCreateModel Data Structure.
/// </summary>
[Serializable]
public class AlipayFinancialnetAuthEcsignDataprepareCreateModel : AopObject
{
/// <summary>
/// 签约回跳类型
/// </summary>
[XmlElement("back_type")]
public string BackType { get; set; }
/// <summary>
/// 签约结束回跳地址
/// </summary>
[XmlElement("back_url")]
public string BackUrl { get; set; }
/// <summary>
/// 签约时所需要的数据信息
/// </summary>
[XmlElement("ext_info")]
public string ExtInfo { get; set; }
/// <summary>
/// 跳转类型
/// </summary>
[XmlElement("jump_type")]
public string JumpType { get; set; }
/// <summary>
/// 外部订单号
/// </summary>
[XmlElement("out_order_no")]
public string OutOrderNo { get; set; }
/// <summary>
/// 合作伙伴ID
/// </summary>
[XmlElement("partner_id")]
public string PartnerId { get; set; }
/// <summary>
/// 签约产品码
/// </summary>
[XmlElement("sign_product_id")]
public string SignProductId { get; set; }
/// <summary>
/// 签约方案码
/// </summary>
[XmlElement("solution_code")]
public string SolutionCode { get; set; }
/// <summary>
/// 回跳地址
/// </summary>
[XmlElement("third_part_schema")]
public string ThirdPartSchema { get; set; }
}
}
| 25.328358 | 80 | 0.494991 | [
"Apache-2.0"
] | alipay/alipay-sdk-net | AlipaySDKNet.Standard/Domain/AlipayFinancialnetAuthEcsignDataprepareCreateModel.cs | 1,801 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.DataContracts.Common
{
using System;
using Newtonsoft.Json;
using YamlDotNet.Serialization;
[Serializable]
public class SpecViewModel
{
[YamlMember(Alias = Constants.PropertyName.Uid)]
[JsonProperty(Constants.PropertyName.Uid)]
public string Uid { get; set; }
[YamlMember(Alias = "name")]
[JsonProperty("name")]
public string Name { get; set; }
[YamlMember(Alias = "fullName")]
[JsonProperty("fullName")]
public string FullName { get; set; }
[YamlMember(Alias = "isExternal")]
[JsonProperty("isExternal")]
public bool IsExternal { get; set; }
[YamlMember(Alias = Constants.PropertyName.Href)]
[JsonProperty(Constants.PropertyName.Href)]
public string Href { get; set; }
}
}
| 28.857143 | 101 | 0.644554 | [
"MIT"
] | ghuntley/docfx | src/Microsoft.DocAsCode.DataContracts.Common/SpecViewModel.cs | 1,010 | C# |
using mouse_keyboard_bot.App;
using mouse_keyboard_bot.HostActions;
using mouse_keyboard_bot.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace mouse_keyboard_bot.Recorder
{
public class Replier
{
Recording _recording;
public Replier()
{
}
public void Start(Recording recording)
{
_recording = recording;
if (_recording != null)
{
Run();
}
}
volatile bool run = false;
private async void Run()
{
int skip = 2;// Config.SkipLast.Value;
run = true;
long prevTime = _recording.StartTime;
for (int i = 0; i < _recording.Events.Count - skip && run; i++)
{
var evt = _recording.Events[i];
await Task.Delay((int)(evt.Time - prevTime));
prevTime = evt.Time;
if (evt.Type == DetailsType.Mouse)
{
MouseMove.ProcessMouseEvent(_recording.Events[i] as MouseDetails);
}
else if (_recording.Events[i].Type == DetailsType.Keyboard)
{
KeyPress.ProcessKeyEvent(_recording.Events[i] as KeyboardDetails);
}
}
}
public void Finish()
{
run = false;
}
}
}
| 25.87931 | 86 | 0.519654 | [
"MIT"
] | Aknilam/mouse-keyboard-bot | mouse-keyboard-bot/Recorder/Replier.cs | 1,503 | C# |
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
namespace DumpDiag.Impl
{
internal static class DotNetToolFinder
{
internal static bool TryFind(
string toolName,
[NotNullWhen(true)] out string? executablePath,
[NotNullWhen(false)] out string? error)
{
var userDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var toolsDir = Path.Combine(userDir, ".dotnet", "tools");
if (!Directory.Exists(toolsDir))
{
executablePath = null;
error = $"Could not find ({toolsDir}), which should contain .NET tools";
return false;
}
var candidates = Directory.GetFiles(toolsDir).Where(x => Path.GetFileNameWithoutExtension(x) == toolName).ToList();
if (candidates.Count == 0)
{
executablePath = null;
error = $"Tool ({toolName}) not found in ({toolsDir}); install with `dotnet tool install --global {toolName}`";
return false;
}
else if (candidates.Count > 1)
{
executablePath = null;
error = $"Multiple candidates for ({toolName}) found in ({toolsDir}): {string.Join(", ", candidates.Select(static x => $"({x})"))}";
return false;
}
executablePath = candidates.Single();
error = null;
return true;
}
}
}
| 33.73913 | 148 | 0.545747 | [
"MIT"
] | kevin-montrose/DumpDiag | DumpDiag/Impl/DotNetToolFinder.cs | 1,554 | C# |
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using UnityEngine;
public class SceneSerializer : MonoBehaviour
{
private void Start()
{
StartCoroutine(DelayedStart());
}
private IEnumerator<YieldInstruction> DelayedStart()
{
yield return new WaitForSeconds(1);
GameObject[] rootObjects = UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects();
foreach (GameObject root in rootObjects)
{
Serialize(root, 0);
}
UnityEngine.Debug.LogFormat("[NMTechSupport] {0}", "Scene succesfullly serialized");
}
private void Serialize(GameObject obj, int i)
{
string output = "";
for (int j = 0; j < i; j++)
{
output += "\t";
}
output += obj.name;
TechSupportLog.Log(output);
output = "";
Component[] components = obj.GetComponents<Component>();
foreach(Component c in components)
{
output = "";
for (int j = 0; j < i; j++)
{
output += "\t";
}
output += " [c] " + c.GetType().ToString();
TechSupportLog.Log(output);
}
int childCount = obj.transform.childCount;
for(int j = 0; j < childCount; j++)
{
GameObject child = obj.transform.GetChild(j).gameObject;
Serialize(child, i + 1);
}
}
}
| 20.47619 | 109 | 0.627907 | [
"MIT"
] | willem88836/ktanemodkit | Assets/Mods/GenericScripts/SceneSerializer.cs | 1,292 | C# |
using Newtonsoft.Json;
namespace Essensoft.AspNetCore.Payment.Alipay.Response
{
/// <summary>
/// AlipayMobileShakeUserQueryResponse.
/// </summary>
public class AlipayMobileShakeUserQueryResponse : AlipayResponse
{
/// <summary>
/// 对应的业务信息
/// </summary>
[JsonProperty("bizdata")]
public string Bizdata { get; set; }
/// <summary>
/// 支付宝用户登录账户,可能是email或者手机号码
/// </summary>
[JsonProperty("logon_id")]
public string LogonId { get; set; }
/// <summary>
/// 对应的核销数据
/// </summary>
[JsonProperty("pass_id")]
public string PassId { get; set; }
/// <summary>
/// 支付宝用户ID
/// </summary>
[JsonProperty("user_id")]
public string UserId { get; set; }
}
}
| 23.914286 | 68 | 0.537634 | [
"MIT"
] | gebiWangshushu/payment | src/Essensoft.AspNetCore.Payment.Alipay/Response/AlipayMobileShakeUserQueryResponse.cs | 915 | 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 states-2016-11-23.normal.json service model.
*/
using System;
using Amazon.Runtime;
using Amazon.Util.Internal;
namespace Amazon.StepFunctions
{
/// <summary>
/// Configuration for accessing Amazon StepFunctions service
/// </summary>
public partial class AmazonStepFunctionsConfig : ClientConfig
{
private static readonly string UserAgentString =
InternalSDKUtils.BuildUserAgentString("3.3.4.7");
private string _userAgent = UserAgentString;
/// <summary>
/// Default constructor
/// </summary>
public AmazonStepFunctionsConfig()
{
this.AuthenticationServiceName = "states";
}
/// <summary>
/// The constant used to lookup in the region hash the endpoint.
/// </summary>
public override string RegionEndpointServiceName
{
get
{
return "states";
}
}
/// <summary>
/// Gets the ServiceVersion property.
/// </summary>
public override string ServiceVersion
{
get
{
return "2016-11-23";
}
}
/// <summary>
/// Gets the value of UserAgent property.
/// </summary>
public override string UserAgent
{
get
{
return _userAgent;
}
}
}
} | 26.2625 | 104 | 0.589243 | [
"Apache-2.0"
] | woellij/aws-sdk-net | sdk/src/Services/StepFunctions/Generated/AmazonStepFunctionsConfig.cs | 2,101 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Xunit;
namespace System.Data.Tests
{
public class FacadeTest
{
[Theory]
[InlineData("Microsoft.SqlServer.Server.SqlMetaData")] // Type from System.Data.SqlClient
[InlineData("System.Data.SqlTypes.SqlBytes")] // Type from System.Data.Common
public void TestSystemData(string typeName)
{
// Verify that the type can be loaded via .NET Framework compat facade
Type.GetType(typeName + ", System.Data", throwOnError: true);
}
}
}
| 32.7 | 97 | 0.666667 | [
"MIT"
] | 71221-maker/runtime | src/libraries/System.Data.Common/tests/System/Data/FacadeTest.cs | 654 | C# |
using BrightstarDB.EntityFramework;
namespace BrightstarDB.Portable.Tests.EntityFramework.Model
{
[Entity]
public interface IIdentityClashTest
{
string Id { get; }
}
[Entity]
public interface IIdentityClashTestLevel1 : IIdentityClashTest
{
//[Identifier]
//string MyId { get; }
}
[Entity]
public interface IIdentityClashTestLevel2 : IIdentityClashTestLevel1
{
//[Identifier]
//string MyId { get; }
}
}
| 19.038462 | 72 | 0.634343 | [
"MIT"
] | rajcybage/BrightstarDB | src/portable/Test/BrightstarDB.Portable.Store.Tests/EntityFramework/Model/IIdentityClashTest.cs | 497 | C# |
using System.Collections.Generic;
using Tonsil.Files;
namespace Tonsil.Processes.Downloaders
{
public class Esentutl : Downloader
{
public override string ImagePath { get; } = @"c:\windows\system32\esentutl.exe";
public override List<FilePathType> ValidSourcePathTypes { get; } = new List<FilePathType>() { FilePathType.Local, FilePathType.ADS, FilePathType.SMB};
public override List<FilePathType> ValidDestinationPathTypes { get; } = new List<FilePathType>() { FilePathType.Local, FilePathType.ADS, FilePathType.SMB};
public override string[] ArgumentsTemplate { get; } = new string[] { "/y","{0}", "/d", "{0}", "/o" };
public override int SourceArgumentIndex { get; } = 1;
public override int DestinationArgumentIndex { get; } = 3;
}
}
| 47.176471 | 163 | 0.685786 | [
"MIT"
] | CreatePhotonW/tonsil | Tonsil/Processes/Downloaders/Esentutl.cs | 804 | C# |
using FreeSql.DataAnnotations;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace FreeSql.Tests.Odbc.SqlServerExpression
{
[Collection("SqlServerCollection")]
public class StringTest
{
ISelect<Topic> select => g.sqlserver.Select<Topic>();
[Table(Name = "tb_topic")]
class Topic
{
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int Clicks { get; set; }
public int TypeGuid { get; set; }
public TestTypeInfo Type { get; set; }
public string Title { get; set; }
public DateTime CreateTime { get; set; }
}
class TestTypeInfo
{
[Column(IsIdentity = true)]
public int Guid { get; set; }
public int ParentId { get; set; }
public TestTypeParentInfo Parent { get; set; }
public string Name { get; set; }
}
class TestTypeParentInfo
{
public int Id { get; set; }
public string Name { get; set; }
public List<TestTypeInfo> Types { get; set; }
}
class TestEqualsGuid
{
public Guid id { get; set; }
}
[Fact]
public void Equals__()
{
var list = new List<object>();
list.Add(select.Where(a => a.Title.Equals("aaa")).ToList());
list.Add(g.sqlserver.Select<TestEqualsGuid>().Where(a => a.id.Equals(Guid.Empty)).ToList());
}
[Fact]
public void Empty()
{
var data = new List<object>();
data.Add(select.Where(a => (a.Title ?? "") == string.Empty).ToSql());
}
[Fact]
public void StartsWith()
{
var list = new List<object>();
list.Add(select.Where(a => a.Title.StartsWith("aaa")).ToList());
list.Add(select.Where(a => a.Title.StartsWith(a.Title)).ToList());
list.Add(select.Where(a => a.Title.StartsWith(a.Title + 1)).ToList());
list.Add(select.Where(a => a.Title.StartsWith(a.Type.Name)).ToList());
list.Add(select.Where(a => (a.Title + "aaa").StartsWith("aaa")).ToList());
list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title)).ToList());
list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title + 1)).ToList());
list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Type.Name)).ToList());
}
[Fact]
public void EndsWith()
{
var list = new List<object>();
list.Add(select.Where(a => a.Title.EndsWith("aaa")).ToList());
list.Add(select.Where(a => a.Title.EndsWith(a.Title)).ToList());
list.Add(select.Where(a => a.Title.EndsWith(a.Title + 1)).ToList());
list.Add(select.Where(a => a.Title.EndsWith(a.Type.Name)).ToList());
list.Add(select.Where(a => (a.Title + "aaa").EndsWith("aaa")).ToList());
list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title)).ToList());
list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title + 1)).ToList());
list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Type.Name)).ToList());
}
[Fact]
public void Contains()
{
var list = new List<object>();
list.Add(select.Where(a => a.Title.Contains("aaa")).ToList());
list.Add(select.Where(a => a.Title.Contains(a.Title)).ToList());
list.Add(select.Where(a => a.Title.Contains(a.Title + 1)).ToList());
list.Add(select.Where(a => a.Title.Contains(a.Type.Name)).ToList());
list.Add(select.Where(a => (a.Title + "aaa").Contains("aaa")).ToList());
list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title)).ToList());
list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title + 1)).ToList());
list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Type.Name)).ToList());
}
[Fact]
public void ToLower()
{
var data = new List<object>();
data.Add(select.Where(a => a.Title.ToLower() == "aaa").ToList());
data.Add(select.Where(a => a.Title.ToLower() == a.Title).ToList());
data.Add(select.Where(a => a.Title.ToLower() == (a.Title + 1)).ToList());
data.Add(select.Where(a => a.Title.ToLower() == a.Type.Name).ToList());
data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == "aaa").ToList());
data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Title).ToList());
data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == (a.Title + 1)).ToList());
data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Type.Name).ToList());
}
[Fact]
public void ToUpper()
{
var data = new List<object>();
data.Add(select.Where(a => a.Title.ToUpper() == "aaa").ToList());
data.Add(select.Where(a => a.Title.ToUpper() == a.Title).ToList());
data.Add(select.Where(a => a.Title.ToUpper() == (a.Title + 1)).ToList());
data.Add(select.Where(a => a.Title.ToUpper() == a.Type.Name).ToList());
data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == "aaa").ToList());
data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Title).ToList());
data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == (a.Title + 1)).ToList());
data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Type.Name).ToList());
}
[Fact]
public void Substring()
{
var data = new List<object>();
data.Add(select.Where(a => a.Title.Substring(0) == "aaa").ToList());
data.Add(select.Where(a => a.Title.Substring(0) == a.Title).ToList());
data.Add(select.Where(a => a.Title.Substring(0) == (a.Title + 1)).ToList());
data.Add(select.Where(a => a.Title.Substring(0) == a.Type.Name).ToList());
data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(a.Title.Length) == "aaa").ToList());
data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, a.Title.Length) == a.Title).ToList());
data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, 3) == (a.Title + 1)).ToList());
data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(1, 2) == a.Type.Name).ToList());
}
[Fact]
public void Length()
{
var data = new List<object>();
data.Add(select.Where(a => a.Title.Length == 0).ToList());
data.Add(select.Where(a => a.Title.Length == 1).ToList());
data.Add(select.Where(a => a.Title.Length == a.Title.Length + 1).ToList());
data.Add(select.Where(a => a.Title.Length == a.Type.Name.Length).ToList());
data.Add(select.Where(a => (a.Title + "aaa").Length == 0).ToList());
data.Add(select.Where(a => (a.Title + "aaa").Length == 1).ToList());
data.Add(select.Where(a => (a.Title + "aaa").Length == a.Title.Length + 1).ToList());
data.Add(select.Where(a => (a.Title + "aaa").Length == a.Type.Name.Length).ToList());
}
[Fact]
public void IndexOf()
{
var data = new List<object>();
data.Add(select.Where(a => a.Title.IndexOf("aaa") == -1).ToList());
data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == -1).ToList());
data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList());
data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList());
data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa") == -1).ToList());
data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == -1).ToList());
data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList());
data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList());
}
[Fact]
public void PadLeft()
{
//var data = new List<object>();
//data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == "aaa").ToList());
//data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Title).ToList());
//data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == (a.Title + 1)).ToList());
//data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Type.Name).ToList());
//data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == "aaa").ToList());
//data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Title).ToList());
//data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == (a.Title + 1)).ToList());
//data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Type.Name).ToList());
}
[Fact]
public void PadRight()
{
//var data = new List<object>();
//data.Add(select.Where(a => a.Title.PadRight(10, 'a') == "aaa").ToList());
//data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Title).ToList());
//data.Add(select.Where(a => a.Title.PadRight(10, 'a') == (a.Title + 1)).ToList());
//data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Type.Name).ToList());
//data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == "aaa").ToList());
//data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Title).ToList());
//data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == (a.Title + 1)).ToList());
//data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Type.Name).ToList());
}
[Fact]
public void Trim()
{
var data = new List<object>();
data.Add(select.Where(a => a.Title.Trim() == "aaa").ToList());
data.Add(select.Where(a => a.Title.Trim('a') == a.Title).ToList());
data.Add(select.Where(a => a.Title.Trim('a', 'b') == (a.Title + 1)).ToList());
data.Add(select.Where(a => a.Title.Trim('a', 'b', 'c') == a.Type.Name).ToList());
data.Add(select.Where(a => (a.Title.Trim() + "aaa").Trim() == "aaa").ToList());
data.Add(select.Where(a => (a.Title.Trim('a') + "aaa").Trim('a') == a.Title).ToList());
data.Add(select.Where(a => (a.Title.Trim('a', 'b') + "aaa").Trim('a', 'b') == (a.Title + 1)).ToList());
data.Add(select.Where(a => (a.Title.Trim('a', 'b', 'c') + "aaa").Trim('a', 'b', 'c') == a.Type.Name).ToList());
}
[Fact]
public void TrimStart()
{
var data = new List<object>();
data.Add(select.Where(a => a.Title.TrimStart() == "aaa").ToList());
data.Add(select.Where(a => a.Title.TrimStart('a') == a.Title).ToList());
data.Add(select.Where(a => a.Title.TrimStart('a', 'b') == (a.Title + 1)).ToList());
data.Add(select.Where(a => a.Title.TrimStart('a', 'b', 'c') == a.Type.Name).ToList());
data.Add(select.Where(a => (a.Title.TrimStart() + "aaa").TrimStart() == "aaa").ToList());
data.Add(select.Where(a => (a.Title.TrimStart('a') + "aaa").TrimStart('a') == a.Title).ToList());
data.Add(select.Where(a => (a.Title.TrimStart('a', 'b') + "aaa").TrimStart('a', 'b') == (a.Title + 1)).ToList());
data.Add(select.Where(a => (a.Title.TrimStart('a', 'b', 'c') + "aaa").TrimStart('a', 'b', 'c') == a.Type.Name).ToList());
}
[Fact]
public void TrimEnd()
{
var data = new List<object>();
data.Add(select.Where(a => a.Title.TrimEnd() == "aaa").ToList());
data.Add(select.Where(a => a.Title.TrimEnd('a') == a.Title).ToList());
data.Add(select.Where(a => a.Title.TrimEnd('a', 'b') == (a.Title + 1)).ToList());
data.Add(select.Where(a => a.Title.TrimEnd('a', 'b', 'c') == a.Type.Name).ToList());
data.Add(select.Where(a => (a.Title.TrimEnd() + "aaa").TrimEnd() == "aaa").ToList());
data.Add(select.Where(a => (a.Title.TrimEnd('a') + "aaa").TrimEnd('a') == a.Title).ToList());
data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b') + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList());
data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b', 'c') + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList());
}
[Fact]
public void Replace()
{
var data = new List<object>();
data.Add(select.Where(a => a.Title.Replace("a", "b") == "aaa").ToList());
data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c") == a.Title).ToList());
data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") == (a.Title + 1)).ToList());
data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") == a.Type.Name).ToList());
data.Add(select.Where(a => (a.Title.Replace("a", "b") + "aaa").TrimEnd() == "aaa").ToList());
data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c") + "aaa").TrimEnd('a') == a.Title).ToList());
data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList());
data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList());
}
[Fact]
public void CompareTo()
{
//var data = new List<object>();
//data.Add(select.Where(a => a.Title.CompareTo(a.Title) == 0).ToList());
//data.Add(select.Where(a => a.Title.CompareTo(a.Title) > 0).ToList());
//data.Add(select.Where(a => a.Title.CompareTo(a.Title + 1) == 0).ToList());
//data.Add(select.Where(a => a.Title.CompareTo(a.Title + a.Type.Name) == 0).ToList());
//data.Add(select.Where(a => (a.Title + "aaa").CompareTo("aaa") == 0).ToList());
//data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title) > 0).ToList());
//data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title + 1) == 0).ToList());
//data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Type.Name) == 0).ToList());
}
[Fact]
public void string_IsNullOrEmpty()
{
var data = new List<object>();
data.Add(select.Where(a => string.IsNullOrEmpty(a.Title)).ToList());
//data.Add(select.Where(a => string.IsNullOrEmpty(a.Title) == false).ToList());
data.Add(select.Where(a => !string.IsNullOrEmpty(a.Title)).ToList());
}
[Fact]
public void string_IsNullOrWhiteSpace()
{
var data = new List<object>();
data.Add(select.Where(a => string.IsNullOrWhiteSpace(a.Title)).ToList());
data.Add(select.Where(a => string.IsNullOrWhiteSpace(a.Title) == false).ToList());
data.Add(select.Where(a => !string.IsNullOrWhiteSpace(a.Title)).ToList());
}
}
}
| 54.274914 | 168 | 0.516652 | [
"MIT"
] | Coldairarrow/FreeSql | FreeSql.Tests/FreeSql.Tests.Provider.Odbc/SqlServer/SqlServerExpression/StringTest.cs | 15,794 | C# |
using System;
using System.Linq;
namespace OddFilter
{
class Program
{
static void Main(string[] args)
{
int[] nums = Console.ReadLine()
.Split()
.Select(int.Parse)
.Where(num => num % 2 == 0)
.ToArray();
ChangeNums(nums);
Console.WriteLine(String.Join(" ", nums));
}
private static void ChangeNums(int[] nums)
{
double average = nums.Average();
for (int i = 0; i < nums.Length; ++i)
{
if (nums[i] > average)
{
++nums[i];
continue;
}
--nums[i];
}
}
}
}
| 20.315789 | 54 | 0.382124 | [
"MIT"
] | MartsTech/IT-Career | 02. Programming/07 - Dictionaries-and-hash-tables/30. Lambda expressions and dictionaries/02. OddFilter/Program.cs | 774 | 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 elasticache-2015-02-02.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.ElastiCache.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.ElastiCache.Model.Internal.MarshallTransformations
{
/// <summary>
/// ModifyCacheSubnetGroup Request Marshaller
/// </summary>
public class ModifyCacheSubnetGroupRequestMarshaller : IMarshaller<IRequest, ModifyCacheSubnetGroupRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((ModifyCacheSubnetGroupRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(ModifyCacheSubnetGroupRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.ElastiCache");
request.Parameters.Add("Action", "ModifyCacheSubnetGroup");
request.Parameters.Add("Version", "2015-02-02");
if(publicRequest != null)
{
if(publicRequest.IsSetCacheSubnetGroupDescription())
{
request.Parameters.Add("CacheSubnetGroupDescription", StringUtils.FromString(publicRequest.CacheSubnetGroupDescription));
}
if(publicRequest.IsSetCacheSubnetGroupName())
{
request.Parameters.Add("CacheSubnetGroupName", StringUtils.FromString(publicRequest.CacheSubnetGroupName));
}
if(publicRequest.IsSetSubnetIds())
{
int publicRequestlistValueIndex = 1;
foreach(var publicRequestlistValue in publicRequest.SubnetIds)
{
request.Parameters.Add("SubnetIds" + "." + "member" + "." + publicRequestlistValueIndex, StringUtils.FromString(publicRequestlistValue));
publicRequestlistValueIndex++;
}
}
}
return request;
}
}
} | 39.756098 | 161 | 0.641411 | [
"Apache-2.0"
] | Bynder/aws-sdk-net | sdk/src/Services/ElastiCache/Generated/Model/Internal/MarshallTransformations/ModifyCacheSubnetGroupRequestMarshaller.cs | 3,260 | C# |
// BlastCommand.cs
// Copyright (c) 2014+ by Michael Penner. All rights reserved.
using System.Diagnostics;
using Eamon.Game.Attributes;
using EamonRT.Framework.Commands;
using EamonRT.Framework.Primitive.Enums;
using static StrongholdOfKahrDur.Game.Plugin.PluginContext;
namespace StrongholdOfKahrDur.Game.Commands
{
[ClassMappings]
public class BlastCommand : EamonRT.Game.Commands.BlastCommand, IBlastCommand
{
public override void PlayerProcessEvents(EventType eventType)
{
var helmArtifact = gADB[25];
Debug.Assert(helmArtifact != null);
// Necromancer cannot be blasted unless wearing Wizard's Helm
if (eventType == EventType.AfterMonsterGetsAggravated && DobjMonster != null && DobjMonster.Uid == 22 && !helmArtifact.IsWornByCharacter())
{
var rl = gEngine.RollDice(1, 4, 56);
gEngine.PrintEffectDesc(rl);
GotoCleanup = true;
}
else
{
base.PlayerProcessEvents(eventType);
}
}
public override bool ShouldAllowSkillGains()
{
// When Necromancer is blasted only allow skill increases if wearing Wizard's Helm
if (DobjMonster != null && DobjMonster.Uid == 22)
{
var helmArtifact = gADB[25];
Debug.Assert(helmArtifact != null);
return helmArtifact.IsWornByCharacter();
}
else
{
return base.ShouldAllowSkillGains();
}
}
}
}
| 24.017241 | 143 | 0.687724 | [
"MIT"
] | skyhoshi/Eamon-CS | Adventures/StrongholdOfKahrDur/Game/Commands/Interactive/BlastCommand.cs | 1,338 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using PlayMe.Common.Model;
using PlayMe.Plumbing.Diagnostics;
using PlayMe.Server.Interfaces;
using PlayMe.Server.PlayMeCallbackServiceReference;
namespace PlayMe.Server
{
public class CallbackClient : ICallbackClient
{
private readonly ILogger logger;
public CallbackClient(ILogger logger)
{
this.logger = logger;
}
public void TrackHistoryChanged(PagedResult<QueuedTrack> trackHistory)
{
try
{
using (var client = new SpotifyCallbackServiceClient())
{
client.TrackHistoryChanged(trackHistory);
}
}
catch (Exception ex)
{
logger.Error("TrackHistoryChanged failed with exception {0}", ex.Message);
}
}
public void QueueChanged(IEnumerable<QueuedTrack> notifyQueue)
{
try
{
using (var client = new SpotifyCallbackServiceClient())
{
client.QueueChanged(notifyQueue.ToList());
}
}
catch (Exception ex)
{
logger.Error("QueueChanged failed with exception {0}", ex.Message);
}
}
public void PlayingTrackChanged(QueuedTrack track)
{
try
{
using (var client = new SpotifyCallbackServiceClient())
{
client.PlayingTrackChanged(track);
}
}
catch (Exception ex)
{
logger.Error("PlayingTrackChanged failed with exception {0}", ex.Message);
}
}
}
}
| 27.333333 | 90 | 0.52439 | [
"MIT"
] | Jono120/PlayMe | PlayMe.Server/CallbackClient.cs | 1,806 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace UOP1.StateMachine.ScriptableObjects
{
[CreateAssetMenu(fileName = "New Transition Table", menuName = "State Machines/Transition Table")]
public class TransitionTableSO : ScriptableObject
{
[SerializeField] private TransitionItem[] _transitions = default;
/// <summary>
/// Will get the initial state and instantiate all subsequent states, transitions, actions and conditions.
/// </summary>
internal State GetInitialState(StateMachine stateMachine)
{
var states = new List<State>();
var transitions = new List<StateTransition>();
var createdInstances = new Dictionary<ScriptableObject, object>();
var fromStates = _transitions.GroupBy(transition => transition.FromState);
foreach (var fromState in fromStates)
{
if (fromState.Key == null)
throw new ArgumentNullException(nameof(fromState.Key), $"TransitionTable: {name}");
var state = fromState.Key.GetState(stateMachine, createdInstances);
states.Add(state);
transitions.Clear();
foreach (var transitionItem in fromState)
{
if (transitionItem.ToState == null)
throw new ArgumentNullException(nameof(transitionItem.ToState), $"TransitionTable: {name}, From State: {fromState.Key.name}");
var toState = transitionItem.ToState.GetState(stateMachine, createdInstances);
ProcessConditionUsages(stateMachine, transitionItem.Conditions, createdInstances, out var conditions, out var resultGroups);
transitions.Add(new StateTransition(toState, conditions, resultGroups));
}
state._transitions = transitions.ToArray();
}
return states.Count > 0 ? states[0]
: throw new InvalidOperationException($"TransitionTable {name} is empty.");
}
private static void ProcessConditionUsages(
StateMachine stateMachine,
ConditionUsage[] conditionUsages,
Dictionary<ScriptableObject, object> createdInstances,
out StateCondition[] conditions,
out int[] resultGroups)
{
int count = conditionUsages.Length;
conditions = new StateCondition[count];
for (int i = 0; i < count; i++)
conditions[i] = conditionUsages[i].Condition.GetCondition(
stateMachine, conditionUsages[i].ExpectedResult == Result.True, createdInstances);
List<int> resultGroupsList = new List<int>();
for (int i = 0; i < count; i++)
{
int idx = resultGroupsList.Count;
resultGroupsList.Add(1);
while (i < count - 1 && conditionUsages[i].Operator == Operator.And)
{
i++;
resultGroupsList[idx]++;
}
}
resultGroups = resultGroupsList.ToArray();
}
[Serializable]
public struct TransitionItem
{
public StateSO FromState;
public StateSO ToState;
public ConditionUsage[] Conditions;
}
[Serializable]
public struct ConditionUsage
{
public Result ExpectedResult;
public StateConditionSO Condition;
public Operator Operator;
}
public enum Result { True, False }
public enum Operator { And, Or }
}
}
| 30.545455 | 132 | 0.720569 | [
"Apache-2.0"
] | Alan-mag/open-project-1 | UOP1_Project/Assets/Scripts/StateMachine/ScriptableObjects/TransitionTableSO.cs | 3,026 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Balivo.AppCenterClient.Models
{
using Newtonsoft.Json;
using System.Linq;
public partial class ErrorRetentionSettings
{
/// <summary>
/// Initializes a new instance of the ErrorRetentionSettings class.
/// </summary>
public ErrorRetentionSettings()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ErrorRetentionSettings class.
/// </summary>
public ErrorRetentionSettings(int retentionInDays)
{
RetentionInDays = retentionInDays;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "retention_in_days")]
public int RetentionInDays { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
//Nothing to validate
}
}
}
| 27.433962 | 90 | 0.584594 | [
"MIT"
] | balivo/appcenter-openapi-sdk | generated/Models/ErrorRetentionSettings.cs | 1,454 | C# |
using System;
class FormatNumber
{
static void Main()
{
int number =int.Parse(Console.ReadLine());
Console.WriteLine("{0,15:D}",number);// Decimal number
Console.WriteLine("{0,15:X}",number);// Hexadecimal number
Console.WriteLine("{0,15:P}",number);// Percentage
Console.WriteLine("{0,15:E}",number);// Scientific notation
}
}
| 21.611111 | 67 | 0.606684 | [
"MIT"
] | DanielaIvanova/04.CSharp-Advanced | 06. StringsAndTextProcessing/11.FormatNumber/FormatNumber.cs | 391 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Arrest.Internals {
public class RestClientEventArgs : EventArgs {
public readonly RestCallData CallData;
internal RestClientEventArgs(RestCallData callData) {
CallData = callData;
}
}
public class RestClientEvents {
public event EventHandler<RestClientEventArgs> SendingRequest;
public event EventHandler<RestClientEventArgs> ReceivedResponse;
public event EventHandler<RestClientEventArgs> ReceivedError;
public event EventHandler<RestClientEventArgs> CallCompleted;
internal void OnSendingRequest(RestClient client, RestCallData callData) {
SendingRequest?.Invoke(client, new RestClientEventArgs(callData));
}
internal void OnReceivedResponse(RestClient client, RestCallData callData) {
ReceivedResponse?.Invoke(client, new RestClientEventArgs(callData));
}
internal void OnReceivedError(RestClient client, RestCallData callData) {
ReceivedError?.Invoke(client, new RestClientEventArgs(callData));
}
internal void OnCompleted(RestClient client, RestCallData callData) {
CallCompleted?.Invoke(client, new RestClientEventArgs(callData));
}
} //class
}
| 34.277778 | 80 | 0.767423 | [
"MIT"
] | rivantsov/arrest | Arrest/Internals/RestClientEvents.cs | 1,236 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Innovator.Client;
using System.ComponentModel;
using Microsoft.VisualBasic;
namespace InnovatorAdmin.Scripts
{
[DisplayName("Generate CT+ Class"), Description("Generate a CT+ class file for the given Item Type"), DefaultProperty("ItemType")]
public class GenerateCtClass : IAsyncScript
{
[ DisplayName("Item Type")
, Category("Main")
, Description("The name of the item type to generate a class for")]
public string ItemType { get; set; }
[ DisplayName("Merge File Path")
, Category("Main")
, Description("The path to the file to merge the results into. {0} will be replaced with the ItemType name (spaces removed).")]
public string MergePath { get; set; }
[ DisplayName("Is Base?")
, Category("Optional")
, DefaultValue(false)
, Description("If the class is core to Aras and will go in Gentex.Data.Aras")]
public bool IsBase { get; set; }
[ DisplayName("Get Properties")
, Category("Optional")
, DefaultValue(false)
, Description("Whether to hard code the property access (which migh help with performance) such as is done with the Part model")]
public bool GetProperties { get; set; }
[ DisplayName("Include Sort Order")
, Category("Optional")
, DefaultValue(false)
, Description("Whether or not to include the sort_order property in the class")]
public bool IncludeSortOrder { get; set; }
public GenerateCtClass()
{
this.MergePath = @"C:\path\to\file\{0}.vb";
}
public IPromise<string> Execute(IAsyncConnection conn)
{
return ExecuteAsync(conn).ToPromise();
}
public async Task<string> ExecuteAsync(IAsyncConnection conn)
{
var defaultProps = new List<string>() {
"classification",
"config_id",
"created_by_id",
"created_on",
"css",
"current_state",
"effective_date",
"generation",
"id",
"is_current",
"is_released",
"keyed_name",
"locked_by_id",
"major_rev",
"managed_by_id",
"minor_rev",
"modified_by_id",
"modified_on",
"new_version",
"not_lockable",
"owned_by_id",
"permission_id",
"release_date",
"state",
"superseded_date",
"team_id",
"related_id",
"source_id",
"behavior",
"itemtype"
};
if (!this.IncludeSortOrder)
defaultProps.Add("sort_order");
var info = await conn.ApplyAsync(@"<AML>
<Item type='ItemType' action='get'>
<name>@0</name>
<Relationships>
<Item action='get' type='Property' select='label,name,is_required,is_class_required,data_type,data_source,readonly,pattern,stored_length,foreign_property(label,name,is_required,is_class_required,data_type,data_source,readonly,pattern,stored_length)'></Item>
</Relationships>
</Item>
</AML>", true, true, this.ItemType).ToTask();
var itemTypeInfo = info.AssertItem();
var itemProps = new List<ArasProperty>();
var classBuilder = new StringBuilder();
var polyItem = itemTypeInfo.Property("implementation_type").AsString("") == "polymorphic";
if (!this.IsBase) classBuilder.AppendLine("Imports Gentex.ComponentTracker.Model");
classBuilder.AppendLine("Imports Gentex.Data.Aras.Model");
classBuilder.AppendLine("Imports Gentex.Data.Base.Model");
classBuilder.AppendLine();
if (this.IsBase)
classBuilder.AppendLine("Namespace Aras.Model");
else
classBuilder.AppendLine("Namespace Model");
classBuilder.AppendFormat(@" <SourceName(""{0}"")> _", this.ItemType).AppendLine();
if (itemTypeInfo.Property("is_relationship").AsBoolean(false))
{
classBuilder.AppendFormat(" Public Class {0}", Strings.StrConv(this.ItemType, VbStrConv.ProperCase).Replace(" ", "")).AppendLine();
var rel = await conn.ApplyAsync(@"<AML>
<Item type='RelationshipType' action='get' select='source_id,related_id' related_expand='0'>
<relationship_id>@0</relationship_id>
</Item>
</AML>", true, true, itemTypeInfo.Id()).ToTask();
var relTypeInfo = rel.AssertItem();
if (!relTypeInfo.RelatedId().KeyedName().HasValue())
classBuilder.AppendFormat(" Inherits NullRelationship(Of {0})",
Strings.StrConv(relTypeInfo.SourceId().Attribute("name").Value, VbStrConv.ProperCase).Replace(" ", ""))
.AppendLine();
else
classBuilder.AppendFormat(" Inherits Relationship(Of {0}, {1})",
Strings.StrConv(relTypeInfo.SourceId().Attribute("name").Value, VbStrConv.ProperCase).Replace(" ", ""),
Strings.StrConv(relTypeInfo.RelatedId().Attribute("name").Value, VbStrConv.ProperCase).Replace(" ", ""))
.AppendLine();
}
else if (polyItem)
{
classBuilder.AppendFormat(" Public Interface I{0}", Strings.StrConv(this.ItemType, VbStrConv.ProperCase).Replace(" ", "")).AppendLine();
if (itemTypeInfo.Property("is_versionable").AsBoolean(false))
classBuilder.AppendLine(" Inherits IVersionableItem");
else
classBuilder.AppendLine(" Inherits IItem");
}
else
{
classBuilder.AppendFormat(" Public Class {0}", Strings.StrConv(this.ItemType, VbStrConv.ProperCase).Replace(" ", "")).AppendLine();
if (itemTypeInfo.Property("is_versionable").AsBoolean(false))
classBuilder.AppendLine(" Inherits VersionableItem");
else
classBuilder.AppendLine(" Inherits Item");
}
classBuilder.AppendLine();
ArasProperty arasProp;
foreach (var prop in itemTypeInfo.Relationships("Property"))
{
if (!defaultProps.Contains(prop.Property("name").AsString("")))
{
arasProp = await ArasProperty.NewProp(prop, conn);
itemProps.Add(arasProp);
}
}
if (!polyItem)
{
itemProps.Sort(SortVariable);
foreach (var prop in itemProps)
{
if (prop.PropType == ArasProperty.PropTypes.ReadOnly)
{
classBuilder.AppendFormat(@" Private {0} As New ReadOnlyPropertyValue(Of {1})(""{2}"", Me)", prop.VarName, prop.DataType, prop.Name).AppendLine();
}
else if (prop.PropType == ArasProperty.PropTypes.Normal)
{
classBuilder.AppendFormat(@" Private {0} As New PropertyValue(Of {1})(""{2}"", Me, {3})", prop.VarName, prop.DataType, prop.Name, prop.Required).AppendLine();
}
}
classBuilder.AppendLine();
var foreignProps = itemProps.Where(p => p.PropType == ArasProperty.PropTypes.Foreign);
if (foreignProps.Any())
{
foreach (var prop in foreignProps)
{
classBuilder.AppendFormat(@" Private {0} As New ForeignPropertyValue(Of {1}, {2})(""{3}"", Me, {4}, Function(item) item.{5})"
, prop.VarName, prop.ForeignLinkProp.DataType, prop.DataType, prop.Name, prop.ForeignLinkProp.VarName, prop.ForeignProp.PropName)
.AppendLine();
}
classBuilder.AppendLine();
}
}
itemProps.Sort(SortProperty);
foreach (var prop in itemProps)
{
classBuilder.AppendLine(" ''' <summary>");
classBuilder.AppendFormat(" ''' Gets the {0}.", prop.Label.ToLower().Replace("&", "&")).AppendLine();
classBuilder.AppendLine(" ''' </summary>");
classBuilder.AppendFormat(@" <DisplayName(""{0}""), SourceName(""{1}"")", prop.Label, prop.Name);
if (!String.IsNullOrEmpty(prop.List))
{
classBuilder.AppendFormat(@", List(""{0}""", prop.List);
if (!String.IsNullOrEmpty(prop.ListFilter))
{
classBuilder.AppendFormat(@", ""{0}""", prop.ListFilter);
}
if (prop.EbsList)
{
if (String.IsNullOrEmpty(prop.ListFilter)) classBuilder.Append(", ");
classBuilder.Append(", True");
}
classBuilder.Append(")");
}
if (prop.StringLength > 0)
classBuilder.AppendFormat(", StringField({0})", prop.StringLength);
classBuilder.Append(">");
classBuilder.AppendLine();
classBuilder.Append(" ");
if (!polyItem) classBuilder.Append("Public ");
switch (prop.PropType)
{
case ArasProperty.PropTypes.ReadOnly:
classBuilder.AppendFormat("ReadOnly Property {0} As ReadOnlyPropertyValue(Of {1})", prop.PropName, prop.DataType).AppendLine();
break;
case ArasProperty.PropTypes.Foreign:
classBuilder.AppendFormat("ReadOnly Property {0} As IPropertyValue(Of {1})", prop.PropName, prop.DataType).AppendLine();
break;
default:
classBuilder.AppendFormat("ReadOnly Property {0} As PropertyValue(Of {1})", prop.PropName, prop.DataType).AppendLine();
break;
}
if (!polyItem)
{
classBuilder.AppendLine(" Get");
classBuilder.AppendFormat(" Return {0}", prop.VarName).AppendLine();
classBuilder.AppendLine(" End Get");
classBuilder.AppendLine(" End Property");
}
}
classBuilder.AppendLine();
if (polyItem)
{
classBuilder.AppendLine(" End Interface");
}
else
{
if (this.IsBase)
classBuilder.AppendLine(" Public Sub New(ByVal builder As Base.Model.IModelBuilder)");
else
classBuilder.AppendLine(" Public Sub New(ByVal builder As IModelBuilder)");
classBuilder.AppendLine(" MyBase.New(builder)");
classBuilder.AppendLine(" End Sub");
if (this.GetProperties)
{
classBuilder.AppendLine();
classBuilder.AppendLine(" Private _getter As New PropGetter(Me)");
classBuilder.AppendLine(" Protected Overrides Function GetPropertyGetter() As Gentex.Data.Base.Model.IModelPropertyGetter");
classBuilder.AppendLine(" Return _getter");
classBuilder.AppendLine(" End Function");
classBuilder.AppendLine();
classBuilder.AppendLine(" Private Class PropGetter");
classBuilder.AppendLine(" Implements IModelPropertyGetter");
classBuilder.AppendLine();
classBuilder.AppendFormat(" Private _parent As {0}", Strings.StrConv(this.ItemType, VbStrConv.ProperCase).Replace(" ", "")).AppendLine();
classBuilder.AppendLine();
classBuilder.AppendLine(" Public ReadOnly Property SupportsByName As Boolean Implements IModelPropertyGetter.SupportsByName");
classBuilder.AppendLine(" Get");
classBuilder.AppendLine(" Return True");
classBuilder.AppendLine(" End Get");
classBuilder.AppendLine(" End Property");
classBuilder.AppendLine();
classBuilder.AppendFormat(" Public Sub New(parent as {0})", Strings.StrConv(this.ItemType, VbStrConv.ProperCase).Replace(" ", "")).AppendLine();
classBuilder.AppendLine(" _parent = parent");
classBuilder.AppendLine(" End Sub");
classBuilder.AppendLine();
classBuilder.AppendLine(" Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of PropertyValueInfo) Implements System.Collections.Generic.IEnumerable(Of Gentex.Data.Base.Model.PropertyValueInfo).GetEnumerator");
classBuilder.AppendLine(" Dim props As New List(Of Data.Base.Model.PropertyValueInfo)");
itemProps.Sort((x, y) => x.VarName.CompareTo(y.VarName));
foreach (var prop in itemProps)
{
classBuilder.AppendLine(String.Format(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent.{0}, Nothing))", prop.VarName));
}
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._configId, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._generation, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._isCurrent, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._isReleased, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._majorRev, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._minorRev, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._releaseDate, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._supersededDate, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._classification, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._createdBy, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._createdOn, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._currentState, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._effectiveDate, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._lockedBy, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._managedBy, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._modifiedBy, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._modifiedOn, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._notLockable, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._ownedBy, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._permission, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._state, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._team, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._id, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._keyedName, Nothing))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._canDelete, New LazyLoadAttribute(True, False)))");
classBuilder.AppendLine(" props.Add(New Data.Base.Model.PropertyValueInfo(_parent._canUpdate, New LazyLoadAttribute(True, False)))");
classBuilder.AppendLine(" Return props");
classBuilder.AppendLine(" End Function");
classBuilder.AppendLine();
classBuilder.AppendLine(" Public Function ByName(name As String) As Base.Model.PropertyValueInfo Implements Gentex.Data.Base.Model.IModelPropertyGetter.ByName");
classBuilder.AppendLine(" Select Case name");
foreach (var prop in itemProps)
{
classBuilder.AppendLine(String.Format(@" Case ""{0}""", prop.Name));
classBuilder.AppendLine(String.Format(" Return New Data.Base.Model.PropertyValueInfo(_parent.{0}, Nothing)", prop.VarName));
}
classBuilder.AppendLine(" Case Field_ConfigId");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._configId, Nothing)");
classBuilder.AppendLine(" Case Field_Generation");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._generation, Nothing)");
classBuilder.AppendLine(" Case \"is_current\"");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._isCurrent, Nothing)");
classBuilder.AppendLine(" Case \"is_released\"");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._isReleased, Nothing)");
classBuilder.AppendLine(" Case Field_MajorRev");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._majorRev, Nothing)");
classBuilder.AppendLine(" Case Field_MinorRev");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._minorRev, Nothing)");
classBuilder.AppendLine(" Case \"release_date\"");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._releaseDate, Nothing)");
classBuilder.AppendLine(" Case \"superseded_date\"");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._supersededDate, Nothing)");
classBuilder.AppendLine(" Case Field_Classification");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._classification, Nothing)");
classBuilder.AppendLine(" Case \"created_by_id\"");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._createdBy, Nothing)");
classBuilder.AppendLine(" Case \"created_on\"");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._createdOn, Nothing)");
classBuilder.AppendLine(" Case \"current_state\"");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._currentState, Nothing)");
classBuilder.AppendLine(" Case \"effective_date\"");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._effectiveDate, Nothing)");
classBuilder.AppendLine(" Case \"locked_by_id\"");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._lockedBy, Nothing)");
classBuilder.AppendLine(" Case \"managed_by_id\"");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._managedBy, Nothing)");
classBuilder.AppendLine(" Case \"modified_by_id\"");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._modifiedBy, Nothing)");
classBuilder.AppendLine(" Case \"modified_on\"");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._modifiedOn, Nothing)");
classBuilder.AppendLine(" Case \"not_lockable\"");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._notLockable, Nothing)");
classBuilder.AppendLine(" Case \"owned_by_id\"");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._ownedBy, Nothing)");
classBuilder.AppendLine(" Case \"permission_id\"");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._permission, Nothing)");
classBuilder.AppendLine(" Case Field_State");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._state, Nothing)");
classBuilder.AppendLine(" Case \"team_id\"");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._team, Nothing)");
classBuilder.AppendLine(" Case Field_PermissionCanDelete");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._canDelete, New LazyLoadAttribute(True, False))");
classBuilder.AppendLine(" Case Field_PermissionCanUpdate");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._canUpdate, New LazyLoadAttribute(True, False))");
classBuilder.AppendLine(" Case Field_Id");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._id, Nothing)");
classBuilder.AppendLine(" Case Field_KeyedName");
classBuilder.AppendLine(" Return New Data.Base.Model.PropertyValueInfo(_parent._keyedName, Nothing)");
classBuilder.AppendLine(" Case Else");
classBuilder.AppendLine(" Return Nothing");
classBuilder.AppendLine(" End Select");
classBuilder.AppendLine(" End Function");
classBuilder.AppendLine();
classBuilder.AppendLine(" Private Function GetEnumeratorCore() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator");
classBuilder.AppendLine(" Return GetEnumerator()");
classBuilder.AppendLine(" End Function");
classBuilder.AppendLine(" End Class");
}
classBuilder.AppendLine(" End Class");
}
classBuilder.AppendLine("End Namespace");
return classBuilder.ToString();
}
private int SortVariable(ArasProperty x, ArasProperty y)
{
return x.VarName.CompareTo(y.VarName);
}
private int SortProperty(ArasProperty x, ArasProperty y)
{
return x.PropName.CompareTo(y.PropName);
}
private class ArasProperty
{
public enum PropTypes
{
Foreign,
ReadOnly,
Normal
}
public string DataType { get; set; }
public bool EbsList { get; set; }
public ArasProperty ForeignProp { get; set; }
public ArasProperty ForeignLinkProp { get; set; }
public string Label { get; set; }
public string List { get; set; }
public string ListFilter { get; set; }
public string Name { get; set; }
public string PropName { get; set; }
public PropTypes PropType { get; set; }
public bool Required { get; set; }
public int StringLength { get; set; }
public string VarName { get; set; }
private ArasProperty() { }
private static Dictionary<string, ArasProperty> _cache = new Dictionary<string, ArasProperty>();
private static ArasProperty NewProp(string id)
{
ArasProperty prop = null;
if (!_cache.TryGetValue(id, out prop))
{
prop = new ArasProperty();
_cache[id] = prop;
}
return prop;
}
public static async Task<ArasProperty> NewProp(IReadOnlyItem item, IAsyncConnection conn)
{
var prop = NewProp(item.Id());
await prop.Initialize(item, conn);
return prop;
}
public async Task Initialize(IReadOnlyItem item, IAsyncConnection conn)
{
this.Label = item.Property("label").AsString("");
this.Name = item.Property("name").AsString("");
this.Required = item.Property("is_required").AsBoolean(false)
|| item.Property("is_class_required").AsBoolean(false);
this.PropName = LabelToProp(this.Label);
this.VarName = NameToVar(this.Name);
if (string.IsNullOrEmpty(this.PropName))
this.PropName = LabelToProp(this.Name);
if (string.IsNullOrEmpty(this.Label))
this.Label = Strings.StrConv(this.Name.Replace('_', ' '), VbStrConv.ProperCase);
if (item.Property("data_type").Value == "foreign")
{
this.PropType = PropTypes.Foreign;
if (!item.Property("foreign_property").HasValue())
{
var result = await conn.ApplyAsync(@"<AML>
<Item type='Property' action='get' id='@0' select='label,name,is_required,is_class_required,data_type,data_source,readonly,pattern,stored_length,foreign_property(label,name,is_required,is_class_required,data_type,data_source,readonly,pattern,stored_length)'>
</Item>
</AML>", true, true, item.Id()).ToTask();
item = result.AssertItem();
}
ForeignProp = await NewProp(item.Property("foreign_property").AsItem(), conn);
ForeignLinkProp = NewProp(item.Property("data_source").Value);
}
else if (item.Property("readonly").AsBoolean(false))
{
PropType = PropTypes.ReadOnly;
}
else
{
PropType = PropTypes.Normal;
}
if (this.ForeignProp != null)
{
this.DataType = ForeignProp.DataType;
}
else
{
switch (item.Property("data_type").AsString("").ToLowerInvariant())
{
case "decimal":
case "float":
DataType = "Double";
break;
case "date":
DataType = "Date";
break;
case "item":
DataType = Strings.StrConv(item.Property("data_source").KeyedName().Value, VbStrConv.ProperCase)
.Replace(" ", "");
if (item.Property("data_source").Value == "0C8A70AE86AF49AD873F817593F893D4")
{
this.List = item.Property("pattern").AsString("");
this.EbsList = true;
}
break;
case "integer":
DataType = "Integer";
break;
case "boolean":
DataType = "Boolean";
break;
case "list":
case "filter list":
case "mv_list":
DataType = "String";
this.List = item.Property("data_source").AsString("");
this.ListFilter = item.Property("pattern").AsString("");
break;
case "image":
DataType = "Gentex.Drawing.WebLazyImage";
break;
default: //"list", "string", "text"
this.StringLength = item.Property("stored_length").AsInt(-1);
this.DataType = "String";
break;
}
}
}
private string LabelToProp(string label)
{
if (string.IsNullOrEmpty(label))
return null;
var result = new StringBuilder(label.Length);
var chars = label.ToCharArray();
if (!char.IsLetter(chars[0]))
result.Append("P_");
for (var i = 0; i < chars.Length; i++)
{
if (char.IsLetter(chars[i]))
{
if (i == 0 || !char.IsLetter(chars[i-1]))
{
result.Append(char.ToUpperInvariant(chars[i]));
}
else
{
result.Append(char.ToLowerInvariant(chars[i]));
}
}
else if (char.IsDigit(chars[i]))
{
result.Append(chars[i]);
}
}
if (result.Length > 64)
return result.ToString(0, 64);
return result.ToString();
}
private string NameToVar(string label)
{
if (string.IsNullOrEmpty(label))
return null;
var result = new StringBuilder(label.Length);
var chars = label.ToCharArray();
result.Append('_');
for (var i = 0; i < chars.Length; i++)
{
if (char.IsLetter(chars[i]))
{
if (i == 0 || !char.IsLetter(chars[i - 1]))
{
result.Append(char.ToUpperInvariant(chars[i]));
}
else
{
result.Append(char.ToLowerInvariant(chars[i]));
}
}
else if (char.IsDigit(chars[i]))
{
result.Append(chars[i]);
}
}
return result.ToString();
}
public override string ToString()
{
return string.Format("{0} ({1})", this.Name, this.DataType);
}
}
}
}
| 48.770903 | 303 | 0.600343 | [
"MIT"
] | GCAE/InnovatorAdmin | InnovatorAdmin/Scripts/GenerateCtClass.cs | 29,167 | C# |
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace MailChimp.Lists
{
[DataContract]
public class StaticSegmentMembersAddResult
{
/// <summary>
/// the total number of successful updates (will include members already in the segment)
/// </summary>
[DataMember(Name = "success_count")]
public int successCount
{
get;
set;
}
/// <summary>
/// Error information
/// </summary>
[DataMember(Name = "errors")]
public List<ListError> Errors
{
get;
set;
}
}
}
| 22.2 | 96 | 0.531532 | [
"MIT"
] | IDisposable/MailChimp.NET | MailChimp/Lists/StaticSegmentMembersAddResult.cs | 668 | C# |
using FlashpackerFlights.Core.Interfaces.Persistance;
using FlashpackerFlights.Core.Model;
using Solution.Base.Interfaces.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlashpackerFlights.Core.Interfaces.Services
{
public interface ICityService : IBaseEntityService<City>
{
}
}
| 22.882353 | 60 | 0.791774 | [
"MIT"
] | davidikin45/DigitalNomadDave | DND.Core/Interfaces/Services/ICityService.cs | 391 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BikeSharing.Clients.Core.Models.Dashboard
{
public class Trends
{
public string Age1 { get; set; }
public string Age2 { get; set; }
public string AgeRange { get; set; }
public string EntryTime { get; set; }
}
}
| 20.684211 | 53 | 0.648855 | [
"MIT"
] | SowmyaA/DellI | src/BikeSharing.Clients.Core/Models/Dashboard/Trends.cs | 395 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace WzComparerR2.Avatar.Properties {
using System;
/// <summary>
/// 一个强类型的资源类,用于查找本地化的字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 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 (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WzComparerR2.Avatar.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;
}
}
/// <summary>
/// 查找 System.Drawing.Bitmap 类型的本地化资源。
/// </summary>
internal static System.Drawing.Bitmap _lock {
get {
object obj = ResourceManager.GetObject("_lock", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// 查找 System.Drawing.Bitmap 类型的本地化资源。
/// </summary>
internal static System.Drawing.Bitmap arrow_in {
get {
object obj = ResourceManager.GetObject("arrow_in", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// 查找 System.Drawing.Bitmap 类型的本地化资源。
/// </summary>
internal static System.Drawing.Bitmap script_code {
get {
object obj = ResourceManager.GetObject("script_code", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// 查找 System.Drawing.Bitmap 类型的本地化资源。
/// </summary>
internal static System.Drawing.Bitmap user {
get {
object obj = ResourceManager.GetObject("user", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
| 36.778846 | 185 | 0.556863 | [
"MIT"
] | Lapig/WzComparerR2 | WzComparerR2.Avatar/Properties/Resources.Designer.cs | 4,263 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Xml;
using System.Linq;
using ICSharpCode.SharpZipLib.Zip;
using Umbraco.Core;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Packaging;
using umbraco.cms.businesslogic.web;
using umbraco.cms.businesslogic.propertytype;
using umbraco.BusinessLogic;
using System.Diagnostics;
using umbraco.cms.businesslogic.macro;
using umbraco.cms.businesslogic.template;
using umbraco.interfaces;
namespace umbraco.cms.businesslogic.packager
{
/// <summary>
/// The packager is a component which enables sharing of both data and functionality components between different umbraco installations.
///
/// The output is a .umb (a zip compressed file) which contains the exported documents/medias/macroes/documenttypes (etc.)
/// in a Xml document, along with the physical files used (images/usercontrols/xsl documents etc.)
///
/// Partly implemented, import of packages is done, the export is *under construction*.
/// </summary>
/// <remarks>
/// Ruben Verborgh 31/12/2007: I had to change some code, I marked my changes with "DATALAYER".
/// Reason: @@IDENTITY can't be used with the new datalayer.
/// I wasn't able to test the code, since I'm not aware how the code functions.
/// </remarks>
public class Installer
{
private const string PackageServer = "packages.umbraco.org";
private readonly List<string> _unsecureFiles = new List<string>();
private readonly Dictionary<string, string> _conflictingMacroAliases = new Dictionary<string, string>();
private readonly Dictionary<string, string> _conflictingTemplateAliases = new Dictionary<string, string>();
private readonly Dictionary<string, string> _conflictingStyleSheetNames = new Dictionary<string, string>();
private readonly List<string> _binaryFileErrors = new List<string>();
public string Name { get; private set; }
public string Version { get; private set; }
public string Url { get; private set; }
public string License { get; private set; }
public string LicenseUrl { get; private set; }
public string Author { get; private set; }
public string AuthorUrl { get; private set; }
public string ReadMe { get; private set; }
public string Control { get; private set; }
public bool ContainsMacroConflict { get; private set; }
public IDictionary<string, string> ConflictingMacroAliases { get { return _conflictingMacroAliases; } }
public bool ContainsUnsecureFiles { get; private set; }
public List<string> UnsecureFiles { get { return _unsecureFiles; } }
public bool ContainsTemplateConflicts { get; private set; }
public IDictionary<string, string> ConflictingTemplateAliases { get { return _conflictingTemplateAliases; } }
/// <summary>
/// Indicates that the package contains assembly reference errors
/// </summary>
public bool ContainsBinaryFileErrors { get; private set; }
/// <summary>
/// List each assembly reference error
/// </summary>
public List<string> BinaryFileErrors { get { return _binaryFileErrors; } }
/// <summary>
/// Indicates that the package contains legacy property editors
/// </summary>
public bool ContainsLegacyPropertyEditors { get; private set; }
public bool ContainsStyleSheeConflicts { get; private set; }
public IDictionary<string, string> ConflictingStyleSheetNames { get { return _conflictingStyleSheetNames; } }
public int RequirementsMajor { get; private set; }
public int RequirementsMinor { get; private set; }
public int RequirementsPatch { get; private set; }
/// <summary>
/// The xmldocument, describing the contents of a package.
/// </summary>
public XmlDocument Config { get; private set; }
/// <summary>
/// Constructor
/// </summary>
public Installer()
{
ContainsBinaryFileErrors = false;
ContainsTemplateConflicts = false;
ContainsUnsecureFiles = false;
ContainsMacroConflict = false;
ContainsStyleSheeConflicts = false;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="Name">The name of the package</param>
/// <param name="Version">The version of the package</param>
/// <param name="Url">The url to a descriptionpage</param>
/// <param name="License">The license under which the package is released (preferably GPL ;))</param>
/// <param name="LicenseUrl">The url to a licensedescription</param>
/// <param name="Author">The original author of the package</param>
/// <param name="AuthorUrl">The url to the Authors website</param>
/// <param name="RequirementsMajor">Umbraco version major</param>
/// <param name="RequirementsMinor">Umbraco version minor</param>
/// <param name="RequirementsPatch">Umbraco version patch</param>
/// <param name="Readme">The readme text</param>
/// <param name="Control">The name of the usercontrol used to configure the package after install</param>
public Installer(string Name, string Version, string Url, string License, string LicenseUrl, string Author, string AuthorUrl, int RequirementsMajor, int RequirementsMinor, int RequirementsPatch, string Readme, string Control)
{
ContainsBinaryFileErrors = false;
ContainsTemplateConflicts = false;
ContainsUnsecureFiles = false;
ContainsMacroConflict = false;
ContainsStyleSheeConflicts = false;
this.Name = Name;
this.Version = Version;
this.Url = Url;
this.License = License;
this.LicenseUrl = LicenseUrl;
this.RequirementsMajor = RequirementsMajor;
this.RequirementsMinor = RequirementsMinor;
this.RequirementsPatch = RequirementsPatch;
this.Author = Author;
this.AuthorUrl = AuthorUrl;
ReadMe = Readme;
this.Control = Control;
}
#region Public Methods
/// <summary>
/// Imports the specified package
/// </summary>
/// <param name="InputFile">Filename of the umbracopackage</param>
/// <returns></returns>
public string Import(string InputFile)
{
using (DisposableTimer.DebugDuration<Installer>(
() => "Importing package file " + InputFile,
() => "Package file " + InputFile + "imported"))
{
var tempDir = "";
if (File.Exists(IOHelper.MapPath(SystemDirectories.Data + Path.DirectorySeparatorChar + InputFile)))
{
var fi = new FileInfo(IOHelper.MapPath(SystemDirectories.Data + Path.DirectorySeparatorChar + InputFile));
// Check if the file is a valid package
if (fi.Extension.ToLower() == ".umb")
{
try
{
tempDir = UnPack(fi.FullName);
LoadConfig(tempDir);
}
catch (Exception unpackE)
{
throw new Exception("Error unpacking extension...", unpackE);
}
}
else
throw new Exception("Error - file isn't a package (doesn't have a .umb extension). Check if the file automatically got named '.zip' upon download.");
}
else
throw new Exception("Error - file not found. Could find file named '" + IOHelper.MapPath(SystemDirectories.Data + Path.DirectorySeparatorChar + InputFile) + "'");
return tempDir;
}
}
public int CreateManifest(string tempDir, string guid, string repoGuid)
{
//This is the new improved install rutine, which chops up the process into 3 steps, creating the manifest, moving files, and finally handling umb objects
var packName = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/name"));
var packAuthor = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/author/name"));
var packAuthorUrl = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/author/website"));
var packVersion = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/version"));
var packReadme = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/readme"));
var packLicense = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/license "));
var packUrl = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/url "));
var enableSkins = false;
var skinRepoGuid = "";
if (Config.DocumentElement.SelectSingleNode("/umbPackage/enableSkins") != null)
{
var skinNode = Config.DocumentElement.SelectSingleNode("/umbPackage/enableSkins");
enableSkins = bool.Parse(XmlHelper.GetNodeValue(skinNode));
if (skinNode.Attributes["repository"] != null && string.IsNullOrEmpty(skinNode.Attributes["repository"].Value) == false)
skinRepoGuid = skinNode.Attributes["repository"].Value;
}
//Create a new package instance to record all the installed package adds - this is the same format as the created packages has.
//save the package meta data
var insPack = InstalledPackage.MakeNew(packName);
insPack.Data.Author = packAuthor;
insPack.Data.AuthorUrl = packAuthorUrl;
insPack.Data.Version = packVersion;
insPack.Data.Readme = packReadme;
insPack.Data.License = packLicense;
insPack.Data.Url = packUrl;
//skinning
insPack.Data.EnableSkins = enableSkins;
insPack.Data.SkinRepoGuid = string.IsNullOrEmpty(skinRepoGuid) ? Guid.Empty : new Guid(skinRepoGuid);
insPack.Data.PackageGuid = guid; //the package unique key.
insPack.Data.RepositoryGuid = repoGuid; //the repository unique key, if the package is a file install, the repository will not get logged.
insPack.Save();
return insPack.Data.Id;
}
public void InstallFiles(int packageId, string tempDir)
{
using (DisposableTimer.DebugDuration<Installer>(
() => "Installing package files for package id " + packageId + " into temp folder " + tempDir,
() => "Package file installation complete for package id " + packageId))
{
//retrieve the manifest to continue installation
var insPack = InstalledPackage.GetById(packageId);
// Move files
//string virtualBasePath = System.Web.HttpContext.Current.Request.ApplicationPath;
string basePath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
foreach (XmlNode n in Config.DocumentElement.SelectNodes("//file"))
{
//we enclose the whole file-moving to ensure that the entire installer doesn't crash
try
{
var destPath = GetFileName(basePath, XmlHelper.GetNodeValue(n.SelectSingleNode("orgPath")));
var sourceFile = GetFileName(tempDir, XmlHelper.GetNodeValue(n.SelectSingleNode("guid")));
var destFile = GetFileName(destPath, XmlHelper.GetNodeValue(n.SelectSingleNode("orgName")));
// Create the destination directory if it doesn't exist
if (Directory.Exists(destPath) == false)
Directory.CreateDirectory(destPath);
//If a file with this name exists, delete it
else if (File.Exists(destFile))
File.Delete(destFile);
// Move the file
File.Move(sourceFile, destFile);
//PPH log file install
insPack.Data.Files.Add(XmlHelper.GetNodeValue(n.SelectSingleNode("orgPath")) + "/" + XmlHelper.GetNodeValue(n.SelectSingleNode("orgName")));
}
catch (Exception ex)
{
LogHelper.Error<Installer>("Package install error", ex);
}
}
insPack.Save();
}
}
public void InstallBusinessLogic(int packageId, string tempDir)
{
using (DisposableTimer.DebugDuration<Installer>(
() => "Installing business logic for package id " + packageId + " into temp folder " + tempDir,
() => "Package business logic installation complete for package id " + packageId))
{
//retrieve the manifest to continue installation
var insPack = InstalledPackage.GetById(packageId);
//bool saveNeeded = false;
// Get current user, with a fallback
var currentUser = new User(0);
if (string.IsNullOrEmpty(BasePages.UmbracoEnsuredPage.umbracoUserContextID) == false)
{
if (BasePages.UmbracoEnsuredPage.ValidateUserContextID(BasePages.UmbracoEnsuredPage.umbracoUserContextID))
{
currentUser = User.GetCurrent();
}
}
//Xml as XElement which is used with the new PackagingService
var rootElement = Config.DocumentElement.GetXElement();
var packagingService = ApplicationContext.Current.Services.PackagingService;
//Perhaps it would have been a good idea to put the following into methods eh?!?
#region DataTypes
var dataTypeElement = rootElement.Descendants("DataTypes").FirstOrDefault();
if(dataTypeElement != null)
{
var dataTypeDefinitions = packagingService.ImportDataTypeDefinitions(dataTypeElement, currentUser.Id);
foreach (var dataTypeDefinition in dataTypeDefinitions)
{
insPack.Data.DataTypes.Add(dataTypeDefinition.Id.ToString(CultureInfo.InvariantCulture));
}
}
#endregion
#region Languages
var languageItemsElement = rootElement.Descendants("Languages").FirstOrDefault();
if (languageItemsElement != null)
{
var insertedLanguages = packagingService.ImportLanguages(languageItemsElement);
insPack.Data.Languages.AddRange(insertedLanguages.Select(l => l.Id.ToString()));
}
#endregion
#region Dictionary items
var dictionaryItemsElement = rootElement.Descendants("DictionaryItems").FirstOrDefault();
if (dictionaryItemsElement != null)
{
var insertedDictionaryItems = packagingService.ImportDictionaryItems(dictionaryItemsElement);
insPack.Data.DictionaryItems.AddRange(insertedDictionaryItems.Select(d => d.Id.ToString()));
}
#endregion
#region Macros
foreach (XmlNode n in Config.DocumentElement.SelectNodes("//macro"))
{
Macro m = Macro.Import(n);
if (m != null)
{
insPack.Data.Macros.Add(m.Id.ToString(CultureInfo.InvariantCulture));
//saveNeeded = true;
}
}
//if (saveNeeded) { insPack.Save(); saveNeeded = false; }
#endregion
#region Templates
var templateElement = rootElement.Descendants("Templates").FirstOrDefault();
if (templateElement != null)
{
var templates = packagingService.ImportTemplates(templateElement, currentUser.Id);
foreach (var template in templates)
{
insPack.Data.Templates.Add(template.Id.ToString(CultureInfo.InvariantCulture));
}
}
#endregion
#region DocumentTypes
//Check whether the root element is a doc type rather then a complete package
var docTypeElement = rootElement.Name.LocalName.Equals("DocumentType") ||
rootElement.Name.LocalName.Equals("DocumentTypes")
? rootElement
: rootElement.Descendants("DocumentTypes").FirstOrDefault();
if (docTypeElement != null)
{
var contentTypes = packagingService.ImportContentTypes(docTypeElement, currentUser.Id);
foreach (var contentType in contentTypes)
{
insPack.Data.Documenttypes.Add(contentType.Id.ToString(CultureInfo.InvariantCulture));
//saveNeeded = true;
}
}
#endregion
#region Stylesheets
foreach (XmlNode n in Config.DocumentElement.SelectNodes("Stylesheets/Stylesheet"))
{
StyleSheet s = StyleSheet.Import(n, currentUser);
insPack.Data.Stylesheets.Add(s.Id.ToString());
//saveNeeded = true;
}
//if (saveNeeded) { insPack.Save(); saveNeeded = false; }
#endregion
#region Documents
var documentElement = rootElement.Descendants("DocumentSet").FirstOrDefault();
if (documentElement != null)
{
var content = packagingService.ImportContent(documentElement, -1, currentUser.Id);
var firstContentItem = content.First();
insPack.Data.ContentNodeId = firstContentItem.Id.ToString(CultureInfo.InvariantCulture);
}
#endregion
#region Package Actions
foreach (XmlNode n in Config.DocumentElement.SelectNodes("Actions/Action"))
{
if (n.Attributes["undo"] == null || n.Attributes["undo"].Value == "true")
{
insPack.Data.Actions += n.OuterXml;
}
//Run the actions tagged only for 'install'
if (n.Attributes["runat"] != null && n.Attributes["runat"].Value == "install")
{
var alias = n.Attributes["alias"] != null ? n.Attributes["alias"].Value : "";
if (alias.IsNullOrWhiteSpace() == false)
{
PackageAction.RunPackageAction(insPack.Data.Name, alias, n);
}
}
}
#endregion
// Trigger update of Apps / Trees config.
// (These are ApplicationStartupHandlers so just instantiating them will trigger them)
new ApplicationRegistrar();
new ApplicationTreeRegistrar();
insPack.Save();
}
}
/// <summary>
/// Remove the temp installation folder
/// </summary>
/// <param name="packageId"></param>
/// <param name="tempDir"></param>
public void InstallCleanUp(int packageId, string tempDir)
{
if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, true);
}
}
/// <summary>
/// Reads the configuration of the package from the configuration xmldocument
/// </summary>
/// <param name="tempDir">The folder to which the contents of the package is extracted</param>
public void LoadConfig(string tempDir)
{
Config = new XmlDocument();
Config.Load(tempDir + Path.DirectorySeparatorChar + "package.xml");
Name = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/name").FirstChild.Value;
Version = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/version").FirstChild.Value;
Url = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/url").FirstChild.Value;
License = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/license").FirstChild.Value;
LicenseUrl = Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/license").Attributes.GetNamedItem("url").Value;
RequirementsMajor = int.Parse(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/requirements/major").FirstChild.Value);
RequirementsMinor = int.Parse(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/requirements/minor").FirstChild.Value);
RequirementsPatch = int.Parse(Config.DocumentElement.SelectSingleNode("/umbPackage/info/package/requirements/patch").FirstChild.Value);
Author = Config.DocumentElement.SelectSingleNode("/umbPackage/info/author/name").FirstChild.Value;
AuthorUrl = Config.DocumentElement.SelectSingleNode("/umbPackage/info/author/website").FirstChild.Value;
var basePath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
var dllBinFiles = new List<string>();
foreach (XmlNode n in Config.DocumentElement.SelectNodes("//file"))
{
var badFile = false;
var destPath = GetFileName(basePath, XmlHelper.GetNodeValue(n.SelectSingleNode("orgPath")));
var orgName = XmlHelper.GetNodeValue(n.SelectSingleNode("orgName"));
var destFile = GetFileName(destPath, orgName);
if (destPath.ToLower().Contains(IOHelper.DirSepChar + "app_code"))
{
badFile = true;
}
if (destPath.ToLower().Contains(IOHelper.DirSepChar + "bin"))
{
badFile = true;
}
if (destFile.ToLower().EndsWith(".dll"))
{
badFile = true;
dllBinFiles.Add(Path.Combine(tempDir, orgName));
}
if (badFile)
{
ContainsUnsecureFiles = true;
_unsecureFiles.Add(XmlHelper.GetNodeValue(n.SelectSingleNode("orgName")));
}
}
if (ContainsUnsecureFiles)
{
//Now we want to see if the DLLs contain any legacy data types since we want to warn people about that
string[] assemblyErrors;
var assembliesWithReferences = PackageBinaryInspector.ScanAssembliesForTypeReference<IDataType>(tempDir, out assemblyErrors).ToArray();
if (assemblyErrors.Any())
{
ContainsBinaryFileErrors = true;
BinaryFileErrors.AddRange(assemblyErrors);
}
if (assembliesWithReferences.Any())
{
ContainsLegacyPropertyEditors = true;
}
}
//this will check for existing macros with the same alias
//since we will not overwrite on import it's a good idea to inform the user what will be overwritten
foreach (XmlNode n in Config.DocumentElement.SelectNodes("//macro"))
{
var alias = n.SelectSingleNode("alias").InnerText;
if (!string.IsNullOrEmpty(alias))
{
var m = ApplicationContext.Current.Services.MacroService.GetByAlias(alias);
if (m != null)
{
ContainsMacroConflict = true;
if (_conflictingMacroAliases.ContainsKey(m.Name) == false)
{
_conflictingMacroAliases.Add(m.Name, alias);
}
}
}
}
foreach (XmlNode n in Config.DocumentElement.SelectNodes("Templates/Template"))
{
var alias = n.SelectSingleNode("Alias").InnerText;
if (!string.IsNullOrEmpty(alias))
{
var t = Template.GetByAlias(alias);
if (t != null)
{
ContainsTemplateConflicts = true;
if (_conflictingTemplateAliases.ContainsKey(t.Text) == false)
{
_conflictingTemplateAliases.Add(t.Text, alias);
}
}
}
}
foreach (XmlNode n in Config.DocumentElement.SelectNodes("Stylesheets/Stylesheet"))
{
var alias = n.SelectSingleNode("Name").InnerText;
if (!string.IsNullOrEmpty(alias))
{
var s = StyleSheet.GetByName(alias);
if (s != null)
{
ContainsStyleSheeConflicts = true;
if (_conflictingStyleSheetNames.ContainsKey(s.Text) == false)
{
_conflictingStyleSheetNames.Add(s.Text, alias);
}
}
}
}
try
{
ReadMe = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/info/readme"));
}
catch { }
try
{
Control = XmlHelper.GetNodeValue(Config.DocumentElement.SelectSingleNode("/umbPackage/control"));
}
catch { }
}
/// <summary>
/// This uses the old method of fetching and only supports the packages.umbraco.org repository.
/// </summary>
/// <param name="Package"></param>
/// <returns></returns>
public string Fetch(Guid Package)
{
// Check for package directory
if (Directory.Exists(IOHelper.MapPath(SystemDirectories.Packages)) == false)
Directory.CreateDirectory(IOHelper.MapPath(SystemDirectories.Packages));
var wc = new System.Net.WebClient();
wc.DownloadFile(
"http://" + PackageServer + "/fetch?package=" + Package.ToString(),
IOHelper.MapPath(SystemDirectories.Packages + "/" + Package + ".umb"));
return "packages\\" + Package + ".umb";
}
#endregion
#region Private Methods
/// <summary>
/// Gets the name of the file in the specified path.
/// Corrects possible problems with slashes that would result from a simple concatenation.
/// Can also be used to concatenate paths.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="fileName">Name of the file.</param>
/// <returns>The name of the file in the specified path.</returns>
private static string GetFileName(string path, string fileName)
{
// virtual dir support
fileName = IOHelper.FindFile(fileName);
if (path.Contains("[$"))
{
//this is experimental and undocumented...
path = path.Replace("[$UMBRACO]", SystemDirectories.Umbraco);
path = path.Replace("[$UMBRACOCLIENT]", SystemDirectories.UmbracoClient);
path = path.Replace("[$CONFIG]", SystemDirectories.Config);
path = path.Replace("[$DATA]", SystemDirectories.Data);
}
//to support virtual dirs we try to lookup the file...
path = IOHelper.FindFile(path);
Debug.Assert(path != null && path.Length >= 1);
Debug.Assert(fileName != null && fileName.Length >= 1);
path = path.Replace('/', '\\');
fileName = fileName.Replace('/', '\\');
// Does filename start with a slash? Does path end with one?
bool fileNameStartsWithSlash = (fileName[0] == Path.DirectorySeparatorChar);
bool pathEndsWithSlash = (path[path.Length - 1] == Path.DirectorySeparatorChar);
// Path ends with a slash
if (pathEndsWithSlash)
{
if (!fileNameStartsWithSlash)
// No double slash, just concatenate
return path + fileName;
return path + fileName.Substring(1);
}
if (fileNameStartsWithSlash)
// Required slash specified, just concatenate
return path + fileName;
return path + Path.DirectorySeparatorChar + fileName;
}
private static string UnPack(string zipName)
{
// Unzip
//the temp directory will be the package GUID - this keeps it consistent!
//the zipName is always the package Guid.umb
var packageFileName = Path.GetFileNameWithoutExtension(zipName);
var packageId = Guid.NewGuid();
Guid.TryParse(packageFileName, out packageId);
string tempDir = IOHelper.MapPath(SystemDirectories.Data) + Path.DirectorySeparatorChar + packageId.ToString();
//clear the directory if it exists
if (Directory.Exists(tempDir)) Directory.Delete(tempDir, true);
Directory.CreateDirectory(tempDir);
var s = new ZipInputStream(File.OpenRead(zipName));
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string fileName = Path.GetFileName(theEntry.Name);
if (fileName != String.Empty)
{
FileStream streamWriter = File.Create(tempDir + Path.DirectorySeparatorChar + fileName);
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
// Clean up
s.Close();
File.Delete(zipName);
return tempDir;
}
#endregion
}
}
| 45.424501 | 233 | 0.561277 | [
"MIT"
] | AdrianJMartin/Umbraco-CMS | src/umbraco.cms/businesslogic/Packager/Installer.cs | 31,888 | C# |
//-----------------------------------------------------------------------
// <copyright file="BlobWriteStreamBase.cs" company="Microsoft">
// Copyright 2013 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.Blob
{
using Microsoft.WindowsAzure.Storage.Core;
using Microsoft.WindowsAzure.Storage.Core.Util;
using Microsoft.WindowsAzure.Storage.Shared.Protocol;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Text;
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Reviewed.")]
internal abstract class BlobWriteStreamBase :
#if WINDOWS_RT
Stream
#else
CloudBlobStream
#endif
{
protected CloudBlockBlob blockBlob;
protected CloudPageBlob pageBlob;
protected long pageBlobSize;
protected bool newPageBlob;
protected long currentOffset;
protected long currentPageOffset;
protected int streamWriteSizeInBytes;
protected MultiBufferMemoryStream internalBuffer;
protected List<string> blockList;
protected string blockIdPrefix;
protected AccessCondition accessCondition;
protected BlobRequestOptions options;
protected OperationContext operationContext;
protected CounterEvent noPendingWritesEvent;
protected MD5Wrapper blobMD5;
protected MD5Wrapper blockMD5;
protected AsyncSemaphore parallelOperationSemaphore;
protected volatile Exception lastException;
protected volatile bool committed;
protected bool disposed;
/// <summary>
/// Initializes a new instance of the BlobWriteStreamBase class.
/// </summary>
/// <param name="serviceClient">The service client.</param>
/// <param name="accessCondition">An object that represents the access conditions for the blob. If null, no condition is used.</param>
/// <param name="options">An object that specifies additional options for the request.</param>
/// <param name="operationContext">An <see cref="OperationContext" /> object for tracking the current operation.</param>
private BlobWriteStreamBase(CloudBlobClient serviceClient, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
: base()
{
this.internalBuffer = new MultiBufferMemoryStream(serviceClient.BufferManager);
this.currentOffset = 0;
this.accessCondition = accessCondition;
this.options = options;
this.operationContext = operationContext;
this.noPendingWritesEvent = new CounterEvent();
this.blobMD5 = this.options.StoreBlobContentMD5.Value ? new MD5Wrapper() : null;
this.blockMD5 = this.options.UseTransactionalMD5.Value ? new MD5Wrapper() : null;
this.parallelOperationSemaphore = new AsyncSemaphore(options.ParallelOperationThreadCount.Value);
this.lastException = null;
this.committed = false;
this.disposed = false;
}
/// <summary>
/// Initializes a new instance of the BlobWriteStreamBase class for a block blob.
/// </summary>
/// <param name="blockBlob">Blob reference to write to.</param>
/// <param name="accessCondition">An object that represents the access conditions for the blob. If null, no condition is used.</param>
/// <param name="options">An object that specifies additional options for the request.</param>
/// <param name="operationContext">An <see cref="OperationContext"/> object for tracking the current operation.</param>
protected BlobWriteStreamBase(CloudBlockBlob blockBlob, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
: this(blockBlob.ServiceClient, accessCondition, options, operationContext)
{
this.blockBlob = blockBlob;
this.blockList = new List<string>();
this.blockIdPrefix = Guid.NewGuid().ToString("N") + "-";
this.streamWriteSizeInBytes = blockBlob.StreamWriteSizeInBytes;
}
/// <summary>
/// Initializes a new instance of the BlobWriteStreamBase class for a page blob.
/// </summary>
/// <param name="pageBlob">Blob reference to write to.</param>
/// <param name="pageBlobSize">Size of the page blob.</param>
/// <param name="createNew">Use <c>true</c> if the page blob is newly created, <c>false</c> otherwise.</param>
/// <param name="accessCondition">An object that represents the access conditions for the blob. If null, no condition is used.</param>
/// <param name="options">An object that specifies additional options for the request.</param>
/// <param name="operationContext">An <see cref="OperationContext"/> object for tracking the current operation.</param>
protected BlobWriteStreamBase(CloudPageBlob pageBlob, long pageBlobSize, bool createNew, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
: this(pageBlob.ServiceClient, accessCondition, options, operationContext)
{
this.currentPageOffset = 0;
this.pageBlob = pageBlob;
this.pageBlobSize = pageBlobSize;
this.streamWriteSizeInBytes = pageBlob.StreamWriteSizeInBytes;
this.newPageBlob = createNew;
}
protected ICloudBlob Blob
{
get
{
if (this.blockBlob != null)
{
return this.blockBlob;
}
else
{
return this.pageBlob;
}
}
}
/// <summary>
/// Gets a value indicating whether the current stream supports reading.
/// </summary>
public override bool CanRead
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether the current stream supports seeking.
/// </summary>
public override bool CanSeek
{
get
{
return this.pageBlob != null;
}
}
/// <summary>
/// Gets a value indicating whether the current stream supports writing.
/// </summary>
public override bool CanWrite
{
get
{
return true;
}
}
/// <summary>
/// Gets the length in bytes of the stream.
/// </summary>
public override long Length
{
get
{
if (this.pageBlob != null)
{
return this.pageBlobSize;
}
else
{
throw new NotSupportedException();
}
}
}
/// <summary>
/// Gets or sets the position within the current stream.
/// </summary>
public override long Position
{
get
{
return this.currentOffset;
}
set
{
this.Seek(value, SeekOrigin.Begin);
}
}
/// <summary>
/// This operation is not supported in BlobWriteStreamBase.
/// </summary>
/// <param name="buffer">Not used.</param>
/// <param name="offset">Not used.</param>
/// <param name="count">Not used.</param>
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
/// <summary>
/// Calculates the new position within the current stream for a Seek operation.
/// </summary>
/// <param name="offset">A byte offset relative to the origin parameter.</param>
/// <param name="origin">A value of type <c>SeekOrigin</c> indicating the reference
/// point used to obtain the new position.</param>
/// <returns>The new position within the current stream.</returns>
protected long GetNewOffset(long offset, SeekOrigin origin)
{
if (!this.CanSeek)
{
throw new NotSupportedException();
}
if (this.lastException != null)
{
throw this.lastException;
}
long newOffset;
switch (origin)
{
case SeekOrigin.Begin:
newOffset = offset;
break;
case SeekOrigin.Current:
newOffset = this.currentOffset + offset;
break;
case SeekOrigin.End:
newOffset = this.Length + offset;
break;
default:
CommonUtility.ArgumentOutOfRange("origin", origin);
throw new ArgumentOutOfRangeException("origin");
}
CommonUtility.AssertInBounds("offset", newOffset, 0, this.Length);
if ((newOffset % Constants.PageSize) != 0)
{
CommonUtility.ArgumentOutOfRange("offset", offset);
}
return newOffset;
}
/// <summary>
/// This operation is not supported in BlobWriteStreamBase.
/// </summary>
/// <param name="value">Not used.</param>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
/// <summary>
/// Generates a new block ID to be used for PutBlock.
/// </summary>
/// <returns>Base64 encoded block ID</returns>
protected string GetCurrentBlockId()
{
string blockIdSuffix = this.blockList.Count.ToString("D6", CultureInfo.InvariantCulture);
byte[] blockIdInBytes = Encoding.UTF8.GetBytes(this.blockIdPrefix + blockIdSuffix);
return Convert.ToBase64String(blockIdInBytes);
}
/// <summary>
/// Releases the blob resources used by the Stream.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (this.blobMD5 != null)
{
this.blobMD5.Dispose();
this.blobMD5 = null;
}
if (this.blockMD5 != null)
{
this.blockMD5.Dispose();
this.blockMD5 = null;
}
if (this.internalBuffer != null)
{
this.internalBuffer.Dispose();
this.internalBuffer = null;
}
if (this.noPendingWritesEvent != null)
{
this.noPendingWritesEvent.Dispose();
this.noPendingWritesEvent = null;
}
}
base.Dispose(disposing);
}
}
}
| 38.26183 | 192 | 0.573172 | [
"Apache-2.0"
] | asorrin-msft/azure-storage-net | Lib/Common/Blob/BlobWriteStreamBase.cs | 12,131 | C# |
using System;
using NHapi.Base;
using NHapi.Base.Parser;
using NHapi.Base.Model;
using NHapi.Model.V28.Datatype;
using NHapi.Base.Log;
namespace NHapi.Model.V28.Segment{
///<summary>
/// Represents an HL7 DB1 message segment.
/// This segment has the following fields:<ol>
///<li>DB1-1: Set ID - DB1 (SI)</li>
///<li>DB1-2: Disabled Person Code (CWE)</li>
///<li>DB1-3: Disabled Person Identifier (CX)</li>
///<li>DB1-4: Disability Indicator (ID)</li>
///<li>DB1-5: Disability Start Date (DT)</li>
///<li>DB1-6: Disability End Date (DT)</li>
///<li>DB1-7: Disability Return to Work Date (DT)</li>
///<li>DB1-8: Disability Unable to Work Date (DT)</li>
///</ol>
/// The get...() methods return data from individual fields. These methods
/// do not throw exceptions and may therefore have to handle exceptions internally.
/// If an exception is handled internally, it is logged and null is returned.
/// This is not expected to happen - if it does happen this indicates not so much
/// an exceptional circumstance as a bug in the code for this class.
///</summary>
[Serializable]
public class DB1 : AbstractSegment {
/**
* Creates a DB1 (Disability) segment object that belongs to the given
* message.
*/
public DB1(IGroup parent, IModelClassFactory factory) : base(parent,factory) {
IMessage message = Message;
try {
this.add(typeof(SI), true, 1, 4, new System.Object[]{message}, "Set ID - DB1");
this.add(typeof(CWE), false, 1, 0, new System.Object[]{message}, "Disabled Person Code");
this.add(typeof(CX), false, 0, 0, new System.Object[]{message}, "Disabled Person Identifier");
this.add(typeof(ID), false, 1, 1, new System.Object[]{message, 136}, "Disability Indicator");
this.add(typeof(DT), false, 1, 0, new System.Object[]{message}, "Disability Start Date");
this.add(typeof(DT), false, 1, 0, new System.Object[]{message}, "Disability End Date");
this.add(typeof(DT), false, 1, 0, new System.Object[]{message}, "Disability Return to Work Date");
this.add(typeof(DT), false, 1, 0, new System.Object[]{message}, "Disability Unable to Work Date");
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Can't instantiate " + GetType().Name, he);
}
}
///<summary>
/// Returns Set ID - DB1(DB1-1).
///</summary>
public SI SetIDDB1
{
get{
SI ret = null;
try
{
IType t = this.GetField(1, 0);
ret = (SI)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Disabled Person Code(DB1-2).
///</summary>
public CWE DisabledPersonCode
{
get{
CWE ret = null;
try
{
IType t = this.GetField(2, 0);
ret = (CWE)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns a single repetition of Disabled Person Identifier(DB1-3).
/// throws HL7Exception if the repetition number is invalid.
/// <param name="rep">The repetition number (this is a repeating field)</param>
///</summary>
public CX GetDisabledPersonIdentifier(int rep)
{
CX ret = null;
try
{
IType t = this.GetField(3, rep);
ret = (CX)t;
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
///<summary>
/// Returns all repetitions of Disabled Person Identifier (DB1-3).
///</summary>
public CX[] GetDisabledPersonIdentifier() {
CX[] ret = null;
try {
IType[] t = this.GetField(3);
ret = new CX[t.Length];
for (int i = 0; i < ret.Length; i++) {
ret[i] = (CX)t[i];
}
} catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
return ret;
}
///<summary>
/// Returns the total repetitions of Disabled Person Identifier (DB1-3).
///</summary>
public int DisabledPersonIdentifierRepetitionsUsed
{
get{
try {
return GetTotalFieldRepetitionsUsed(3);
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception cce) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce);
throw new System.Exception("An unexpected error ocurred", cce);
}
}
}
///<summary>
/// Returns Disability Indicator(DB1-4).
///</summary>
public ID DisabilityIndicator
{
get{
ID ret = null;
try
{
IType t = this.GetField(4, 0);
ret = (ID)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Disability Start Date(DB1-5).
///</summary>
public DT DisabilityStartDate
{
get{
DT ret = null;
try
{
IType t = this.GetField(5, 0);
ret = (DT)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Disability End Date(DB1-6).
///</summary>
public DT DisabilityEndDate
{
get{
DT ret = null;
try
{
IType t = this.GetField(6, 0);
ret = (DT)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Disability Return to Work Date(DB1-7).
///</summary>
public DT DisabilityReturnToWorkDate
{
get{
DT ret = null;
try
{
IType t = this.GetField(7, 0);
ret = (DT)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
///<summary>
/// Returns Disability Unable to Work Date(DB1-8).
///</summary>
public DT DisabilityUnableToWorkDate
{
get{
DT ret = null;
try
{
IType t = this.GetField(8, 0);
ret = (DT)t;
}
catch (HL7Exception he) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he);
throw new System.Exception("An unexpected error ocurred", he);
} catch (System.Exception ex) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex);
throw new System.Exception("An unexpected error ocurred", ex);
}
return ret;
}
}
}} | 32.97786 | 121 | 0.662638 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | AMCN41R/nHapi | src/NHapi.Model.V28/Segment/DB1.cs | 8,937 | C# |
// /********************************************************
// * *
// * Copyright (C) Microsoft. All rights reserved. *
// * Licensed under the MIT license. *
// * *
// ********************************************************/
namespace System.Reactive.Kql
{
using System.Collections.Generic;
using System.ComponentModel;
[Description("strlen")]
public class StrlenFunction : ScalarFunction
{
/// <summary>
/// Empty constructor supporting Serialization/Deserialization. DO NOT REMOVE
/// </summary>
public StrlenFunction()
{
}
public override object GetValue(IDictionary<string, object> evt)
{
var dict = (IDictionary<string, object>)evt;
var arg = Arguments[0].GetValue(evt).ToString();
return arg.Length;
}
}
} | 33.1 | 90 | 0.437059 | [
"Apache-2.0"
] | 00mjk/KqlTools | Source/Rx.Kql/Functions/StrlenFunction.cs | 995 | C# |
// -----------------------------------------------------------------------
// <copyright file="GetCustomerSkus.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerProducts
{
using System.Globalization;
/// <summary>
/// A scenario that retrieves all the SKUs related to a product that apply to a customer.
/// </summary>
public class GetCustomerSkus : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerSkus"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerSkus(IScenarioContext context) : base("Get skus for customer", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
var customerId = this.ObtainCustomerId("Enter the ID of the corresponding customer");
var productId = this.ObtainProductId("Enter the ID of the corresponding product");
this.Context.ConsoleHelper.StartProgress(string.Format(CultureInfo.InvariantCulture, "Getting skus from product {0} for customer {1}", productId, customerId));
var skus = partnerOperations.Customers.ById(customerId).Products.ById(productId).Skus.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(skus, "Skus for customer");
}
}
}
| 42.219512 | 171 | 0.601386 | [
"MIT"
] | Bhaskers-Blu-Org2/Partner-Center-DotNet-Samples | sdk/SdkSamples/CustomerProducts/GetCustomerSkus.cs | 1,733 | C# |
using System;
namespace ColorHelper
{
public static partial class ColorGenerator
{
public static T GetRandomColor<T>() where T: IColor
{
return GetRandomColor<T>(GetColorFilter(ColorThemesEnum.Default));
}
public static T GetLightRandomColor<T>() where T : IColor
{
return GetRandomColor<T>(GetColorFilter(ColorThemesEnum.Light));
}
public static T GetDarkRandomColor<T>() where T : IColor
{
return GetRandomColor<T>(GetColorFilter(ColorThemesEnum.Dark));
}
public static T GetRandomColorExact<T>(int hashCode, ColorThemesEnum colorTheme = ColorThemesEnum.Default) where T : IColor
{
return GetRandomColorExact<T>(hashCode, GetColorFilter(colorTheme));
}
private static RgbRandomColorFilter GetColorFilter(ColorThemesEnum colorTheme)
{
const byte maxRangeValue = 80;
const byte minRangeValue = 170;
RgbRandomColorFilter filter = new RgbRandomColorFilter();
switch (colorTheme)
{
case ColorThemesEnum.Default:
break;
case ColorThemesEnum.Light:
filter.minR = minRangeValue;
filter.minG = minRangeValue;
filter.minB = minRangeValue;
break;
case ColorThemesEnum.Dark:
filter.maxR = maxRangeValue;
filter.maxG = maxRangeValue;
filter.maxB = maxRangeValue;
break;
}
return filter;
}
private static T GetRandomColor<T>(RgbRandomColorFilter filter) where T : IColor
{
Random random = new Random(DateTime.Now.Millisecond);
return GetRandomColor<T>(filter, random);
}
private static T GetRandomColorExact<T>(int hashCode, RgbRandomColorFilter filter) where T : IColor
{
Random random = new Random(DateTime.Now.Millisecond + hashCode);
return GetRandomColor<T>(filter, random);
}
private static T GetRandomColor<T>(RgbRandomColorFilter filter, Random random) where T : IColor
{
RGB rgb = new RGB(
(byte)random.Next(filter.minR, filter.maxR),
(byte)random.Next(filter.minG, filter.maxG),
(byte)random.Next(filter.minB, filter.maxB));
return ConvertRgbToNecessaryColorType<T>(rgb);
}
private static T ConvertRgbToNecessaryColorType<T>(RGB rgb) where T: IColor
{
if (typeof(T) == typeof(RGB))
{
return (T)(object)rgb;
}
else if (typeof(T) == typeof(HEX))
{
return (T)(object)ColorConverter.RgbToHex(rgb);
}
else if (typeof(T) == typeof(CMYK))
{
return (T)(object)ColorConverter.RgbToCmyk(rgb);
}
else if (typeof(T) == typeof(HSV))
{
return (T)(object)ColorConverter.RgbToHsv(rgb);
}
else if (typeof(T) == typeof(HSL))
{
return (T)(object)ColorConverter.RgbToHsl(rgb);
}
else if (typeof(T) == typeof(XYZ))
{
return (T)(object)ColorConverter.RgbToXyz(rgb);
}
else
{
throw new ArgumentException("Incorrect class type");
}
}
}
}
| 33.314815 | 131 | 0.538633 | [
"MIT"
] | DenisMtfl/ColorHelper | ColorHelper/Generator/ColorGenerator.cs | 3,600 | C# |
using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Input;
using Snap.Core.DependencyInjection;
using Snap.Net.Afdian;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Input;
namespace DGP.Genshin.ViewModel
{
[ViewModel(InjectAs.Transient)]
internal class SponsorViewModel : ObservableObject
{
private const string UserId = "8f9ed3e87f4911ebacb652540025c377";
private const string Token = "Th98JamKvc5FHYyErgM4d6spAXGVwbPD";
private List<Sponsor>? sponsors;
public List<Sponsor>? Sponsors
{
get => sponsors;
set => SetProperty(ref sponsors, value);
}
public ICommand OpenUICommand { get; }
public SponsorViewModel()
{
OpenUICommand = new AsyncRelayCommand(OpenUIAsync);
}
private async Task OpenUIAsync()
{
int currentPage = 1;
List<Sponsor> result = new();
Response<ListWrapper<Sponsor>>? response;
do
{
response = await new AfdianProvider(UserId, Token).QuerySponsorAsync(currentPage++);
if (response?.Data?.List is List<Sponsor> part)
{
result.AddRange(part);
}
}
while (response?.Data?.TotalPage >= currentPage);
Sponsors = result;
}
}
}
| 28.313725 | 100 | 0.59903 | [
"MIT"
] | uranium2333/Snap.Genshin | DGP.Genshin/ViewModel/SponsorViewModel.cs | 1,446 | C# |
// Copyright (c) 2012 Markus Jarderot
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
using System;
namespace AndroidXml.Res
{
/// <summary>
/// Not sure this class is correct, since the original code dealing
/// with this is pretty cryptic.
/// TODO: Check this, and remove this comment.
/// </summary>
#if !NETSTANDARD1_3
[Serializable]
#endif
public class ResTable_map
{
public ResTable_ref Name { get; set; }
public Res_value Value { get; set; }
public MapMetaAttributes? MetaName
{
get
{
var ident = (MapMetaAttributes?) Name.Ident;
switch (ident)
{
case MapMetaAttributes.ATTR_TYPE:
case MapMetaAttributes.ATTR_MIN:
case MapMetaAttributes.ATTR_MAX:
case MapMetaAttributes.ATTR_L10N:
case MapMetaAttributes.ATTR_OTHER:
case MapMetaAttributes.ATTR_ZERO:
case MapMetaAttributes.ATTR_ONE:
case MapMetaAttributes.ATTR_TWO:
case MapMetaAttributes.ATTR_FEW:
case MapMetaAttributes.ATTR_MANY:
return ident;
default:
return null;
}
}
set
{
if (value != null)
{
Name.Ident = (uint) value.Value;
}
else if (MetaName != null)
{
Name.Ident = 0;
}
}
}
public MapAllowedTypes? AllowedTypes
{
get
{
if (MetaName != MapMetaAttributes.ATTR_TYPE) return null;
return (MapAllowedTypes?) Value.RawData;
}
set
{
if (MetaName != MapMetaAttributes.ATTR_TYPE)
{
throw new InvalidOperationException(
"Can't set AllowedTypes unless MetaName is ATTR_TYPE (0x01000000)");
}
if (value == null)
{
throw new ArgumentNullException("value");
}
Value.RawData = (uint) value.Value;
}
}
public MapL10N? L10N
{
get
{
if (MetaName != MapMetaAttributes.ATTR_L10N) return null;
return (MapL10N?) Value.RawData;
}
set
{
if (MetaName != MapMetaAttributes.ATTR_L10N)
{
throw new InvalidOperationException(
"Can't set L10N unless MetaName is ATTR_L10N (0x01000003)");
}
if (value == null)
{
throw new ArgumentNullException("value");
}
Value.RawData = (uint) value.Value;
}
}
}
public enum MapMetaAttributes
{
ATTR_TYPE = 0x01000000,
ATTR_MIN = 0x01000001,
ATTR_MAX = 0x01000002,
ATTR_L10N = 0x01000003,
ATTR_OTHER = 0x01000004,
ATTR_ZERO = 0x01000005,
ATTR_ONE = 0x01000006,
ATTR_TWO = 0x01000007,
ATTR_FEW = 0x01000008,
ATTR_MANY = 0x01000009
}
[Flags]
public enum MapAllowedTypes
{
TYPE_ANY = 0x0000FFFF,
TYPE_REFERENCE = 1 << 0,
TYPE_STRING = 1 << 1,
TYPE_INTEGER = 1 << 2,
TYPE_BOOLEAN = 1 << 3,
TYPE_COLOR = 1 << 4,
TYPE_FLOAT = 1 << 5,
TYPE_DIMENSION = 1 << 6,
TYPE_FRACTION = 1 << 7,
TYPE_ENUM = 1 << 16,
TYPE_FLAGS = 1 << 17
}
public enum MapL10N
{
L10N_NOT_REQUIRED = 0,
L10N_SUGGESTED = 1
}
} | 28.978261 | 92 | 0.473868 | [
"Apache-2.0"
] | Ticomware/AstoriaUWP | AndroidXmlBackup/Res/ResTable_map.cs | 4,001 | C# |
namespace Dfc.CourseDirectory.FindACourseApi.Features.CourseRunDetail
{
public class RegionViewModel
{
public string RegionId { get; set; }
public string Name { get; set; }
}
}
| 22.888889 | 70 | 0.669903 | [
"MIT"
] | SkillsFundingAgency/dfc-coursedirectory | src/Dfc.CourseDirectory.FindACourseApi/Features/CourseRunDetail/RegionViewModel.cs | 208 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DualMonitor.Controls;
using System.Drawing;
namespace DualMonitor.Entities
{
public class ProcessGroup : List<BaseTaskbarButton>
{
public Rectangle GetBounds()
{
var buttons = this.Where(tb => tb.Visible);
return new Rectangle(
buttons.Min(tb => tb.Left),
buttons.Min(tb => tb.Top),
buttons.Max(tb => tb.Right) - buttons.Min(tb => tb.Left),
buttons.Max(tb => tb.Bottom) - buttons.Min(tb => tb.Top));
}
public int GetFirstIndex(System.Windows.Forms.Control.ControlCollection controlCollection)
{
return this.Min(tb => controlCollection.GetChildIndex(tb));
}
public int GetLastIndex(System.Windows.Forms.Control.ControlCollection controlCollection)
{
return this.Max(tb => controlCollection.GetChildIndex(tb));
}
public void Arrange(System.Windows.Forms.Control.ControlCollection controlCollection, int index)
{
this.Sort((x, y) => x.AddedToTaskbar.CompareTo(y.AddedToTaskbar));
foreach (var item in this)
{
controlCollection.SetChildIndex(item, index);
index++;
}
}
public TaskbarPinnedButton GetPinnedButton()
{
return this.Find(tb => tb is TaskbarPinnedButton) as TaskbarPinnedButton;
}
}
}
| 31.163265 | 104 | 0.600524 | [
"MIT"
] | zhanghb1994/DualMonitorTaskbar | DualMonitorSolution/Entities/ProcessGroup.cs | 1,529 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Core.Entities
{
public class Customer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Contact { get; set; }
public string Email { get; set; }
public DateTime DateOfBirth { get; set; }
}
}
| 23.526316 | 49 | 0.635347 | [
"MIT"
] | mirusser/Learning-dontNet | src/RepoPatternRedisHangfireDemo/Core/Entities/Customer.cs | 449 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Nop.Core;
using Nop.Core.Caching;
using Nop.Core.Data;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Security;
using Nop.Services.Events;
namespace Nop.Services.Security
{
/// <summary>
/// ACL service
/// </summary>
public partial class AclService : IAclService
{
#region Constants
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : entity ID
/// {1} : entity name
/// </remarks>
private const string ACLRECORD_BY_ENTITYID_NAME_KEY = "Nop.aclrecord.entityid-name-{0}-{1}";
/// <summary>
/// Key pattern to clear cache
/// </summary>
private const string ACLRECORD_PATTERN_KEY = "Nop.aclrecord.";
#endregion
#region Fields
private readonly IRepository<AclRecord> _aclRecordRepository;
private readonly IWorkContext _workContext;
private readonly ICacheManager _cacheManager;
private readonly IEventPublisher _eventPublisher;
private readonly CatalogSettings _catalogSettings;
#endregion
#region Ctor
/// <summary>
/// Ctor
/// </summary>
/// <param name="cacheManager">Cache manager</param>
/// <param name="workContext">Work context</param>
/// <param name="aclRecordRepository">ACL record repository</param>
/// <param name="catalogSettings">Catalog settings</param>
/// <param name="eventPublisher">Event publisher</param>
public AclService(ICacheManager cacheManager,
IWorkContext workContext,
IRepository<AclRecord> aclRecordRepository,
IEventPublisher eventPublisher,
CatalogSettings catalogSettings)
{
this._cacheManager = cacheManager;
this._workContext = workContext;
this._aclRecordRepository = aclRecordRepository;
this._eventPublisher = eventPublisher;
this._catalogSettings = catalogSettings;
}
#endregion
#region Methods
/// <summary>
/// Deletes an ACL record
/// </summary>
/// <param name="aclRecord">ACL record</param>
public virtual void DeleteAclRecord(AclRecord aclRecord)
{
if (aclRecord == null)
throw new ArgumentNullException("aclRecord");
_aclRecordRepository.Delete(aclRecord);
//cache
_cacheManager.RemoveByPattern(ACLRECORD_PATTERN_KEY);
//event notification
_eventPublisher.EntityDeleted(aclRecord);
}
/// <summary>
/// Gets an ACL record
/// </summary>
/// <param name="aclRecordId">ACL record identifier</param>
/// <returns>ACL record</returns>
public virtual AclRecord GetAclRecordById(int aclRecordId)
{
if (aclRecordId == 0)
return null;
return _aclRecordRepository.GetById(aclRecordId);
}
/// <summary>
/// Gets ACL records
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="entity">Entity</param>
/// <returns>ACL records</returns>
public virtual IList<AclRecord> GetAclRecords<T>(T entity) where T : BaseEntity, IAclSupported
{
if (entity == null)
throw new ArgumentNullException("entity");
int entityId = entity.Id;
string entityName = typeof(T).Name;
var query = from ur in _aclRecordRepository.Table
where ur.EntityId == entityId &&
ur.EntityName == entityName
select ur;
var aclRecords = query.ToList();
return aclRecords;
}
/// <summary>
/// Inserts an ACL record
/// </summary>
/// <param name="aclRecord">ACL record</param>
public virtual void InsertAclRecord(AclRecord aclRecord)
{
if (aclRecord == null)
throw new ArgumentNullException("aclRecord");
_aclRecordRepository.Insert(aclRecord);
//cache
_cacheManager.RemoveByPattern(ACLRECORD_PATTERN_KEY);
//event notification
_eventPublisher.EntityInserted(aclRecord);
}
/// <summary>
/// Inserts an ACL record
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="customerRoleId">Customer role id</param>
/// <param name="entity">Entity</param>
public virtual void InsertAclRecord<T>(T entity, int customerRoleId) where T : BaseEntity, IAclSupported
{
if (entity == null)
throw new ArgumentNullException("entity");
if (customerRoleId == 0)
throw new ArgumentOutOfRangeException("customerRoleId");
int entityId = entity.Id;
string entityName = typeof(T).Name;
var aclRecord = new AclRecord
{
EntityId = entityId,
EntityName = entityName,
CustomerRoleId = customerRoleId
};
InsertAclRecord(aclRecord);
}
/// <summary>
/// Updates the ACL record
/// </summary>
/// <param name="aclRecord">ACL record</param>
public virtual void UpdateAclRecord(AclRecord aclRecord)
{
if (aclRecord == null)
throw new ArgumentNullException("aclRecord");
_aclRecordRepository.Update(aclRecord);
//cache
_cacheManager.RemoveByPattern(ACLRECORD_PATTERN_KEY);
//event notification
_eventPublisher.EntityUpdated(aclRecord);
}
/// <summary>
/// Find customer role identifiers with granted access
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="entity">Wntity</param>
/// <returns>Customer role identifiers</returns>
public virtual int[] GetCustomerRoleIdsWithAccess<T>(T entity) where T : BaseEntity, IAclSupported
{
if (entity == null)
throw new ArgumentNullException("entity");
int entityId = entity.Id;
string entityName = typeof(T).Name;
string key = string.Format(ACLRECORD_BY_ENTITYID_NAME_KEY, entityId, entityName);
return _cacheManager.Get(key, () =>
{
var query = from ur in _aclRecordRepository.Table
where ur.EntityId == entityId &&
ur.EntityName == entityName
select ur.CustomerRoleId;
return query.ToArray();
});
}
/// <summary>
/// Authorize ACL permission
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="entity">Wntity</param>
/// <returns>true - authorized; otherwise, false</returns>
public virtual bool Authorize<T>(T entity) where T : BaseEntity, IAclSupported
{
return Authorize(entity, _workContext.CurrentCustomer);
}
/// <summary>
/// Authorize ACL permission
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="entity">Wntity</param>
/// <param name="customer">Customer</param>
/// <returns>true - authorized; otherwise, false</returns>
public virtual bool Authorize<T>(T entity, Customer customer) where T : BaseEntity, IAclSupported
{
if (entity == null)
return false;
if (customer == null)
return false;
if (_catalogSettings.IgnoreAcl)
return true;
if (!entity.SubjectToAcl)
return true;
foreach (var role1 in customer.CustomerRoles.Where(cr => cr.Active))
foreach (var role2Id in GetCustomerRoleIdsWithAccess(entity))
if (role1.Id == role2Id)
//yes, we have such permission
return true;
//no permission found
return false;
}
#endregion
}
} | 32.77907 | 112 | 0.561547 | [
"MIT"
] | andri0331/cetaku | Libraries/Nop.Services/Security/AclService.cs | 8,457 | C# |
using System;
namespace EasyNetQ
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
public class QueueAttribute : Attribute
{
internal static readonly QueueAttribute Default = new QueueAttribute(null);
public QueueAttribute(string queueName)
{
QueueName = queueName ?? string.Empty;
}
public string QueueName { get; }
public string ExchangeName { get; set; }
}
}
| 24.35 | 96 | 0.661191 | [
"MIT"
] | LegitSecurity/EasyNetQ | Source/EasyNetQ/QueueAttribute.cs | 487 | C# |
using System;
namespace FactoryPattern
{
public class Circle : IShape
{
public void Draw()
{
Console.WriteLine("Drawing a circle");
}
}
}
| 14.461538 | 50 | 0.537234 | [
"MIT"
] | Divya1384/designpatterns | Creational/FactoryPattern/Circle.cs | 190 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Tizen.NUI
{
internal static partial class Interop
{
internal static partial class WidgetImpl
{
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_WidgetImpl_SWIGUpcast")]
public static extern global::System.IntPtr WidgetImpl_SWIGUpcast(global::System.IntPtr jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_WidgetImpl_New")]
public static extern global::System.IntPtr WidgetImpl_New();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_WidgetImpl_OnCreate")]
public static extern void WidgetImpl_OnCreate(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2, global::System.Runtime.InteropServices.HandleRef jarg3);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_WidgetImpl_OnCreateSwigExplicitWidgetImpl")]
public static extern void WidgetImpl_OnCreateSwigExplicitWidgetImpl(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2, global::System.Runtime.InteropServices.HandleRef jarg3);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_WidgetImpl_OnTerminate")]
public static extern void WidgetImpl_OnTerminate(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2, int jarg3);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_WidgetImpl_OnTerminateSwigExplicitWidgetImpl")]
public static extern void WidgetImpl_OnTerminateSwigExplicitWidgetImpl(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2, int jarg3);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_WidgetImpl_OnPause")]
public static extern void WidgetImpl_OnPause(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_WidgetImpl_OnPauseSwigExplicitWidgetImpl")]
public static extern void WidgetImpl_OnPauseSwigExplicitWidgetImpl(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_WidgetImpl_OnResume")]
public static extern void WidgetImpl_OnResume(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_WidgetImpl_OnResumeSwigExplicitWidgetImpl")]
public static extern void WidgetImpl_OnResumeSwigExplicitWidgetImpl(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_WidgetImpl_OnResize")]
public static extern void WidgetImpl_OnResize(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_WidgetImpl_OnResizeSwigExplicitWidgetImpl")]
public static extern void WidgetImpl_OnResizeSwigExplicitWidgetImpl(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_WidgetImpl_OnUpdate")]
public static extern void WidgetImpl_OnUpdate(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2, int jarg3);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_WidgetImpl_OnUpdateSwigExplicitWidgetImpl")]
public static extern void WidgetImpl_OnUpdateSwigExplicitWidgetImpl(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2, int jarg3);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_WidgetImpl_SignalConnected")]
public static extern void WidgetImpl_SignalConnected(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2, global::System.Runtime.InteropServices.HandleRef jarg3);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_WidgetImpl_SignalConnectedSwigExplicitWidgetImpl")]
public static extern void WidgetImpl_SignalConnectedSwigExplicitWidgetImpl(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2, global::System.Runtime.InteropServices.HandleRef jarg3);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_WidgetImpl_SignalDisconnected")]
public static extern void WidgetImpl_SignalDisconnected(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2, global::System.Runtime.InteropServices.HandleRef jarg3);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_WidgetImpl_SignalDisconnectedSwigExplicitWidgetImpl")]
public static extern void WidgetImpl_SignalDisconnectedSwigExplicitWidgetImpl(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2, global::System.Runtime.InteropServices.HandleRef jarg3);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_WidgetImpl_SetContentInfo")]
public static extern void WidgetImpl_SetContentInfo(global::System.Runtime.InteropServices.HandleRef jarg1, string jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_WidgetImpl_SetImpl")]
public static extern void WidgetImpl_SetImpl(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_WidgetImpl_director_connect")]
public static extern void WidgetImpl_director_connect(global::System.Runtime.InteropServices.HandleRef jarg1, Tizen.NUI.WidgetImpl.SwigDelegateWidgetImpl_0 delegate0, Tizen.NUI.WidgetImpl.SwigDelegateWidgetImpl_1 delegate1,
Tizen.NUI.WidgetImpl.SwigDelegateWidgetImpl_2 delegate2, Tizen.NUI.WidgetImpl.SwigDelegateWidgetImpl_3 delegate3, Tizen.NUI.WidgetImpl.SwigDelegateWidgetImpl_4 delegate4, Tizen.NUI.WidgetImpl.SwigDelegateWidgetImpl_5 delegate5,
Tizen.NUI.WidgetImpl.SwigDelegateWidgetImpl_6 delegate6, Tizen.NUI.WidgetImpl.SwigDelegateWidgetImpl_7 delegate7);
}
}
}
| 72.454545 | 258 | 0.788234 | [
"Apache-2.0"
] | dalinui/TizenFX | src/Tizen.NUI/src/internal/Interop/Interop.WidgetImpl.cs | 7,175 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
namespace MvcCustomRouting.Mvc
{
public static class FeatureRoutingExtensions
{
public static ControllerActionEndpointConventionBuilder MapFeatureControllerRoute(
this IEndpointRouteBuilder endpoints,
string name,
string pattern,
object defaults = null,
object constraints = null,
object dataTokens = null)
{
if (endpoints == null)
{
throw new ArgumentNullException(nameof(endpoints));
}
//EnsureControllerServices(endpoints);
var dataSource = GetOrCreateDataSource(endpoints);
return dataSource.AddRoute(
name,
pattern,
new RouteValueDictionary(defaults),
new RouteValueDictionary(constraints),
new RouteValueDictionary(dataTokens));
}
private static ControllerActionEndpointDataSource GetOrCreateDataSource(IEndpointRouteBuilder endpoints)
{
var dataSource = endpoints.DataSources.OfType<ControllerActionEndpointDataSource>().FirstOrDefault();
if (dataSource == null)
{
dataSource = endpoints.ServiceProvider.GetRequiredService<ControllerActionEndpointDataSource>();
endpoints.DataSources.Add(dataSource);
}
//var dataSource = endpoints.ServiceProvider.GetRequiredService<ControllerActionEndpointDataSource>();
//endpoints.DataSources.Add(dataSource);
return dataSource;
}
}
}
| 35.08 | 114 | 0.63854 | [
"MIT"
] | jasselin/MvcCustomRouting | MvcCustomRouting/Mvc/FeatureRoutingExtensions.cs | 1,756 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Biba.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.16129 | 151 | 0.578848 | [
"MIT"
] | W-angler/Biba | Biba/Properties/Settings.Designer.cs | 1,061 | C# |
/* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2021 Ingo Herbote
* https://www.yetanotherforum.net/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* 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.
*/
namespace YAF.Dialogs
{
#region Using
using System;
using YAF.Core.BaseControls;
using YAF.Core.Extensions;
using YAF.Core.Helpers;
using YAF.Core.Model;
using YAF.Core.Services;
using YAF.Core.Utilities;
using YAF.Types;
using YAF.Types.Constants;
using YAF.Types.Extensions;
using YAF.Types.Interfaces;
using YAF.Types.Models;
#endregion
/// <summary>
/// The Admin Replace Words Add/Edit Dialog.
/// </summary>
public partial class ReplaceWordsEdit : BaseUserControl
{
#region Methods
/// <summary>
/// Gets or sets the spam word identifier.
/// </summary>
/// <value>
/// The spam word identifier.
/// </value>
public int? ReplaceWordId
{
get => this.ViewState["ReplaceWordId"].ToType<int?>();
set => this.ViewState["ReplaceWordId"] = value;
}
/// <summary>
/// Binds the data.
/// </summary>
/// <param name="replaceWordId">The replace word identifier.</param>
public void BindData(int? replaceWordId)
{
this.ReplaceWordId = replaceWordId;
this.Title.LocalizedPage = "ADMIN_REPLACEWORDS_EDIT";
this.Save.TextLocalizedPage = "ADMIN_REPLACEWORDS";
if (this.ReplaceWordId.HasValue)
{
// Edit
var replaceWord = this.GetRepository<Replace_Words>().GetById(this.ReplaceWordId.Value);
this.badword.Text = replaceWord.BadWord;
this.goodword.Text = replaceWord.GoodWord;
this.Title.LocalizedTag = "TITLE_EDIT";
this.Save.TextLocalizedTag = "SAVE";
}
else
{
// Add
this.badword.Text = string.Empty;
this.goodword.Text = string.Empty;
this.Title.LocalizedTag = "TITLE";
this.Save.TextLocalizedTag = "ADD";
}
}
/// <summary>
/// The page_ load.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e)
{
if (!this.IsPostBack)
{
return;
}
this.PageContext.PageElements.RegisterJsBlockStartup(
"loadValidatorFormJs",
JavaScriptBlocks.FormValidatorJs(this.Save.ClientID));
}
/// <summary>
/// Handles the Click event of the Add control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
protected void Save_OnClick([NotNull] object sender, [NotNull] EventArgs e)
{
if (!this.Page.IsValid)
{
return;
}
if (!ValidationHelper.IsValidRegex(this.badword.Text.Trim()))
{
this.PageContext.AddLoadMessage(
this.GetText("ADMIN_REPLACEWORDS_EDIT", "MSG_REGEX_BAD"),
MessageTypes.warning);
this.PageContext.PageElements.RegisterJsBlockStartup(
"openModalJs",
JavaScriptBlocks.OpenModalJs("ReplaceWordsEditDialog"));
return;
}
this.GetRepository<Replace_Words>()
.Save(
this.ReplaceWordId,
this.badword.Text,
this.goodword.Text);
this.Get<LinkBuilder>().Redirect(ForumPages.Admin_ReplaceWords);
}
#endregion
}
} | 32.296774 | 105 | 0.554535 | [
"Apache-2.0"
] | Spinks90/YAFNET | yafsrc/YetAnotherForum.NET/Dialogs/ReplaceWordsEdit.ascx.cs | 4,855 | C# |
using System;
namespace Alturos.Yolo.Model
{
internal class YoloTrackingItemExtended : YoloItem
{
public string ObjectId { get; }
public int ProcessIndex { get; set; }
public double TrackingConfidence { get; private set; }
public YoloTrackingItemExtended(YoloItem item, string objectId)
{
ObjectId = objectId;
Type = item.Type;
Confidence = item.Confidence;
X = item.X;
Y = item.Y;
Width = item.Width;
Height = item.Height;
}
public void IncreaseTrackingConfidence()
{
if (TrackingConfidence < 100)
{
TrackingConfidence += 5;
}
}
public void DecreaseTrackingConfidence()
{
if (TrackingConfidence > 0)
{
TrackingConfidence -= 5;
}
}
}
}
| 22.571429 | 71 | 0.504219 | [
"MIT"
] | AlgirdasKartavicius/Yolo.Net | src/Alturos.Yolo/Model/YoloTrackingItemExtended.cs | 950 | C# |
using System.Globalization;
using IbanNet.Registry.Patterns;
namespace IbanNet.Registry.Swift
{
public class SwiftPatternTokenizerTests
{
private readonly SwiftPatternTokenizer _sut;
public SwiftPatternTokenizerTests()
{
_sut = new SwiftPatternTokenizer();
}
#if !USE_SPANS
[Fact]
public void Given_null_input_when_tokenizing_it_should_throw()
{
char[] input = null;
// Act
// ReSharper disable once IteratorMethodResultIsIgnored
// ReSharper disable once AssignNullToNotNullAttribute
Action act = () => _sut.Tokenize(input);
// Assert
act.Should()
.ThrowExactly<ArgumentNullException>()
.Which.ParamName.Should()
.Be(nameof(input));
}
#endif
[Theory]
[InlineData("2!n", "12", true)]
[InlineData("3!n", "1234", false)]
[InlineData("2!n", "1A", false)]
[InlineData("2n", "", false)]
[InlineData("2n", "1", true)]
[InlineData("2n", "12", true)]
[InlineData("2n", "123", false)]
[InlineData("8n6a", "AB", false)]
[InlineData("1!a", "A", true)]
[InlineData("1!a1!n", "A1", true)]
[InlineData("3!c", "d1F", true)]
[InlineData("2!n", "@#", false)]
[InlineData("2!n3!a2!c", "12ABCe1", true)]
[InlineData("2n3a2c", "12ABCe1", true)]
[InlineData("2n3!a2c", "12123e1", false)]
[InlineData("2n3a2c", "12123e1", false)]
[InlineData("2n3a3!c", "", false)]
[InlineData("2n3a", "12ABCD", false)]
public void Given_valid_pattern_without_countryCode_it_should_decompose_into_tests(string pattern, string value, bool expectedResult)
{
// Act
var validator = new PatternValidator(new FakePattern(_sut.Tokenize(pattern)));
bool result = validator.Validate(value);
// Assert
result.Should().Be(expectedResult);
}
[Theory]
[InlineData("A", "A", 0)]
[InlineData("2z", "2z", 0)]
[InlineData("2!n2z", "2z", 1)]
public void Given_invalid_pattern_when_tokenizing_it_should_throw(string pattern, string token, int pos)
{
// Act
Action act = () => _sut.Tokenize(pattern);
// Assert
act.Should()
.ThrowExactly<PatternException>()
.WithMessage(string.Format(CultureInfo.CurrentCulture, Resources.ArgumentException_The_structure_segment_0_is_invalid, token, pos) + "*")
.Which.InnerException.Should()
.BeNull();
}
}
}
| 33.580247 | 153 | 0.559926 | [
"Apache-2.0"
] | French-Coders-Organization/IbanNet | test/IbanNet.Tests/Registry/Swift/SwiftPatternTokenizerTests.cs | 2,722 | C# |
using System.Net;
namespace Payabbhi.Error
{
public class SignatureVerificationError : BaseError
{
public SignatureVerificationError(string description, string field, PayabbhiResponse payabbhiResponse, HttpStatusCode httpStatusCode = HttpStatusCode.Unused)
:base(description, field, payabbhiResponse, httpStatusCode){}
}
}
| 32.363636 | 165 | 0.764045 | [
"MIT"
] | paypermint/payabbhi-dotnet-1 | src/Errors/SignatureVerificationError.cs | 356 | C# |
using CreateVmSample.Common;
using Microsoft.Azure.Management.Profiles.hybrid_2019_03_01.Compute;
using Microsoft.Azure.Management.Profiles.hybrid_2019_03_01.Network;
using Microsoft.Azure.Management.Profiles.hybrid_2019_03_01.ResourceManager;
using Microsoft.Azure.Management.Profiles.hybrid_2019_03_01.ResourceManager.Models;
using Microsoft.Rest.Azure;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace CreateVmSample
{
class Program
{
static void Main(string[] args)
{
// Tenant Id of DBE
// For DBE tenant id is same for all devices
var tenantId = "c0257de7-538f-415c-993a-1b87a031879d";
// User Name
// To make a ARM connection with DBE, the user name is constant
var userName = "EdgeArmUser";
// User Password
// To make a ARM connection with DBE, the password for the above user
// TODO: Please replace this value with the appropriate value for your device.
var password = "Password1";
// Arm Subscription Id
// After the device is registered with the portal. Arm on the device will be configured.
// You can run Get-ArmSubscriptionId to get the local device arm subscription Id.
// Or you can make a Cloud Managed Rest Call to retrive this value.
var localArmSubscriptionId = "383843f2-12f2-4231-9bef-77598b1eb610";
// Location
// For DBE the location is fixed, dbelocal
var location = "dbelocal";
// Appliance machine name or host name
// you can get this value from the DBE local use
var hostName = "<ApplianceName>";
// Local Arm Authority URL
// This is the authority/authenticating website URL
// You can also find this value from the local UI
// Make sure that the name is resonvable
var authenticationAuthorityUrl = $"https://login.dbe-{hostName.ToLower()}.microsoftdatabox.com/adfs/";
// Arm Management endpoint
// ARM uses this endpoint to make all ARM request.
// After you have configured your device you can find this value in local UI
// Make sure the name is resolvable
var managementEndpointUrl = $"https://management.dbe-{hostName.ToLower()}.microsoftdatabox.com/";
// Arm template json file path
// You can use one of the json shared in the VM creation template JSON
var templateJson = "<Template File Name>";
// Arm Template Json Parameter file.
// You can either pre-populate the parameter file with values or we can programatically fill in the values
var templateParameters = "<>";
// The example assumes that the VHD has been uploaded to the device.
// template parameters.
// These values are required to create VM.
// resource group to create. All the related resources are created in this group
var resourceGroupName = "testVM10";
// Depoyment job name
var deploymentName = "testVM_Deployment10";
// Name of the VM
string vmName = "VMT10";
// VM Admin user name
string adminUserName = "admin";
// VM Admin User password
string adminUserPassword = "P@ssword1";
// Name of the image to use for creating VM
string imageName = "";
// Size of the VM
string vmSize = "";
// VM's NIC Name
string nicName = "nic10";
// VM's IP Config Name
string ipConfigName = "ipconfignic10";
// Virtual Network Name
// On ASE device when you configure/enable compute on a given network. The device automatically crates a VNet
// You can query the VNET and provide it here, or leave it as blank and the sample will query the device and populate these values
string vnetName = "";
string vnetResourceGroup = "";
string subNetName = "";
// construct a credentials object.
// If you have changed the domain name of the device you below constructor to consruct the credentials object
// var clientCreds = new AseServiceClientCredentials(userName, password, tenantId, managementEndpointUrl, authenticationAuthorityUrl);
var clientCreds = new AseServiceClientCredentials(userName, password, tenantId, hostName);
// Once you have created a credentials obejct you can now interact with any Azure SDK component and operate with the device
// In this example, we will use the ARM templates to create a VM resource.
// Create an instance of Resource Management Client.
var resourceClient = new ResourceManagementClient(new Uri(clientCreds.AudienceResourceUrl), clientCreds)
{
SubscriptionId = localArmSubscriptionId
};
// if the template assums the resource group to be present, then create the resource group
var resourceGroup = resourceClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup(location));
// Lets get the template
var deploymentTemplate = GetJsonFileContents(templateJson);
// Lets get the template prameter
var deploymentTemplateParameters = GetJsonFileContents(templateParameters);
// If code defines the parameter lets replace the template parameter values with the one in template.
deploymentTemplateParameters = InitializeDeploymentTemplateParameters(deploymentTemplateParameters,
clientCreds,
localArmSubscriptionId,
resourceGroupName,
vmName,
adminUserName,
adminUserPassword,
imageName,
vmSize,
nicName,
ipConfigName,
vnetName,
vnetResourceGroup,
subNetName);
DeploymentExtended deploymentResult = null;
var deployment = new Deployment();
deployment.Properties = new DeploymentProperties()
{
Mode = DeploymentMode.Incremental,
Template = deploymentTemplate,
Parameters = deploymentTemplateParameters["parameters"].ToObject<JObject>()
};
try
{
deploymentResult = resourceClient.Deployments.CreateOrUpdate(resourceGroupName, deploymentName, deployment);
Utilities.Log($"Template deployment {deploymentName} provisioningState: {deploymentResult.Properties.ProvisioningState}");
}
catch (CloudException ex)
{
Utilities.Log($"Received template deployment exception. Ex: {ex}");
if(ex.Body != null)
{
Utilities.Log($"{ex.Body.Code} <=> {ex.Body.Message}");
if(ex.Body.Details != null)
{
foreach(var d in ex.Body.Details)
{
Utilities.Log($"\t{d.Code} <==>{d.Message}");
}
}
}
throw;
}
}
/// <summary>
/// Initialize VM deployment template parameter values
/// </summary>
/// <param name="deploymentTemplateParameters">JSon object with all the deployment template</param>
/// <param name="clientCreds">Credential Object, used to query device</param>
/// <param name="subscriptionId">local arm subscription id</param>
/// <param name="resourceGroupName">resourceGroup Name</param>
/// <param name="vmName">VM Name</param>
/// <param name="adminUserName">Admin user name on the VM</param>
/// <param name="adminUserPassword">Admin user password on the VM</param>
/// <param name="imageName">Image name to use for creating VM</param>
/// <param name="vmSize">VM Size</param>
/// <param name="nicName">NIC Name</param>
/// <param name="ipConfigName">IPConfig Name</param>
/// <param name="vnetName">VNet Name</param>
/// <param name="vnetResourceGroup">VNet Resource Group Name</param>
/// <param name="subNetName">Sub Net Name</param>
/// <returns></returns>
private static JObject InitializeDeploymentTemplateParameters(JObject deploymentTemplateParameters,
AseServiceClientCredentials clientCreds,
string subscriptionId,
string resourceGroupName,
string vmName,
string adminUserName,
string adminUserPassword,
string imageName,
string vmSize,
string nicName,
string ipConfigName,
string vnetName,
string vnetResourceGroup,
string subNetName)
{
// Connect to the device's Network Management Client
var networkClient = new NetworkManagementClient(new Uri(clientCreds.AudienceResourceUrl), clientCreds)
{
SubscriptionId = subscriptionId
};
// Compute Management client. Will use to get Compute realted information
var computeClient = new ComputeManagementClient(new Uri(clientCreds.AudienceResourceUrl), clientCreds)
{
SubscriptionId = subscriptionId
};
// Update resource group name
//if(!string.IsNullOrEmpty(resourceGroupName))
//{
// ((dynamic)deploymentTemplateParameters).parameters.rgName.value = resourceGroupName;
//}
// Update value for parameter VMName
if (!string.IsNullOrEmpty(vmName))
{
((dynamic)deploymentTemplateParameters).parameters.vmName.value = vmName;
}
// Update value for parameter adminUserName
if (!string.IsNullOrEmpty(adminUserName))
{
((dynamic)deploymentTemplateParameters).parameters.adminUsername.value = adminUserName;
}
// Update value for parameter adminUserPassword
if (!string.IsNullOrEmpty(adminUserPassword))
{
((dynamic)deploymentTemplateParameters).parameters.Password.value = adminUserPassword;
}
// Update value for parameter imageName
if (!string.IsNullOrEmpty(imageName))
{
((dynamic)deploymentTemplateParameters).parameters.imageName.value = imageName;
}
else
{
// Query the device to get a list of image name
var images = computeClient.Images.List();
if(images.Any())
{
// lets pick the fist image for the sample
var img = images.First();
((dynamic)deploymentTemplateParameters).parameters.imageName.value = img.Name;
((dynamic)deploymentTemplateParameters).parameters.imageRG.value = GetResourceGroup(img.Id);
}
}
// Update value for parameter vmSize
if (!string.IsNullOrEmpty(vmSize))
{
((dynamic)deploymentTemplateParameters).parameters.vmSize.value = vmSize;
}
else
{
((dynamic)deploymentTemplateParameters).parameters.vmSize.value = "Standard_D1_v2";
}
// Update value for parameter nicName
if (!string.IsNullOrEmpty(nicName))
{
((dynamic)deploymentTemplateParameters).parameters.nicName.value = nicName;
}
// Update value for parameter ipConfigName
if (!string.IsNullOrEmpty(ipConfigName))
{
((dynamic)deploymentTemplateParameters).parameters.IPConfigName.value = ipConfigName;
}
// Update value for parameter vnetName and related values
if (string.IsNullOrEmpty(vnetName))
{
// Query all the virtual network
var allNetworks = networkClient.VirtualNetworks.ListAll();
foreach (var vn in allNetworks)
{
Utilities.Log($"{vn.Name} {vn.ProvisioningState} {vn.Location}");
}
// Use the first network for the sample
var vNet = allNetworks.FirstOrDefault();
if(vNet == null)
{
throw new Exception("VNet is not configured.");
}
// Update the parameter values
((dynamic)deploymentTemplateParameters).parameters.vnetName.value = vNet.Name;
((dynamic)deploymentTemplateParameters).parameters.vnetRG.value = GetResourceGroup(vNet.Id);
((dynamic)deploymentTemplateParameters).parameters.subnetName.value = vNet.Subnets.First().Name;
}
return deploymentTemplateParameters;
}
/// <summary>
/// Function returns the resource group name.
/// </summary>
/// <param name="id">Resource ID</param>
/// <returns></returns>
private static string GetResourceGroup(string id)
{
var keyValue = id.Split(new char[] { '/' },StringSplitOptions.RemoveEmptyEntries);
var count = 0;
while(count < keyValue.Length)
{
if(keyValue[count].Equals("resourcegroups",StringComparison.OrdinalIgnoreCase))
{
return keyValue[count + 1];
}
count = count + 2;
}
throw new Exception("Resource Group not found");
}
/// <summary>
/// Read the test JSON file
/// </summary>
/// <param name="pathToJson">JSON file path</param>
/// <returns></returns>
private static JObject GetJsonFileContents(string pathToJson)
{
JObject templatefileContent;
using (var file = File.OpenText(pathToJson))
{
using (var reader = new JsonTextReader(file))
{
templatefileContent = (JObject)JToken.ReadFrom(reader);
return templatefileContent;
}
}
}
}
}
| 40.120968 | 146 | 0.583786 | [
"MIT"
] | aasahu-msft/azure-stack-edge-deploy-vms | dotnetSamples/LocalArm/CreateVmSample/CreateVmSample/Program.cs | 14,927 | C# |
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace izBackend.Models.Common
{
public class APIResponse<T> : ActionResult
{
public bool Success { get; set; }
public string message = "";
public T Data { get; set; }
public int? TotalCount;
public Exception exception;
public String error = "";
public APIResponse()
{
}
public APIResponse(String error, Exception e)
{
this.Success = false;
this.exception = e;
this.error = error;
}
public APIResponse(T data)
{
this.Success = true;
this.Data = data;
this.TotalCount = GetCount(data);
}
public int? GetCount(object t)
{
int? count = null;
if (t is IEnumerable)
{
count = 0;
foreach (object item in (IEnumerable)t)
{
count++;
}
}
return count;
}
}
public class APIResponseSuccess : APIResponse<String>
{
public APIResponseSuccess(String message)
{
this.Success = true;
this.message = message;
}
public APIResponseSuccess()
{
this.Success = true;
this.Data ="";
}
}
public class APIResponseError : APIResponse<string>
{
public APIResponseError()
{
this.Success = false;
this.Data = "";
}
public APIResponseError(string message)
{
this.Success = false;
this.message = message;
this.Data = "";
}
}
}
| 22.081395 | 57 | 0.485519 | [
"MIT"
] | izzatshehadeh/automatic-pancake | izBackend/Models/Common/APIResponse.cs | 1,901 | C# |
using System.Threading.Tasks;
using Microsoft.Identity.Client;
namespace AP.AzureADAuth.Services
{
internal interface IAuthenticationService
{
Task<AuthenticationResult> LoginAsync();
Task<AuthenticationResult> LoginSilentAsync();
Task LogoutAsync();
}
}
| 19.666667 | 54 | 0.715254 | [
"MIT"
] | AvantiPoint/AP.AzureADAuth | src/AP.AzureADAuth/Services/IAuthenticationService.cs | 297 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Mettle.Sdk;
using Xunit.Abstractions;
using Xunit.Sdk;
namespace Mettle
{
/// <summary>
/// The default <see cref="IServiceProvider" /> implementation that ships
/// with Mettle.
/// </summary>
public class SimpleServiceProvider : IServiceProvider, IDisposable
{
private readonly ScopedLifetime scopedLifetime;
private ConcurrentDictionary<Type, Func<IServiceProvider, object?>>? factories =
new ConcurrentDictionary<Type, Func<IServiceProvider, object?>>();
/// <summary>
/// Initializes a new instance of the <see cref="SimpleServiceProvider"/> class.
/// </summary>
public SimpleServiceProvider()
{
this.scopedLifetime = new ScopedLifetime();
this.factories.TryAdd(typeof(ScopedLifetime), _ => this.scopedLifetime);
this.factories.TryAdd(typeof(IScopedServiceProviderLifetime), _ => new SimpleScopedServiceLifetime(this));
this.AddScoped(typeof(ITestOutputHelper), _ => new TestOutputHelper());
}
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
public void Dispose()
{
GC.SuppressFinalize(this);
this.Dispose(true);
}
/// <summary>
/// Gets an instance of the specified service type.
/// </summary>
/// <param name="serviceType">The clr type that should be injected.</param>
/// <returns>
/// The instance of the service type; otherwise, <see langword="null" />.
/// </returns>
public object? GetService(Type serviceType)
{
if (this.factories is null)
throw new ObjectDisposedException(nameof(SimpleServiceProvider));
if (serviceType == null)
throw new ArgumentNullException(nameof(serviceType));
if (this.factories.TryGetValue(serviceType, out var factory))
return factory(this);
if (!serviceType.IsValueType)
{
var ctors = serviceType.GetConstructors();
if (ctors.Length > 1 || ctors.Length == 0)
return null;
var ctor = ctors[0];
var parameters = ctor.GetParameters();
if (parameters == null || parameters.Length == 0)
{
this.factories.TryAdd(serviceType, _ => Activator.CreateInstance(serviceType));
return Activator.CreateInstance(serviceType);
}
this.factories.TryAdd(serviceType, (s) =>
{
var args = new List<object>();
foreach (var p in parameters)
{
args.Add(s.GetService(p.ParameterType));
}
return Activator.CreateInstance(serviceType, args.ToArray());
});
var args = new List<object?>();
foreach (var p in parameters)
{
args.Add(this.GetService(p.ParameterType));
}
return Activator.CreateInstance(serviceType, args.ToArray());
}
return Activator.CreateInstance(serviceType);
}
/// <summary>
/// Adds a single instance of the specified type.
/// </summary>
/// <param name="type">The clr type that should be injected.</param>
/// <param name="instance">The live object instance.</param>
public void AddSingleton(Type type, object instance)
{
if (this.factories is null)
throw new ObjectDisposedException(nameof(SimpleServiceProvider));
if (type == null)
throw new ArgumentNullException(nameof(type));
this.scopedLifetime.SetState(type, instance);
this.factories.TryAdd(type, s => instance);
}
/// <summary>
/// Adds a single instance of the specified type.
/// </summary>
/// <param name="type">The clr type that should be injected.</param>
/// <param name="activator">The factory method used to create the instance.</param>
public void AddSingleton(Type type, Func<IServiceProvider, object> activator)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
this.AddScoped(type, activator);
}
/// <summary>
/// Adds a service type that will be created once per lifetime scope
/// when <see cref="GetService(Type)" /> is called.
/// </summary>
/// <param name="type">The clr type that should be injected.</param>
/// <param name="activator">The factory method used to create the instance.</param>
public void AddScoped(Type type, Func<IServiceProvider, object> activator)
{
if (this.factories is null)
throw new ObjectDisposedException(nameof(SimpleServiceProvider));
this.factories.TryAdd(type, s =>
{
var sl = s.GetService(typeof(ScopedLifetime));
if (sl == null)
return null;
var scope = (ScopedLifetime)sl;
if (scope.ContainsKey(type))
return scope.GetState(type);
var r = activator(s);
scope.SetState(type, r);
return r;
});
}
/// <summary>
/// Adds a service type that will be created each time <see cref="GetService(Type)" />
/// is called.
/// </summary>
/// <param name="type">The clr type that should be injected.</param>
public void AddTransient(Type type)
{
if (this.factories is null)
throw new ObjectDisposedException(nameof(SimpleServiceProvider));
this.factories.TryAdd(type, s => Activator.CreateInstance(type));
}
/// <summary>
/// Adds a service type that will be created each time <see cref="GetService(Type)" />
/// is called.
/// </summary>
/// <param name="type">The clr type that should be injected.</param>
/// <param name="activator">The factory method used to create the instance.</param>
public void AddTransient(Type type, Func<IServiceProvider, object> activator)
{
if (this.factories is null)
throw new ObjectDisposedException(nameof(SimpleServiceProvider));
if (type == null)
throw new ArgumentNullException(nameof(type));
if (activator == null)
throw new ArgumentNullException(nameof(activator));
this.factories.TryAdd(type, activator);
}
protected virtual void Dispose(bool disposing)
{
if (disposing && this.factories != null)
{
if (this.scopedLifetime == null)
return;
foreach (var disposable in this.scopedLifetime.GetDisposables())
disposable.Dispose();
this.scopedLifetime?.Clear();
this.factories?.Clear();
this.factories = null;
}
}
public class ScopedLifetime
{
private readonly ConcurrentDictionary<Type, object> state =
new ConcurrentDictionary<Type, object>();
public bool ContainsKey(Type type)
{
return this.state.ContainsKey(type);
}
public void SetState(Type type, object instance)
{
this.state[type] = instance;
}
public object GetState(Type type)
{
this.state.TryGetValue(type, out var instance);
return instance;
}
public void Clear()
{
this.state.Clear();
}
public IEnumerable<IDisposable> GetDisposables()
{
var list = new List<IDisposable>();
foreach (var kv in this.state)
{
if (kv.Value is IDisposable disposable)
list.Add(disposable);
}
return list;
}
}
#pragma warning disable S3881
// this is a private class, so fully implementing IDispose is overkill.
private class SimpleScopedServiceLifetime : IScopedServiceProviderLifetime
{
private readonly SimpleServiceProvider provider;
public SimpleScopedServiceLifetime([NotNull] SimpleServiceProvider provider)
{
this.provider = provider ?? new SimpleServiceProvider();
if (provider is null)
throw new ArgumentNullException(nameof(provider));
if (provider.factories is null)
throw new ArgumentNullException(nameof(provider));
var provider2 = new SimpleServiceProvider();
if (provider2.factories is null)
return;
foreach (var kv in provider.factories)
{
if (kv.Key == typeof(ScopedLifetime))
continue;
if (provider2.factories.ContainsKey(kv.Key))
continue;
provider2.factories.TryAdd(kv.Key, kv.Value);
}
this.provider = provider;
}
public IServiceProvider Provider => this.provider;
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
public void Dispose()
{
this.provider?.Dispose();
}
}
}
} | 35.564912 | 139 | 0.54854 | [
"MIT"
] | nerdymishka/home-lab | nmfx/Mettle/src/SimpleServiceProvider.cs | 10,136 | C# |
/*
* ETML
* Clément Sartoni
* 22.03.2021
* Projet P_OO-Smart-Thésaurus
* Form d'héritage représentant toutes les vues.
*/
using System.Windows.Forms;
using P_Thesaurus.Controllers;
namespace P_Thesaurus.Views
{
/// <summary>
/// View that reproups all the common fields and methods of the views
/// </summary>
public partial class BaseView : Form
{
public BaseView()
{
InitializeComponent();
this.ShowIcon = false;
this.Text = "P_Thésaurus";
}
/// <summary>
/// Shows a MessageBox in the view because controller shouldn't do it
/// </summary>
/// <param name="message"></param>
/// <param name="icon"></param>
public void ShowMessageBox(string message, MessageBoxIcon icon = MessageBoxIcon.Error)
{
MessageBox.Show(message, "un problème est survenu.");
}
}
}
| 25.108108 | 94 | 0.594187 | [
"MIT"
] | Mathias-ETML/P_OO_Thesaurus | P_Thesaurus/Views/BaseView.cs | 937 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using SqlWrangler.Properties;
namespace SqlWrangler
{
public partial class FrmMain : Form
{
public IDbConnection Connection { get; set; }
public FrmLogin Login { get; set; }
public List<TextSnippet> Snippets = new List<TextSnippet>();
public FrmMain()
{
InitializeComponent();
GetSnippets();
var b = Resources.toolbox;
var pIcon = b.GetHicon();
var i = Icon.FromHandle(pIcon);
Icon = i;
i.Dispose();
}
private void newToolStripMenuItem_Click_1(object sender, EventArgs e)
{
NewSqlForm();
}
private void NewSqlForm()
{
var newForm = new SqlClient(Snippets)
{
Connection = Connection,
MdiParent = this
};
newForm.Show();
}
private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
{
Connection.Close();
Connection.Dispose();
Login.Close();
PersistSnippets();
}
private void PersistSnippets()
{
var fi = new FileInfo("snippets.xml");
if (fi.Exists) fi.Delete();
var serializer = new XmlSerializer(typeof (List<TextSnippet>));
using (var tw = XmlWriter.Create(fi.OpenWrite()))
{
serializer.Serialize(tw, Snippets);
}
}
protected override bool ProcessCmdKey(ref Message message, Keys keys)
{
switch (keys)
{
case Keys.F1:
{
NewSqlForm();
break;
}
}
return base.ProcessCmdKey(ref message, keys);
}
private void GetSnippets()
{
var xmlfi = new FileInfo("snippets.xml");
if (xmlfi.Exists)
{
var serializer = new XmlSerializer(typeof (List<TextSnippet>));
if (xmlfi.Length > 0)
{
using (var sr = new StreamReader(xmlfi.OpenRead()))
{
Snippets = (List<TextSnippet>) serializer.Deserialize(sr);
}
}
return;
}
//Old snippets text file...
var fi = new FileInfo("snippets.txt");
if (!fi.Exists) return;
using (var sr = new StreamReader(fi.OpenRead()))
{
var s = sr.ReadLine();
while (s != null)
{
try
{
var idx = s.IndexOf(",", StringComparison.Ordinal);
if (idx > -1)
{
var splits = new string[2];
splits[0] = s.Substring(0, idx);
splits[1] = s.Substring(idx + 1);
var snip = new TextSnippet()
{
Name = splits[0],
Text = splits[1].Replace(@"\r", "\r").Replace(@"\n", "\n").Replace(@"\t", "\t")
};
Snippets.Add(snip);
}
s = sr.ReadLine();
}
catch
{
//
}
}
}
}
private void frmMain_DragDrop(object sender, DragEventArgs e)
{
}
private void helpToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show(string.Format(@"
CURRENT CONNECTION
{0}
---------------------------
SQL WRANGLER
", Connection.ConnectionString), "About", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
| 28.36129 | 111 | 0.432439 | [
"MIT"
] | dshifflet/SqlWrangler | SqlWrangler/SqlWrangler/FmMain.cs | 4,398 | C# |
/* RecordField.cs - поле библиографической записи
* Ars Magna project, http://arsmagna.ru
*/
#region Using directives
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using Newtonsoft.Json;
#endregion
namespace ManagedClient
{
/// <summary>
/// Поле библиографической записи.
/// </summary>
[Serializable]
[XmlRoot("field")]
[DebuggerDisplay("Tag={Tag} Text={Text}")]
public sealed class RecordField
{
#region Constants
/// <summary>
/// Разделитель подполей.
/// </summary>
public const char Delimiter = '^';
#endregion
#region Properties
/// <summary>
/// Флаг: выбрасывать исключение, если свойству Text
/// присваивается значение, содержащее разделитель.
/// </summary>
public static bool BreakOnTextContainDelimiters;
/// <summary>
/// Метка поля.
/// </summary>
[XmlAttribute("tag")]
[JsonProperty("tag")]
public string Tag { get; set; }
/// <summary>
/// Повторение поля.
/// Настраивается перед передачей
/// в скрипты.
/// Не используется в большинстве сценариев.
/// </summary>
[XmlIgnore]
[JsonIgnore]
[NonSerialized]
public int Repeat;
/// <summary>
/// Значение поля до первого разделителя подполей.
/// </summary>
/// <remarks>
/// Внимание! Если присваиваемое значение содержит
/// разделитель, то происходит и присвоение подполей!
/// Имеющиеся в SubFields значения при этом пропадают
/// и замещаются на вновь присваиваемые!
/// </remarks>
[XmlAttribute("text")]
[JsonProperty("text")]
public string Text
{
get
{
return _text;
}
set
{
if (string.IsNullOrEmpty(value))
{
_text = value;
}
else
{
if (value.IndexOf(Delimiter) >= 0)
{
if (BreakOnTextContainDelimiters)
{
throw new ArgumentException
(
"Contains delimiter",
"Text"
);
}
SetSubFields(value);
}
else
{
value = Utilities
.ReplaceControlCharacters(value);
if (!string.IsNullOrEmpty(value))
{
value = value.Trim();
}
_text = value;
}
}
}
}
/// <summary>
/// Список подполей.
/// </summary>
[XmlElement("subfield")]
[JsonProperty("subfields")]
public SubFieldCollection SubFields
{
get { return _subFields; }
}
/// <summary>
/// Произвольные пользовательские данные.
/// </summary>
[XmlIgnore]
[JsonIgnore]
public object UserData
{
get { return _userData; }
set { _userData = value; }
}
/// <summary>
/// Ссылка на запись, владеющую
/// данным полем. Настраивается
/// перед передачей в скрипты.
/// Всё остальное время неактуально.
/// </summary>
[XmlIgnore]
[JsonIgnore]
[NonSerialized]
public IrbisRecord Record;
#endregion
#region Construction
/// <summary>
/// Initializes a new instance of the <see cref="RecordField" /> class.
/// </summary>
public RecordField()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RecordField" /> class.
/// </summary>
/// <param name="tag">The tag.</param>
public RecordField
(
string tag
)
{
Tag = tag;
}
/// <summary>
/// Initializes a new instance of the <see cref="RecordField" /> class.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="text">The text.</param>
public RecordField
(
string tag,
string text
)
{
Tag = tag;
Text = text;
}
#endregion
#region Private members
private string _text;
private readonly SubFieldCollection _subFields
= new SubFieldCollection();
[NonSerialized]
private object _userData;
private static void AddSubField
(
RecordField field,
char code,
StringBuilder value
)
{
if (code != 0)
{
if (value.Length == 0)
{
field.SubFields.Add(new SubField(code));
}
else
{
field.SubFields.Add(new SubField
(
code,
value.ToString()
));
}
}
value.Length = 0;
}
private static void _EncodeSubField
(
StringBuilder builder,
SubField subField
)
{
builder.AppendFormat
(
"{0}{1}{2}",
Delimiter,
subField.Code,
subField.Text
);
}
internal static void _EncodeField
(
StringBuilder builder,
RecordField field
)
{
int fieldNumber = field.Tag.SafeParseInt32();
if (fieldNumber != 0)
{
builder.AppendFormat
(
"{0}#",
fieldNumber
);
}
else
{
builder.AppendFormat
(
"{0}#",
field.Tag
);
}
if (!string.IsNullOrEmpty(field.Text))
{
builder.Append(field.Text);
}
foreach (SubField subField in field.SubFields)
{
_EncodeSubField
(
builder,
subField
);
}
builder.Append("\x001F\x001E");
}
#endregion
#region Public methods
/// <summary>
/// Перечень подполей с указанным кодом.
/// </summary>
/// <param name="code">Искомый код подполя.</param>
/// <remarks>Сравнение кодов происходит без учета
/// регистра символов.</remarks>
/// <returns>Найденные подполя.</returns>
public SubField[] GetSubField
(
char code
)
{
SubField[] result = SubFields
.Where(_ => _.Code.SameChar(code))
.ToArray();
return result;
}
/// <summary>
/// Указанное повторение подполя с данным кодом.
/// </summary>
/// <param name="code">Искомый код подполя.</param>
/// <param name="occurrence">Номер повторения.
/// Нумерация начинается с нуля.
/// Отрицательные индексы отсчитываются с конца массива.</param>
/// <returns>Найденное подполе или <c>null</c>.</returns>
public SubField GetSubField
(
char code,
int occurrence
)
{
SubField[] found = GetSubField(code);
occurrence = (occurrence >= 0)
? occurrence
: found.Length - occurrence;
SubField result = null;
if ((occurrence >= 0) && (occurrence < found.Length))
{
result = found[occurrence];
}
return result;
}
/// <summary>
/// Gets the first subfield.
/// </summary>
/// <param name="code">The code.</param>
/// <returns>SubField.</returns>
public SubField GetFirstSubField
(
char code
)
{
return SubFields.FirstOrDefault(sf => sf.Code.SameChar(code));
}
/// <summary>
/// Получение текста указанного подполя.
/// </summary>
/// <param name="code">Искомый код подполя.</param>
/// <param name="occurrence">Номер повторения.
/// Нумерация начинается с нуля.
/// Отрицательные индексы отсчитываются с конца массива.</param>
/// <returns>Текст найденного подполя или <c>null</c>.</returns>
public string GetSubFieldText
(
char code,
int occurrence
)
{
SubField result = GetSubField(code, occurrence);
return (result == null)
? null
: result.Text;
}
/// <summary>
/// Gets first subfield text.
/// </summary>
/// <param name="code">The code.</param>
/// <returns>System.String.</returns>
public string GetFirstSubFieldText
(
char code
)
{
SubField result = GetFirstSubField(code);
return (result == null)
? null
: result.Text;
}
/// <summary>
/// Filters the sub fields.
/// </summary>
/// <param name="subFields">The sub fields.</param>
/// <param name="predicate">The predicate.</param>
/// <returns>SubField[].</returns>
public static SubField[] FilterSubFields
(
IEnumerable<SubField> subFields,
Func<SubField, bool> predicate
)
{
return subFields
.Where(predicate)
.ToArray();
}
/// <summary>
/// Filters the sub fields.
/// </summary>
/// <param name="predicate">The predicate.</param>
/// <returns>SubField[].</returns>
public SubField[] FilterSubFields
(
Func<SubField, bool> predicate
)
{
return FilterSubFields(SubFields, predicate);
}
/// <summary>
/// Filters the sub fields.
/// </summary>
/// <param name="subFields">The sub fields.</param>
/// <param name="codes">The codes.</param>
/// <param name="predicate">The predicate.</param>
/// <returns>SubField[].</returns>
public static SubField[] FilterSubFields
(
IEnumerable<SubField> subFields,
char[] codes,
Func<SubField, bool> predicate
)
{
return subFields
.Where(_ => _.Code.OneOf(codes)
&& predicate(_))
.ToArray();
}
/// <summary>
/// Filters the sub fields.
/// </summary>
/// <param name="codes">The codes.</param>
/// <param name="predicate">The predicate.</param>
/// <returns>SubField[].</returns>
public SubField[] FilterSubFields
(
char[] codes,
Func<SubField, bool> predicate
)
{
return FilterSubFields(SubFields, codes, predicate);
}
/// <summary>
/// Отбор подполей с указанными кодами.
/// </summary>
/// <param name="subFields"></param>
/// <param name="codes"></param>
/// <returns></returns>
public static SubField[] FilterSubFields
(
IEnumerable<SubField> subFields,
params char[] codes
)
{
return subFields
.Where(_ => _.Code.OneOf(codes))
.ToArray();
}
/// <summary>
/// Отбор подполей с указанными кодами.
/// </summary>
/// <param name="codes"></param>
/// <returns></returns>
public SubField[] FilterSubFields
(
params char[] codes
)
{
return FilterSubFields(SubFields, codes);
}
/// <summary>
/// Adds the sub field.
/// </summary>
/// <param name="code">The code.</param>
/// <param name="text">The text.</param>
/// <returns>RecordField.</returns>
public RecordField AddSubField
(
char code,
string text
)
{
SubFields.Add(new SubField(code, text));
return this;
}
/// <summary>
/// Adds the non empty sub field.
/// </summary>
/// <param name="code">The code.</param>
/// <param name="text">The text.</param>
/// <returns>RecordField.</returns>
public RecordField AddNonEmptySubField
(
char code,
string text
)
{
if (!string.IsNullOrEmpty(text))
{
AddSubField(code, text);
}
return this;
}
/// <summary>
/// Sets the sub field.
/// </summary>
/// <param name="code">The code.</param>
/// <param name="text">The text.</param>
/// <returns></returns>
/// <remarks>Устанавливает значение только первого
/// подполя с указанным кодом (если в поле их несколько)!
/// </remarks>
public RecordField SetSubField
(
char code,
string text
)
{
SubField subField = SubFields
.Find(_ => _.Code.SameChar(code));
if (subField == null)
{
subField = new SubField(code, text);
SubFields.Add(subField);
}
subField.Text = text;
return this;
}
/// <summary>
/// Replaces the sub field.
/// </summary>
/// <param name="code">The code.</param>
/// <param name="oldValue">The old value.</param>
/// <param name="newValue">The new value.</param>
/// <returns>RecordField.</returns>
public RecordField ReplaceSubField
(
char code,
string oldValue,
string newValue
)
{
var found = SubFields
.Where(sf => sf.Code.SameChar(code)
&& (string.CompareOrdinal(sf.Text, oldValue) == 0));
foreach (SubField subField in found)
{
subField.Text = newValue;
}
return this;
}
/// <summary>
/// Removes the sub field.
/// </summary>
/// <param name="code">The code.</param>
/// <returns></returns>
/// <remarks>Удаляет все повторения подполей
/// с указанным кодом.
/// </remarks>
public RecordField RemoveSubField
(
char code
)
{
code = char.ToLowerInvariant(code);
SubField[] found = SubFields
.FindAll(_ => char.ToLowerInvariant(_.Code) == code)
.ToArray();
foreach (SubField subField in found)
{
SubFields.Remove(subField);
}
return this;
}
/// <summary>
/// Replaces the sub field.
/// </summary>
/// <param name="code">The code.</param>
/// <param name="newValue">The new value.</param>
/// <param name="ignoreCase">if set to <c>true</c> [ignore case].</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
public bool ReplaceSubField
(
char code,
string newValue,
bool ignoreCase
)
{
string oldValue = GetSubFieldText(code, 0);
bool changed = string.Compare
(
oldValue,
newValue,
ignoreCase
) != 0;
if (changed)
{
SetSubField(code, newValue);
}
return changed;
}
/// <summary>
/// Haves the sub field.
/// </summary>
/// <param name="codes">The codes.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
public bool HaveSubField
(
params char[] codes
)
{
return (codes.Any(code => GetSubField(code).Length != 0));
}
/// <summary>
/// Haves the not sub field.
/// </summary>
/// <param name="codes">The codes.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
public bool HaveNotSubField
(
params char[] codes
)
{
return (codes.All(code => GetSubField(code).Length == 0));
}
/// <summary>
/// To the text.
/// </summary>
/// <returns>System.String.</returns>
public string ToText()
{
StringBuilder result = new StringBuilder();
if (!string.IsNullOrEmpty(Text))
{
result.Append(Text);
}
foreach (SubField subField in SubFields)
{
string subText = subField.ToString();
if (!string.IsNullOrEmpty(subText))
{
result.Append(subText);
}
}
return result.ToString();
}
/// <summary>
/// Вывод поля в порядке алфавита
/// кодов подполей.
/// </summary>
/// <returns></returns>
public string ToSortedText()
{
StringBuilder result = new StringBuilder();
if (!string.IsNullOrEmpty(Text))
{
result.Append(Text);
}
foreach (SubField subField
in SubFields.OrderBy(sf => sf.CodeString.ToUpperInvariant()))
{
string subText = string.Format
(
"^{0}{1}",
subField.CodeString.ToUpperInvariant(),
subField.Text
);
if (!string.IsNullOrEmpty(subText))
{
result.Append(subText);
}
}
return result.ToString();
}
/// <summary>
/// Парсинг текстового представления поля
/// </summary>
/// <param name="tag"></param>
/// <param name="body"></param>
/// <returns></returns>
public static RecordField Parse
(
string tag,
string body
)
{
RecordField result = new RecordField(tag);
int first = body.IndexOf(Delimiter);
if (first != 0)
{
if (first < 0)
{
result.Text = body;
body = string.Empty;
}
else
{
result.Text = body.Substring
(
0,
first
);
body = body.Substring(first);
}
}
var code = (char)0;
var value = new StringBuilder();
foreach (char c in body)
{
if (c == Delimiter)
{
AddSubField
(
result,
code,
value
);
code = (char)0;
}
else
{
if (code == 0)
{
code = c;
}
else
{
value.Append(c);
}
}
}
AddSubField
(
result,
code,
value
);
return result;
}
/// <summary>
/// Reparses the specified text.
/// </summary>
/// <param name="text">The text.</param>
/// <returns>RecordField.</returns>
public RecordField Reparse
(
string text
)
{
RecordField parsed = Parse
(
Tag,
text
);
if (!ReferenceEquals(parsed, null))
{
Text = parsed.Text;
_subFields.Clear();
_subFields.AddRange(parsed._subFields);
}
return this;
}
/// <summary>
/// Adds the sub fields.
/// </summary>
/// <param name="subFields">The sub fields.</param>
/// <returns>RecordField.</returns>
public RecordField AddSubFields
(
IEnumerable<SubField> subFields
)
{
SubFields.AddRange
(
subFields.NonNullItems()
);
return this;
}
/// <summary>
/// Adds the sub fields.
/// </summary>
/// <param name="encodedText">The encoded text.</param>
/// <returns>RecordField.</returns>
public RecordField AddSubFields
(
string encodedText
)
{
RecordField parsed = Parse(encodedText);
if (!ReferenceEquals(parsed, null))
{
if (!string.IsNullOrEmpty(parsed.Text))
{
Text += parsed.Text;
}
AddSubFields(parsed.SubFields);
}
return this;
}
/// <summary>
/// Sets the sub fields.
/// </summary>
/// <param name="subFields">The sub fields.</param>
/// <returns>RecordField.</returns>
public RecordField SetSubFields
(
IEnumerable<SubField> subFields
)
{
foreach (SubField subField in subFields.NonNullItems())
{
SetSubField
(
subField.Code,
subField.Text
);
}
return this;
}
/// <summary>
/// Sets the sub fields.
/// </summary>
/// <param name="encodedText">The encoded text.</param>
/// <returns>RecordField.</returns>
public RecordField SetSubFields
(
string encodedText
)
{
RecordField parsed = Parse(encodedText);
if (!ReferenceEquals(parsed, null))
{
if (!string.IsNullOrEmpty(parsed.Text))
{
_text = parsed.Text;
}
SetSubFields(parsed.SubFields);
}
return this;
}
/// <summary>
/// Парсинг строкового представления поля.
/// </summary>
/// <param name="line">The line.</param>
/// <returns></returns>
public static RecordField Parse
(
string line
)
{
if (string.IsNullOrEmpty(line))
{
return null;
}
string[] parts = line.SplitFirst('#');
string tag = parts[0];
string body = parts[1];
return Parse
(
tag,
body
);
}
/// <summary>
/// Clones this instance.
/// </summary>
/// <returns>RecordField.</returns>
public RecordField Clone()
{
RecordField result = new RecordField
{
Tag = Tag,
Text = Text
};
result.SubFields.AddRange
(
from subField in SubFields
select subField.Clone()
);
return result;
}
/// <summary>
/// Compares the specified field1.
/// </summary>
/// <param name="field1">The field1.</param>
/// <param name="field2">The field2.</param>
/// <param name="verbose">if set to <c>true</c> [verbose].</param>
/// <returns>System.Int32.</returns>
public static int Compare
(
RecordField field1,
RecordField field2,
bool verbose
)
{
int result = string.CompareOrdinal(field1.Tag, field2.Tag);
if (result != 0)
{
if (verbose)
{
Console.WriteLine
(
"Field1 Tag={0}, Field2 Tag={1}",
field1.Tag,
field2.Tag
);
}
return result;
}
if (!string.IsNullOrEmpty(field1.Text)
|| !string.IsNullOrEmpty(field2.Text))
{
result = string.CompareOrdinal(field1.Text, field2.Text);
if (result != 0)
{
if (verbose)
{
Console.WriteLine
(
"Field1 Text={0}, Field2 Text={1}",
field1.Text,
field2.Text
);
}
return result;
}
}
IEnumerator<SubField> enum1 = field1.SubFields.GetEnumerator();
IEnumerator<SubField> enum2 = field2.SubFields.GetEnumerator();
while (true)
{
bool next1 = enum1.MoveNext();
bool next2 = enum2.MoveNext();
if ((!next1) && (!next2))
{
break;
}
if (!next1)
{
return -1;
}
if (!next2)
{
return 1;
}
SubField subField1 = enum1.Current;
SubField subField2 = enum2.Current;
result = SubField.Compare
(
subField1,
subField2,
verbose
);
if (result != 0)
{
return result;
}
}
return 0;
}
/// <summary>
/// Gets the embedded fields.
/// </summary>
/// <param name="sign">The sign.</param>
/// <returns>RecordField[].</returns>
public RecordField[] GetEmbeddedFields
(
char sign
)
{
List<RecordField> result = new List<RecordField>();
RecordField found = null;
foreach (SubField subField in SubFields)
{
if (subField.Code == sign)
{
if (found != null)
{
result.Add(found);
}
string tag = subField.Text.Substring
(
0,
3
);
found = new RecordField(tag);
if (tag.StartsWith("00")
&& (subField.Text.Length > 3)
)
{
found.Text = subField.Text.Substring(3);
}
}
else
{
if (found != null)
{
found.AddSubField
(
subField.Code,
subField.Text
);
}
}
}
if (found != null)
{
result.Add(found);
}
return result.ToArray();
}
/// <summary>
/// Gets the embedded fields.
/// </summary>
/// <returns>RecordField[].</returns>
public RecordField[] GetEmbeddedFields()
{
return GetEmbeddedFields('1');
}
/// <summary>
/// Нормализация тега.
/// </summary>
public static string NormalizeTag
(
string tag
)
{
string result = tag;
while (result.Length < 3)
{
result = "0" + result;
}
return result;
}
/// <summary>
/// Означает ли тег фиксированное поле.
/// </summary>
public static bool IsFixed
(
string tag
)
{
return tag.StartsWith("00");
}
#endregion
#region Object members
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
StringBuilder result = new StringBuilder();
_EncodeField(result, this);
return result.ToString();
}
#endregion
}
}
| 27.855735 | 81 | 0.409657 | [
"MIT"
] | amironov73/ManagedClient.3 | ManagedClient/RecordField.cs | 32,428 | C# |
using Discord.Audio;
using System.Threading.Tasks;
namespace Discord
{
/// <summary>
/// Represents a generic audio channel.
/// </summary>
public interface IAudioChannel : IChannel
{
/// <summary>
/// Gets the RTC region for this audio channel.
/// </summary>
/// <remarks>
/// This property can be <see langword="null"/>.
/// </remarks>
string RTCRegion { get; }
/// <summary>
/// Connects to this audio channel.
/// </summary>
/// <param name="selfDeaf">Determines whether the client should deaf itself upon connection.</param>
/// <param name="selfMute">Determines whether the client should mute itself upon connection.</param>
/// <param name="external">Determines whether the audio client is an external one or not.</param>
/// <returns>
/// A task representing the asynchronous connection operation. The task result contains the
/// <see cref="IAudioClient"/> responsible for the connection.
/// </returns>
Task<IAudioClient> ConnectAsync(bool selfDeaf = false, bool selfMute = false, bool external = false);
/// <summary>
/// Disconnects from this audio channel.
/// </summary>
/// <returns>
/// A task representing the asynchronous operation for disconnecting from the audio channel.
/// </returns>
Task DisconnectAsync();
}
}
| 37.375 | 109 | 0.59398 | [
"MIT"
] | XenotropicDev/Discord.Net-Labs | src/Discord.Net.Core/Entities/Channels/IAudioChannel.cs | 1,495 | 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.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.WebSockets
{
internal static partial class WebSocketValidate
{
internal const string SecWebSocketKeyGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
internal const string WebSocketUpgradeToken = "websocket";
internal const int DefaultReceiveBufferSize = 16 * 1024;
internal const int DefaultClientSendBufferSize = 16 * 1024;
// RFC 6455 requests WebSocket clients to let the server initiate the TCP close to avoid that client sockets
// end up in TIME_WAIT-state
//
// After both sending and receiving a Close message, an endpoint considers the WebSocket connection closed and
// MUST close the underlying TCP connection. The server MUST close the underlying TCP connection immediately;
// the client SHOULD wait for the server to close the connection but MAY close the connection at any time after
// sending and receiving a Close message, e.g., if it has not received a TCP Close from the server in a
// reasonable time period.
internal const int ClientTcpCloseTimeout = 1000; // 1s
private static readonly ArraySegment<byte> s_EmptyPayload = new ArraySegment<byte>(new byte[] { }, 0, 0);
private static readonly Random s_keyGenerator = new Random();
private static readonly bool s_httpSysSupportsWebSockets = (Environment.OSVersion.Version >= new Version(6, 2));
internal static ArraySegment<byte> EmptyPayload
{
get { return s_EmptyPayload; }
}
internal static Task<HttpListenerWebSocketContext> AcceptWebSocketAsync(HttpListenerContext context,
string subProtocol,
int receiveBufferSize,
TimeSpan keepAliveInterval,
ArraySegment<byte> internalBuffer)
{
ValidateOptions(subProtocol, receiveBufferSize, WebSocketBuffer.MinSendBufferSize, keepAliveInterval);
ValidateArraySegment<byte>(internalBuffer, nameof(internalBuffer));
WebSocketBuffer.Validate(internalBuffer.Count, receiveBufferSize, WebSocketBuffer.MinSendBufferSize, true);
return AcceptWebSocketAsyncCore(context, subProtocol, receiveBufferSize, keepAliveInterval, internalBuffer);
}
private static async Task<HttpListenerWebSocketContext> AcceptWebSocketAsyncCore(HttpListenerContext context,
string subProtocol,
int receiveBufferSize,
TimeSpan keepAliveInterval,
ArraySegment<byte> internalBuffer)
{
HttpListenerWebSocketContext webSocketContext = null;
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(null, context);
}
try
{
// get property will create a new response if one doesn't exist.
HttpListenerResponse response = context.Response;
HttpListenerRequest request = context.Request;
ValidateWebSocketHeaders(context);
string secWebSocketVersion = request.Headers[HttpKnownHeaderNames.SecWebSocketVersion];
// Optional for non-browser client
string origin = request.Headers[HttpKnownHeaderNames.Origin];
List<string> secWebSocketProtocols = new List<string>();
string outgoingSecWebSocketProtocolString;
bool shouldSendSecWebSocketProtocolHeader =
ProcessWebSocketProtocolHeader(
request.Headers[HttpKnownHeaderNames.SecWebSocketProtocol],
subProtocol,
out outgoingSecWebSocketProtocolString);
if (shouldSendSecWebSocketProtocolHeader)
{
secWebSocketProtocols.Add(outgoingSecWebSocketProtocolString);
response.Headers.Add(HttpKnownHeaderNames.SecWebSocketProtocol,
outgoingSecWebSocketProtocolString);
}
// negotiate the websocket key return value
string secWebSocketKey = request.Headers[HttpKnownHeaderNames.SecWebSocketKey];
string secWebSocketAccept = WebSocketValidate.GetSecWebSocketAcceptString(secWebSocketKey);
response.Headers.Add(HttpKnownHeaderNames.Connection, HttpKnownHeaderNames.Upgrade);
response.Headers.Add(HttpKnownHeaderNames.Upgrade, WebSocketUpgradeToken);
response.Headers.Add(HttpKnownHeaderNames.SecWebSocketAccept, secWebSocketAccept);
response.StatusCode = (int)HttpStatusCode.SwitchingProtocols; // HTTP 101
response.ComputeCoreHeaders();
ulong hresult = SendWebSocketHeaders(response);
if (hresult != 0)
{
throw new WebSocketException((int)hresult,
SR.Format(SR.net_WebSockets_NativeSendResponseHeaders,
nameof(AcceptWebSocketAsync),
hresult));
}
if (NetEventSource.IsEnabled)
{
NetEventSource.Info(null, $"{HttpKnownHeaderNames.Origin} = {origin}");
NetEventSource.Info(null, $"{HttpKnownHeaderNames.SecWebSocketVersion} = {secWebSocketVersion}");
NetEventSource.Info(null, $"{HttpKnownHeaderNames.SecWebSocketKey} = {secWebSocketKey}");
NetEventSource.Info(null, $"{HttpKnownHeaderNames.SecWebSocketAccept} = {secWebSocketAccept}");
NetEventSource.Info(null, $"{HttpKnownHeaderNames.SecWebSocketProtocol} = {request.Headers[HttpKnownHeaderNames.SecWebSocketProtocol]}");
NetEventSource.Info(null, $"{HttpKnownHeaderNames.SecWebSocketProtocol} = {outgoingSecWebSocketProtocolString}");
}
await response.OutputStream.FlushAsync().SuppressContextFlow();
HttpResponseStream responseStream = response.OutputStream as HttpResponseStream;
Debug.Assert(responseStream != null, "'responseStream' MUST be castable to System.Net.HttpResponseStream.");
((HttpResponseStream)response.OutputStream).SwitchToOpaqueMode();
HttpRequestStream requestStream = new HttpRequestStream(context);
requestStream.SwitchToOpaqueMode();
WebSocketHttpListenerDuplexStream webSocketStream =
new WebSocketHttpListenerDuplexStream(requestStream, responseStream, context);
WebSocket webSocket = ServerWebSocket.Create(webSocketStream,
subProtocol,
receiveBufferSize,
keepAliveInterval,
internalBuffer);
webSocketContext = new HttpListenerWebSocketContext(
request.Url,
request.Headers,
request.Cookies,
context.User,
request.IsAuthenticated,
request.IsLocal,
request.IsSecureConnection,
origin,
secWebSocketProtocols.AsReadOnly(),
secWebSocketVersion,
secWebSocketKey,
webSocket);
if (NetEventSource.IsEnabled)
{
NetEventSource.Associate(context, webSocketContext);
NetEventSource.Associate(webSocketContext, webSocket);
}
}
catch (Exception ex)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Error(context, ex);
}
throw;
}
finally
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Exit(context);
}
}
return webSocketContext;
}
[SuppressMessage("Microsoft.Security", "CA5350", Justification = "SHA1 used only for hashing purposes, not for crypto.")]
internal static string GetSecWebSocketAcceptString(string secWebSocketKey)
{
string retVal;
// SHA1 used only for hashing purposes, not for crypto. Check here for FIPS compat.
using (SHA1 sha1 = SHA1.Create())
{
string acceptString = string.Concat(secWebSocketKey, WebSocketValidate.SecWebSocketKeyGuid);
byte[] toHash = Encoding.UTF8.GetBytes(acceptString);
retVal = Convert.ToBase64String(sha1.ComputeHash(toHash));
}
return retVal;
}
internal static string GetTraceMsgForParameters(int offset, int count, CancellationToken cancellationToken)
{
return string.Format(CultureInfo.InvariantCulture,
"offset: {0}, count: {1}, cancellationToken.CanBeCanceled: {2}",
offset,
count,
cancellationToken.CanBeCanceled);
}
// return value here signifies if a Sec-WebSocket-Protocol header should be returned by the server.
internal static bool ProcessWebSocketProtocolHeader(string clientSecWebSocketProtocol,
string subProtocol,
out string acceptProtocol)
{
acceptProtocol = string.Empty;
if (string.IsNullOrEmpty(clientSecWebSocketProtocol))
{
// client hasn't specified any Sec-WebSocket-Protocol header
if (subProtocol != null)
{
// If the server specified _anything_ this isn't valid.
throw new WebSocketException(WebSocketError.UnsupportedProtocol,
SR.Format(SR.net_WebSockets_ClientAcceptingNoProtocols, subProtocol));
}
// Treat empty and null from the server as the same thing here, server should not send headers.
return false;
}
// here, we know the client specified something and it's non-empty.
if (subProtocol == null)
{
// client specified some protocols, server specified 'null'. So server should send headers.
return true;
}
// here, we know that the client has specified something, it's not empty
// and the server has specified exactly one protocol
string[] requestProtocols = clientSecWebSocketProtocol.Split(new char[] { ',' },
StringSplitOptions.RemoveEmptyEntries);
acceptProtocol = subProtocol;
// client specified protocols, serverOptions has exactly 1 non-empty entry. Check that
// this exists in the list the client specified.
for (int i = 0; i < requestProtocols.Length; i++)
{
string currentRequestProtocol = requestProtocols[i].Trim();
if (string.Compare(acceptProtocol, currentRequestProtocol, StringComparison.OrdinalIgnoreCase) == 0)
{
return true;
}
}
throw new WebSocketException(WebSocketError.UnsupportedProtocol,
SR.Format(SR.net_WebSockets_AcceptUnsupportedProtocol,
clientSecWebSocketProtocol,
subProtocol));
}
internal static ConfiguredTaskAwaitable SuppressContextFlow(this Task task)
{
// We don't flow the synchronization context within WebSocket.xxxAsync - but the calling application
// can decide whether the completion callback for the task returned from WebSocket.xxxAsync runs
// under the caller's synchronization context.
return task.ConfigureAwait(false);
}
internal static ConfiguredTaskAwaitable<T> SuppressContextFlow<T>(this Task<T> task)
{
// We don't flow the synchronization context within WebSocket.xxxAsync - but the calling application
// can decide whether the completion callback for the task returned from WebSocket.xxxAsync runs
// under the caller's synchronization context.
return task.ConfigureAwait(false);
}
internal static void ValidateBuffer(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (buffer.Length - offset))
{
throw new ArgumentOutOfRangeException(nameof(count));
}
}
private static unsafe ulong SendWebSocketHeaders(HttpListenerResponse response)
{
return response.SendHeaders(null, null,
Interop.HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_OPAQUE |
Interop.HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_MORE_DATA |
Interop.HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_BUFFER_DATA,
true);
}
private static void ValidateWebSocketHeaders(HttpListenerContext context)
{
EnsureHttpSysSupportsWebSockets();
if (!context.Request.IsWebSocketRequest)
{
throw new WebSocketException(WebSocketError.NotAWebSocket,
SR.Format(SR.net_WebSockets_AcceptNotAWebSocket,
nameof(ValidateWebSocketHeaders),
HttpKnownHeaderNames.Connection,
HttpKnownHeaderNames.Upgrade,
WebSocketValidate.WebSocketUpgradeToken,
context.Request.Headers[HttpKnownHeaderNames.Upgrade]));
}
string secWebSocketVersion = context.Request.Headers[HttpKnownHeaderNames.SecWebSocketVersion];
if (string.IsNullOrEmpty(secWebSocketVersion))
{
throw new WebSocketException(WebSocketError.HeaderError,
SR.Format(SR.net_WebSockets_AcceptHeaderNotFound,
nameof(ValidateWebSocketHeaders),
HttpKnownHeaderNames.SecWebSocketVersion));
}
if (string.Compare(secWebSocketVersion, WebSocketProtocolComponent.SupportedVersion, StringComparison.OrdinalIgnoreCase) != 0)
{
throw new WebSocketException(WebSocketError.UnsupportedVersion,
SR.Format(SR.net_WebSockets_AcceptUnsupportedWebSocketVersion,
nameof(ValidateWebSocketHeaders),
secWebSocketVersion,
WebSocketProtocolComponent.SupportedVersion));
}
if (string.IsNullOrWhiteSpace(context.Request.Headers[HttpKnownHeaderNames.SecWebSocketKey]))
{
throw new WebSocketException(WebSocketError.HeaderError,
SR.Format(SR.net_WebSockets_AcceptHeaderNotFound,
nameof(ValidateWebSocketHeaders),
HttpKnownHeaderNames.SecWebSocketKey));
}
}
internal static void ValidateOptions(string subProtocol,
int receiveBufferSize,
int sendBufferSize,
TimeSpan keepAliveInterval)
{
// We allow the subProtocol to be null. Validate if it is not null.
if (subProtocol != null)
{
ValidateSubprotocol(subProtocol);
}
ValidateBufferSizes(receiveBufferSize, sendBufferSize);
if (keepAliveInterval < Timeout.InfiniteTimeSpan) // -1
{
throw new ArgumentOutOfRangeException(nameof(keepAliveInterval), keepAliveInterval,
SR.Format(SR.net_WebSockets_ArgumentOutOfRange_TooSmall, Timeout.InfiniteTimeSpan.ToString()));
}
}
internal static void ValidateBufferSizes(int receiveBufferSize, int sendBufferSize)
{
if (receiveBufferSize < WebSocketBuffer.MinReceiveBufferSize)
{
throw new ArgumentOutOfRangeException(nameof(receiveBufferSize), receiveBufferSize,
SR.Format(SR.net_WebSockets_ArgumentOutOfRange_TooSmall, WebSocketBuffer.MinReceiveBufferSize));
}
if (sendBufferSize < WebSocketBuffer.MinSendBufferSize)
{
throw new ArgumentOutOfRangeException(nameof(sendBufferSize), sendBufferSize,
SR.Format(SR.net_WebSockets_ArgumentOutOfRange_TooSmall, WebSocketBuffer.MinSendBufferSize));
}
if (receiveBufferSize > WebSocketBuffer.MaxBufferSize)
{
throw new ArgumentOutOfRangeException(nameof(receiveBufferSize), receiveBufferSize,
SR.Format(SR.net_WebSockets_ArgumentOutOfRange_TooBig,
nameof(receiveBufferSize),
receiveBufferSize,
WebSocketBuffer.MaxBufferSize));
}
if (sendBufferSize > WebSocketBuffer.MaxBufferSize)
{
throw new ArgumentOutOfRangeException(nameof(sendBufferSize), sendBufferSize,
SR.Format(SR.net_WebSockets_ArgumentOutOfRange_TooBig,
nameof(sendBufferSize),
sendBufferSize,
WebSocketBuffer.MaxBufferSize));
}
}
internal static void ValidateInnerStream(Stream innerStream)
{
if (innerStream == null)
{
throw new ArgumentNullException(nameof(innerStream));
}
if (!innerStream.CanRead)
{
throw new ArgumentException(SR.net_writeonlystream, nameof(innerStream));
}
if (!innerStream.CanWrite)
{
throw new ArgumentException(SR.net_readonlystream, nameof(innerStream));
}
}
internal static void ThrowIfConnectionAborted(Stream connection, bool read)
{
if ((!read && !connection.CanWrite) ||
(read && !connection.CanRead))
{
throw new WebSocketException(WebSocketError.ConnectionClosedPrematurely);
}
}
internal static void ThrowPlatformNotSupportedException_WSPC()
{
throw new PlatformNotSupportedException(SR.net_WebSockets_UnsupportedPlatform);
}
private static void ThrowPlatformNotSupportedException_HTTPSYS()
{
throw new PlatformNotSupportedException(SR.net_WebSockets_UnsupportedPlatform);
}
internal static void ValidateArraySegment<T>(ArraySegment<T> arraySegment, string parameterName)
{
Debug.Assert(!string.IsNullOrEmpty(parameterName), "'parameterName' MUST NOT be NULL or string.Empty");
if (arraySegment.Array == null)
{
throw new ArgumentNullException(parameterName + "." + nameof(arraySegment.Array));
}
if (arraySegment.Offset < 0 || arraySegment.Offset > arraySegment.Array.Length)
{
throw new ArgumentOutOfRangeException(parameterName + "." + nameof(arraySegment.Offset));
}
if (arraySegment.Count < 0 || arraySegment.Count > (arraySegment.Array.Length - arraySegment.Offset))
{
throw new ArgumentOutOfRangeException(parameterName + "." + nameof(arraySegment.Count));
}
}
private static void EnsureHttpSysSupportsWebSockets()
{
if (!s_httpSysSupportsWebSockets)
{
ThrowPlatformNotSupportedException_HTTPSYS();
}
}
}
}
| 46.141921 | 157 | 0.595703 | [
"MIT"
] | Roibal/corefx | src/System.Net.HttpListener/src/System/Net/WebSockets/WebSocketHelpers.cs | 21,133 | C# |
// -------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
using System;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Azure.WebJobs.Extensions.DurableTask;
using Microsoft.Health.Dicom.Operations.DurableTask;
namespace Microsoft.Health.Dicom.Operations.Indexing
{
/// <summary>
/// Represents the options for a "re-index" function.
/// </summary>
public class QueryTagIndexingOptions
{
internal const string SectionName = "Indexing";
/// <summary>
/// Gets or sets the number of DICOM instances processed by a single activity.
/// </summary>
[Range(1, int.MaxValue)]
public int BatchSize { get; set; } = 100;
/// <summary>
/// Gets or sets the number of threads available for each batch.
/// </summary>
[Range(1, int.MaxValue)]
public int BatchThreadCount { get; set; } = 5;
/// <summary>
/// Gets or sets the maximum number of concurrent batches processed at a given time.
/// </summary>
[Range(1, int.MaxValue)]
public int MaxParallelBatches { get; set; } = 10;
/// <summary>
/// Gets the maximum number of DICOM instances that are processed concurrently
/// across all activities for a single orchestration instance.
/// </summary>
public int MaxParallelCount => BatchSize * MaxParallelBatches;
/// <summary>
/// Gets or sets the <see cref="RetryOptions"/> for re-indexing activities.
/// </summary>
public RetryOptions ActivityRetryOptions { get; set; }
// TODO: Change this hackery. The problem is that the binder used to convert 1 or more properties
// found in an IConfiguration object into a user-defined type can only process types with a
// default ctor. Unfortunately, RetryOptions does not define a default ctor, despite
// all of its properties being mutable. This should probably be fixed by the durable extension framework.
[Required]
[SuppressMessage("CodeQuality", "IDE0052:Remove unread private members", Justification = "This property is set via reflection.")]
private RetryOptionsTemplate RetryOptions
{
get => ActivityRetryOptions == null
? null
: new RetryOptionsTemplate
{
BackoffCoefficient = ActivityRetryOptions.BackoffCoefficient,
FirstRetryInterval = ActivityRetryOptions.FirstRetryInterval,
MaxNumberOfAttempts = ActivityRetryOptions.MaxNumberOfAttempts,
MaxRetryInterval = ActivityRetryOptions.MaxRetryInterval,
RetryTimeout = ActivityRetryOptions.RetryTimeout,
};
set => ActivityRetryOptions = value == null
? null
: new RetryOptions(value.FirstRetryInterval, value.MaxNumberOfAttempts)
{
BackoffCoefficient = value.BackoffCoefficient,
MaxRetryInterval = value.MaxRetryInterval,
RetryTimeout = value.RetryTimeout,
};
}
}
}
| 44.848101 | 137 | 0.593283 | [
"MIT"
] | ChimpPACS/dicom-server | src/Microsoft.Health.Dicom.Operations/Indexing/QueryTagIndexingOptions.cs | 3,545 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("MatchNumbers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| 36.222222 | 82 | 0.742331 | [
"MIT"
] | nikolayvutov/CSharp | 08.RegEx/MatchNumbers/Properties/AssemblyInfo.cs | 980 | C# |
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace TestAPI.Areas.HelpPage.ModelDescriptions
{
public class ParameterDescription
{
public ParameterDescription()
{
Annotations = new Collection<ParameterAnnotation>();
}
public Collection<ParameterAnnotation> Annotations { get; private set; }
public string Documentation { get; set; }
public string Name { get; set; }
public ModelDescription TypeDescription { get; set; }
}
} | 25.619048 | 80 | 0.674721 | [
"MIT"
] | OasesOng/TestVS | TestAPI/TestAPI/Areas/HelpPage/ModelDescriptions/ParameterDescription.cs | 538 | C# |
using MindKeeper.Domain.Entities;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MindKeeper.Api.Services.Domains
{
public interface IDomainService
{
Task<List<DomainEntity>> GetAll();
}
}
| 19.75 | 42 | 0.738397 | [
"MIT"
] | vashov/mindkeeper-api | Source/MindKeeper.Api/Services/Domains/IDomainService.cs | 239 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
/// <summary>
/// The interface IGroupMemberOfCollectionWithReferencesRequestBuilder.
/// </summary>
public partial interface IGroupMemberOfCollectionWithReferencesRequestBuilder
{
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
IGroupMemberOfCollectionWithReferencesRequest Request();
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
IGroupMemberOfCollectionWithReferencesRequest Request(IEnumerable<Option> options);
/// <summary>
/// Gets an <see cref="IDirectoryObjectWithReferenceRequestBuilder"/> for the specified DirectoryObject.
/// </summary>
/// <param name="id">The ID for the DirectoryObject.</param>
/// <returns>The <see cref="IDirectoryObjectWithReferenceRequestBuilder"/>.</returns>
IDirectoryObjectWithReferenceRequestBuilder this[string id] { get; }
/// <summary>
/// Gets an <see cref="IGroupMemberOfCollectionReferencesRequestBuilder"/> for the references in the collection.
/// </summary>
/// <returns>The <see cref="IGroupMemberOfCollectionReferencesRequestBuilder"/>.</returns>
IGroupMemberOfCollectionReferencesRequestBuilder References { get; }
}
}
| 43.288889 | 153 | 0.619097 | [
"MIT"
] | MIchaelMainer/GraphAPI | src/Microsoft.Graph/Requests/Generated/IGroupMemberOfCollectionWithReferencesRequestBuilder.cs | 1,948 | C# |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace OpenSim.Services.Interfaces
{
public interface IBakedTextureService
{
byte[] Get(string id);
void Store(string id, byte[] data, int datalenght);
}
}
| 50.166667 | 80 | 0.745293 | [
"BSD-3-Clause"
] | mdickson/opensim | OpenSim/Services/Interfaces/IBakedTextureService.cs | 1,806 | C# |
using UIKit;
namespace SaveImageToDatabaseSampleApp.iOS
{
public class Application
{
static void Main(string[] args) => UIApplication.Main(args, null, nameof(AppDelegate));
}
}
| 19.9 | 95 | 0.693467 | [
"MIT"
] | CSharped/SaveImageToDatabaseSampleApp | SaveImageToDatabaseSampleApp.iOS/Main.cs | 201 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace CountOfOccurrences
{
class StartUp
{
static void Main()
{
var numbers = Console.ReadLine()
.Split()
.Select(int.Parse)
.ToArray();
var list = new int[1000];
foreach (var number in numbers)
{
list[number]++;
}
for (int i = 0; i < list.Length; i++)
{
if (list[i] != 0)
{
Console.WriteLine(i + " -> " + list[i] + " times");
}
}
}
}
}
| 20.151515 | 71 | 0.4 | [
"MIT"
] | SonicTheCat/Data-Structures | 02.Linear Data Structures Lists - Exercise/05.01.CountOfOccurrences/StartUp.cs | 667 | C# |
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2008 Jonathan Skeet. 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.
#endregion
#if NO_HASHSET
using System.Linq;
#endif
namespace MoreLinq
{
using System;
using System.Collections.Generic;
static partial class MoreEnumerable
{
/// <summary>
/// Returns all distinct elements of the given source, where "distinctness"
/// is determined via a projection and the default eqaulity comparer for the projected type.
/// </summary>
/// <remarks>
/// This operator uses deferred execution and streams the results, although
/// a set of already-seen keys is retained. If a key is seen multiple times,
/// only the first element with that key is returned.
/// </remarks>
/// <typeparam name="TSource">Type of the source sequence</typeparam>
/// <typeparam name="TKey">Type of the projected element</typeparam>
/// <param name="source">Source sequence</param>
/// <param name="keySelector">Projection for determining "distinctness"</param>
/// <returns>A sequence consisting of distinct elements from the source sequence,
/// comparing them by the specified key projection.</returns>
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
{
return source.DistinctBy(keySelector, null);
}
/// <summary>
/// Returns all distinct elements of the given source, where "distinctness"
/// is determined via a projection and the specified comparer for the projected type.
/// </summary>
/// <remarks>
/// This operator uses deferred execution and streams the results, although
/// a set of already-seen keys is retained. If a key is seen multiple times,
/// only the first element with that key is returned.
/// </remarks>
/// <typeparam name="TSource">Type of the source sequence</typeparam>
/// <typeparam name="TKey">Type of the projected element</typeparam>
/// <param name="source">Source sequence</param>
/// <param name="keySelector">Projection for determining "distinctness"</param>
/// <param name="comparer">The equality comparer to use to determine whether or not keys are equal.
/// If null, the default equality comparer for <c>TSource</c> is used.</param>
/// <returns>A sequence consisting of distinct elements from the source sequence,
/// comparing them by the specified key projection.</returns>
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
if (source == null) throw new ArgumentNullException("source");
if (keySelector == null) throw new ArgumentNullException("keySelector");
return DistinctByImpl(source, keySelector, comparer);
}
private static IEnumerable<TSource> DistinctByImpl<TSource, TKey>(IEnumerable<TSource> source,
Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
#if !NO_HASHSET
var knownKeys = new HashSet<TKey>(comparer);
foreach (var element in source)
{
if (knownKeys.Add(keySelector(element)))
{
yield return element;
}
}
#else
//
// On platforms where LINQ is available but no HashSet<T>
// (like on Silverlight), implement this operator using
// existing LINQ operators. Using GroupBy is slightly less
// efficient since it has do all the grouping work before
// it can start to yield any one element from the source.
//
return source.GroupBy(keySelector, comparer).Select(g => g.First());
#endif
}
}
} | 44.346154 | 107 | 0.647875 | [
"MIT"
] | 2E0PGS/Emby.Plugins | MediaBrowser.Plugins.Lastfm/Providers/MoreEnumerable.cs | 4,614 | 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("RedfieldWeather.Common")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RedfieldWeather.Common")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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("c9649039-c563-47b5-9e44-dbd369d53bb0")]
// 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.297297 | 84 | 0.747354 | [
"MIT"
] | erenken/redfieldweather | RedfieldWeather/RedfieldWeather.Common/Properties/AssemblyInfo.cs | 1,420 | C# |
namespace Xamarin.iOS.Tasks
{
public class CompileEntitlements : CompileEntitlementsTaskBase
{
}
}
| 14.714286 | 63 | 0.786408 | [
"BSD-3-Clause"
] | 1975781737/xamarin-macios | msbuild/Xamarin.iOS.Tasks/Tasks/CompileEntitlements.cs | 105 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using ApprovalTests.Reporters;
using Exceptionless.Api.Tests.Utility;
using Exceptionless.Core.Extensions;
using Exceptionless.Core.Models;
using Exceptionless.Core.Plugins.Formatting;
using Newtonsoft.Json;
using Xunit;
namespace Exceptionless.Api.Tests.Plugins {
[UseReporter(typeof(DiffReporter))]
public class SummaryDataTests {
private readonly FormattingPluginManager _formattingPluginManager = IoC.GetInstance<FormattingPluginManager>();
[Theory]
[MemberData("Events")]
public void EventSummaryData(string path) {
var settings = IoC.GetInstance<JsonSerializerSettings>();
settings.Formatting = Formatting.Indented;
var json = File.ReadAllText(path);
var ev = json.FromJson<PersistentEvent>(settings);
Assert.NotNull(ev);
var data = _formattingPluginManager.GetEventSummaryData(ev);
var summary = new EventSummaryModel {
TemplateKey = data.TemplateKey,
Id = ev.Id,
Date = ev.Date,
Data = data.Data
};
ApprovalsUtility.VerifyFile(Path.ChangeExtension(path, "summary.json"), JsonConvert.SerializeObject(summary, settings));
}
[Theory]
[MemberData("Stacks")]
public void StackSummaryData(string path) {
var settings = IoC.GetInstance<JsonSerializerSettings>();
settings.Formatting = Formatting.Indented;
var json = File.ReadAllText(path);
var stack = json.FromJson<Stack>(settings);
Assert.NotNull(stack);
var data = _formattingPluginManager.GetStackSummaryData(stack);
var summary = new StackSummaryModel {
TemplateKey = data.TemplateKey,
Data = data.Data,
Id = stack.Id,
Title = stack.Title,
Total = 1,
};
ApprovalsUtility.VerifyFile(Path.ChangeExtension(path, "summary.json"), JsonConvert.SerializeObject(summary, settings));
}
public static IEnumerable<object[]> Events {
get {
var result = new List<object[]>();
foreach (var file in Directory.GetFiles(@"..\..\Search\Data\", "event*.json", SearchOption.AllDirectories))
if (!file.EndsWith("summary.json"))
result.Add(new object[] { Path.GetFullPath(file) });
return result.ToArray();
}
}
public static IEnumerable<object[]> Stacks {
get {
var result = new List<object[]>();
foreach (var file in Directory.GetFiles(@"..\..\Search\Data\", "stack*.json", SearchOption.AllDirectories))
if (!file.EndsWith("summary.json"))
result.Add(new object[] { Path.GetFullPath(file) });
return result.ToArray();
}
}
}
} | 36.309524 | 132 | 0.59082 | [
"Apache-2.0"
] | ToddZhao/Exceptionless | Source/Tests/Plugins/SummaryDataTests.cs | 3,052 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.KeyVault.Fluent
{
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.Azure.KeyVault.Models;
using Microsoft.Azure.Management.KeyVault.Fluent;
using Microsoft.Azure.Management.KeyVault.Fluent.Secret.Definition;
using Microsoft.Azure.Management.KeyVault.Fluent.Secret.Update;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
internal partial class SecretImpl
{
/// <summary>
/// Specifies the secret value.
/// </summary>
/// <param name="value">The string value of the secret.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Secret.Definition.IWithCreate Microsoft.Azure.Management.KeyVault.Fluent.Secret.Definition.IWithValue.WithValue(string value)
{
return this.WithValue(value) as Microsoft.Azure.Management.KeyVault.Fluent.Secret.Definition.IWithCreate;
}
/// <summary>
/// Specifies the new version of the value to be added.
/// </summary>
/// <param name="value">The value for the new version.</param>
/// <return>The next stage of the secret update.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Secret.Update.IUpdate Microsoft.Azure.Management.KeyVault.Fluent.Secret.Update.IWithValue.WithValue(string value)
{
return this.WithValue(value) as Microsoft.Azure.Management.KeyVault.Fluent.Secret.Update.IUpdate;
}
/// <summary>
/// Specifies the secret attributes.
/// </summary>
/// <param name="attributes">The object attributes managed by Key Vault service.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Secret.Definition.IWithCreate Microsoft.Azure.Management.KeyVault.Fluent.Secret.Definition.IWithAttributes.WithAttributes(Attributes attributes)
{
return this.WithAttributes(attributes) as Microsoft.Azure.Management.KeyVault.Fluent.Secret.Definition.IWithCreate;
}
/// <summary>
/// Specifies the secret attributes.
/// </summary>
/// <param name="attributes">The object attributes managed by Key Vault service.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Secret.Update.IUpdate Microsoft.Azure.Management.KeyVault.Fluent.Secret.Update.IWithAttributes.WithAttributes(Attributes attributes)
{
return this.WithAttributes(attributes) as Microsoft.Azure.Management.KeyVault.Fluent.Secret.Update.IUpdate;
}
/// <summary>
/// Specifies the secret content type.
/// </summary>
/// <param name="contentType">The content type.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Secret.Definition.IWithCreate Microsoft.Azure.Management.KeyVault.Fluent.Secret.Definition.IWithContentType.WithContentType(string contentType)
{
return this.WithContentType(contentType) as Microsoft.Azure.Management.KeyVault.Fluent.Secret.Definition.IWithCreate;
}
/// <summary>
/// Specifies the secret content type.
/// </summary>
/// <param name="contentType">The content type.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Secret.Update.IUpdate Microsoft.Azure.Management.KeyVault.Fluent.Secret.Update.IWithContentType.WithContentType(string contentType)
{
return this.WithContentType(contentType) as Microsoft.Azure.Management.KeyVault.Fluent.Secret.Update.IUpdate;
}
/// <summary>
/// Specifies the version the secret show use.
/// </summary>
/// <param name="version">The version of the secret.</param>
/// <return>The next stage of the secret update.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Secret.Update.IUpdate Microsoft.Azure.Management.KeyVault.Fluent.Secret.Update.IWithVersion.WithVersion(string version)
{
return this.WithVersion(version) as Microsoft.Azure.Management.KeyVault.Fluent.Secret.Update.IUpdate;
}
/// <summary>
/// Gets the resource ID string.
/// </summary>
string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasId.Id
{
get
{
return this.Id();
}
}
/// <return>A list of individual secret versions with the same secret name.</return>
async Task<Microsoft.Azure.Management.ResourceManager.Fluent.Core.IPagedCollection<Microsoft.Azure.Management.KeyVault.Fluent.ISecret>> Microsoft.Azure.Management.KeyVault.Fluent.ISecret.ListVersionsAsync(CancellationToken cancellationToken)
{
return await this.ListVersionsAsync(cancellationToken);
}
/// <summary>
/// Gets the secret management attributes.
/// </summary>
Microsoft.Azure.KeyVault.Models.SecretAttributes Microsoft.Azure.Management.KeyVault.Fluent.ISecret.Attributes
{
get
{
return this.Attributes() as Microsoft.Azure.KeyVault.Models.SecretAttributes;
}
}
/// <summary>
/// Gets application specific metadata in the form of key-value pairs.
/// </summary>
System.Collections.Generic.IReadOnlyDictionary<string, string> Microsoft.Azure.Management.KeyVault.Fluent.ISecret.Tags
{
get
{
return this.Tags() as System.Collections.Generic.IReadOnlyDictionary<string, string>;
}
}
/// <summary>
/// Gets the secret value.
/// </summary>
string Microsoft.Azure.Management.KeyVault.Fluent.ISecret.Value
{
get
{
return this.Value();
}
}
/// <summary>
/// Gets the corresponding key backing the KV certificate if this is a
/// secret backing a KV certificate.
/// </summary>
string Microsoft.Azure.Management.KeyVault.Fluent.ISecret.Kid
{
get
{
return this.Kid();
}
}
/// <summary>
/// Gets type of the secret value such as a password.
/// </summary>
string Microsoft.Azure.Management.KeyVault.Fluent.ISecret.ContentType
{
get
{
return this.ContentType();
}
}
/// <summary>
/// Gets true if the secret's lifetime is managed by key vault. If this is a key
/// backing a certificate, then managed will be true.
/// </summary>
bool Microsoft.Azure.Management.KeyVault.Fluent.ISecret.Managed
{
get
{
return this.Managed();
}
}
/// <return>A list of individual secret versions with the same secret name.</return>
System.Collections.Generic.IEnumerable<Microsoft.Azure.Management.KeyVault.Fluent.ISecret> Microsoft.Azure.Management.KeyVault.Fluent.ISecret.ListVersions()
{
return this.ListVersions() as System.Collections.Generic.IEnumerable<Microsoft.Azure.Management.KeyVault.Fluent.ISecret>;
}
/// <summary>
/// Specifies the tags on the secret.
/// </summary>
/// <param name="tags">The key value pair of the tags.</param>
/// <return>The next stage of the definition.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Secret.Definition.IWithCreate Microsoft.Azure.Management.KeyVault.Fluent.Secret.Definition.IWithTags.WithTags(IDictionary<string, string> tags)
{
return this.WithTags(tags) as Microsoft.Azure.Management.KeyVault.Fluent.Secret.Definition.IWithCreate;
}
/// <summary>
/// Specifies the tags on the secret.
/// </summary>
/// <param name="tags">The key value pair of the tags.</param>
/// <return>The next stage of the update.</return>
Microsoft.Azure.Management.KeyVault.Fluent.Secret.Update.IUpdate Microsoft.Azure.Management.KeyVault.Fluent.Secret.Update.IWithTags.WithTags(IDictionary<string, string> tags)
{
return this.WithTags(tags) as Microsoft.Azure.Management.KeyVault.Fluent.Secret.Update.IUpdate;
}
}
} | 44.705584 | 249 | 0.647326 | [
"MIT"
] | Azure/azure-libraries-for-net | src/ResourceManagement/KeyVault/Domain/InterfaceImpl/SecretImpl.cs | 8,807 | C# |
using System.Windows.Documents;
namespace DaveSexton.XmlGel.Maml.Documents.Visitors
{
internal sealed class FlowDocumentToReferenceWithSyntaxDocumentVisitor : FlowDocumentToMamlVisitor
{
public FlowDocumentToReferenceWithSyntaxDocumentVisitor(FlowDocument flowDocument, MamlDocument document)
: base(flowDocument, document)
{
}
}
} | 28.75 | 107 | 0.831884 | [
"Apache-2.0"
] | RxDave/XMLGel | Source/DaveSexton.XmlGel/MAML/Documents/Visitors/FlowDocumentToReferenceWithSyntaxDocumentVisitor.cs | 347 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.