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.Net;
using Construct.Base.Test.Integration.Base;
using Construct.Core.Data.Response;
using Construct.User.Data.Request;
using Construct.User.Data.Response;
using NUnit.Framework;
namespace Construct.User.Test.Integration.Controllers
{
public class UserControllerTest : BaseIntegrationTest
{
/// <summary>
/// Starts the program.
/// </summary>
[SetUp]
public void SetUpProgram()
{
this.StartProgram<Program>();
this.WaitForApp("User");
}
/// <summary>
/// Tests registering and getting a user.
/// </summary>
[Test]
public void TestRegisterUser()
{
// Register a user.
var userRequest = new RegisterUserRequest()
{
HashedId = "test_hash",
Name = "Test User",
Email = "test@email",
College = "Test College",
Year = "Test Year",
};
var (registerResponse, registerResponseCode) = this.Post<BaseSuccessResponse>("User", "/user/register", userRequest);
Assert.AreEqual(HttpStatusCode.OK, registerResponseCode);
Assert.AreEqual("success",registerResponse.Status);
// Get the registered user.
var (getResponse, getResponseCode) = this.Get<GetUserResponse>("User", "/user/get?hashedid=test_hash");
Assert.AreEqual(HttpStatusCode.OK, getResponseCode);
Assert.AreEqual("success", getResponse.Status);
Assert.AreEqual("Test User", getResponse.Name);
Assert.AreEqual("test@email", getResponse.Email);
Assert.AreEqual(0, getResponse.OwedPrintBalance);
Assert.AreEqual(0, getResponse.Permissions.Count);
// Stop the program.
// Can't be done in a TearDown since the ASP.NET app prevents it from running.
this.StopProgram();
}
/// <summary>
/// Tests registering duplicate users.
/// </summary>
[Test]
public void TestRegisterUserDuplicate()
{
// Register a user.
var userRequest = new RegisterUserRequest()
{
HashedId = "test_hash",
Name = "Test User",
Email = "test@email",
College = "Test College",
Year = "Test Year",
};
var (registerResponse, registerResponseCode) = this.Post<GenericStatusResponse>("User", "/user/register", userRequest);
Assert.AreEqual(HttpStatusCode.OK, registerResponseCode);
Assert.AreEqual("success",registerResponse.Status);
// Re-send the request and check that HTTP 409 Conflict is returned.
(registerResponse, registerResponseCode) = this.Post<GenericStatusResponse>("User", "/user/register", userRequest);
Assert.AreEqual(HttpStatusCode.Conflict, registerResponseCode);
Assert.AreEqual("duplicate-user", registerResponse.Status);
// Stop the program.
// Can't be done in a TearDown since the ASP.NET app prevents it from running.
this.StopProgram();
}
/// <summary>
/// Tests getting a user that isn't registered.
/// </summary>
[Test]
public void TestGetUserNotFound()
{
// Get the user and check that it was not found.
var (getResponse, getResponseCode) = this.Get<GenericStatusResponse>("User", "/user/get?hashedid=test_hash");
Assert.AreEqual(HttpStatusCode.NotFound, getResponseCode);
Assert.AreEqual("user-not-found", getResponse.Status);
// Stop the program.
// Can't be done in a TearDown since the ASP.NET app prevents it from running.
this.StopProgram();
}
}
}
| 39.84
| 131
| 0.57254
|
[
"MIT"
] |
ChrisFigura/Makerspace-Database-Server
|
Construct.User.Test/Integration/Controllers/UserControllerTest.cs
| 3,986
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Equinox.Application.ViewModels
{
public class ConsultaCepViewModel
{
public string CEP { get; set; }
public string Logradouro { get; set; }
public string Complemento { get; set; }
public string Bairro { get; set; }
public string Localidade { get; set; }
public string UF { get; set; }
public string IBGE { get; set; }
public string GIA { get; set; }
public string DDD { get; set; }
public string SIAFI { get; set; }
}
}
| 27.826087
| 47
| 0.625
|
[
"MIT"
] |
MitsuiSama/MitsuiNox
|
src/Equinox.Application/ViewModels/ConsultaCepViewModel.cs
| 642
|
C#
|
using System;
using DotNetCore.CAP.Models;
namespace DotNetCore.CAP.Processor.States
{
public class ScheduledState : IState
{
public const string StateName = "Scheduled";
public TimeSpan? ExpiresAfter => null;
public string Name => StateName;
public void Apply(CapPublishedMessage message, IStorageTransaction transaction)
{
}
public void Apply(CapReceivedMessage message, IStorageTransaction transaction)
{
}
}
}
| 22.863636
| 87
| 0.664016
|
[
"MIT"
] |
hybirdtheory/CAP
|
src/DotNetCore.CAP/Processor/States/IState.Scheduled.cs
| 505
|
C#
|
using NUnit.Framework;
namespace Nustache.Core.Tests
{
[TestFixture]
public class RenderContext_Behaviour_Support
{
[Test, ExpectedException(ExpectedException = typeof(NustacheDataContextMissException),
ExpectedMessage = "Path : . is undefined, RaiseExceptionOnDataContextMiss : true.")]
public void It_throws_an_exception_when_array_is_null_and_the_render_context_behaviour_throw_on_miss_is_true()
{
Render.StringToString("before{{#.}}{{.}}{{/.}}after", null , new RenderContextBehaviour{ RaiseExceptionOnDataContextMiss = true});
}
[Test, ExpectedException(ExpectedException = typeof(NustacheEmptyStringException),
ExpectedMessage = "Path : foo is an empty string, RaiseExceptionOnEmptyStringValue : true.")]
public void It_throws_an_exception_when_the_data_is_an_empty_string_and_the_render_context_behaviour_throw_on_empty_string_is_true()
{
Render.StringToString("before{{foo}}after", new{ foo = string.Empty}, new RenderContextBehaviour { RaiseExceptionOnEmptyStringValue = true });
}
[Test, ExpectedException(ExpectedException = typeof(NustacheDataContextMissException),
ExpectedMessage = "Path : foo is undefined, RaiseExceptionOnDataContextMiss : true.")]
public void It_throws_an_exception_when_there_is_no_data_and_the_render_context_behaviour_throw_on_miss_is_true()
{
Render.StringToString("before{{foo}}after", null, new RenderContextBehaviour { RaiseExceptionOnDataContextMiss = true });
}
[Test, ExpectedException(ExpectedException = typeof(NustacheDataContextMissException),
ExpectedMessage = "Path : foo.bar is undefined, RaiseExceptionOnDataContextMiss : true.")]
public void It_throws_an_exception_when_there_is_no_nested_data_and_the_render_context_behaviour_throw_on_miss_is_true()
{
Render.StringToString("before{{foo.bar}}after", new { foo = new { } }, new RenderContextBehaviour { RaiseExceptionOnDataContextMiss = true });
}
[Test, ExpectedException(ExpectedException = typeof(NustacheEmptyStringException),
ExpectedMessage = "Path : foo is an empty string, RaiseExceptionOnEmptyStringValue : true.")]
public void It_throws_an_exception_when_section_is_mapped_to_empty_string_and_the_render_context_behaviour_throw_on_empty_string_is_true()
{
Render.StringToString("before{{#foo}}FOO{{/foo}}after", new { foo = string.Empty }, new RenderContextBehaviour { RaiseExceptionOnEmptyStringValue = true });
}
[Test, ExpectedException(ExpectedException = typeof(NustacheDataContextMissException),
ExpectedMessage = "Path : foo is undefined, RaiseExceptionOnDataContextMiss : true.")]
public void It_throws_an_exception_when_section_is_mapped_to_null_and_the_render_context_behaviour_throw_on_miss_is_true()
{
Render.StringToString("before{{#foo}}FOO{{/foo}}after", new { foo = (string)null }, new RenderContextBehaviour { RaiseExceptionOnDataContextMiss = true });
}
[Test]
public void It_does_not_throw_an_exception_when_there_is_no_data_and_the_render_context_behaviour_throw_on_miss_is_false()
{
var result = Render.StringToString("before{{foo}}after", null, new RenderContextBehaviour { RaiseExceptionOnDataContextMiss = false });
Assert.AreEqual("beforeafter", result);
}
[Test]
public void Use_custom_encoder()
{
var result = Render.StringToString("before{{foo}}after", new {foo = string.Empty},
new RenderContextBehaviour {HtmlEncoder = text => "middle"});
Assert.AreEqual("beforemiddleafter", result);
}
}
}
| 58.676923
| 168
| 0.722601
|
[
"MIT"
] |
aloisdg/Nustache
|
Nustache.Core.Tests/RenderContext_Behaviour_Support.cs
| 3,816
|
C#
|
using System;
using System.Collections.Generic;
using System.IO;
using Phantasma.Core;
using Phantasma.Cryptography;
using Phantasma.Storage.Utils;
using Phantasma.Numerics;
namespace Phantasma.Network.P2P.Messages
{
[Flags]
public enum RequestKind
{
None = 0,
Peers = 0x1,
Chains = 0x2,
Mempool = 0x4,
Blocks = 0x8,
}
public sealed class RequestMessage : Message
{
public readonly RequestKind Kind;
public readonly string NexusName;
private Dictionary<string, BigInteger> _blockFetches;
public IEnumerable<KeyValuePair<string, BigInteger>> Blocks => _blockFetches;
public RequestMessage(RequestKind kind, string nexusName, Address address) :base(Opcode.REQUEST, address)
{
Kind = kind;
NexusName = nexusName;
}
public void SetBlocks(Dictionary<string, BigInteger> blockFetches)
{
this._blockFetches = blockFetches;
}
internal static RequestMessage FromReader(Address address, BinaryReader reader)
{
var kind = (RequestKind)reader.ReadByte();
var nexusName = reader.ReadVarString();
var msg = new RequestMessage(kind, nexusName, address);
if (kind.HasFlag(RequestKind.Blocks))
{
var count = reader.ReadVarInt();
var fetches = new Dictionary<string, BigInteger>();
while (count > 0)
{
var key = reader.ReadVarString();
var height = reader.ReadBigInteger();
fetches[key] = height;
count--;
}
msg.SetBlocks(fetches);
}
return msg;
}
protected override void OnSerialize(BinaryWriter writer)
{
writer.Write((byte)Kind);
writer.WriteVarString(NexusName);
if (Kind.HasFlag(RequestKind.Blocks))
{
Throw.IfNull(_blockFetches, nameof(_blockFetches));
Throw.If(_blockFetches.Count > 255, "max chain block fetches per request reached");
writer.WriteVarInt(_blockFetches.Count);
foreach (var entry in _blockFetches)
{
writer.WriteVarString(entry.Key);
writer.Write((uint)entry.Value);
}
}
}
}
}
| 29.903614
| 113
| 0.560435
|
[
"MIT"
] |
GOATi/PhantasmaChain
|
Phantasma.P2P/Messages/RequestMessage.cs
| 2,484
|
C#
|
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Lime.Messaging.Resources;
using Lime.Protocol;
using NSubstitute;
using Serilog;
using Shouldly;
using Take.Blip.Client.Extensions.Contacts;
using Take.Blip.Client.Extensions.Directory;
using Take.Blip.Client.Receivers;
using Xunit;
namespace Take.Blip.Client.UnitTests.Receivers
{
public class ContactMessageReceiverBaseTests : TestsBase
{
public ContactMessageReceiverBaseTests()
{
ContactExtension = Substitute.For<IContactExtension>();
DirectoryExtension = Substitute.For<IDirectoryExtension>();
CacheExpiration = TimeSpan.FromMilliseconds(250);
}
public IContactExtension ContactExtension { get; }
public IDirectoryExtension DirectoryExtension { get; set; }
public bool CacheLocally { get; set; }
public TimeSpan CacheExpiration { get; set; }
public TestContactMessageReceiver GetTarget()
{
return new TestContactMessageReceiver(
ContactExtension,
DirectoryExtension,
Substitute.For<ILogger>(),
CacheLocally,
CacheExpiration
);
}
[Fact]
public async Task ReceiveMessageShouldGetContactFromContacts()
{
// Arrange
var message = Dummy.CreateMessage();
var identity = message.From.ToIdentity();
var contact = Dummy.CreateContact();
contact.Identity = identity;
ContactExtension
.GetAsync(identity, Arg.Any<CancellationToken>())
.Returns(contact);
var target = GetTarget();
// Act
await target.ReceiveAsync(message, CancellationToken);
// Assert
target.ReceivedItems.Count.ShouldBe(1);
target.ReceivedItems[0].message.ShouldBe(message);
var actualContact = target.ReceivedItems[0].contact;
actualContact.ShouldNotBeNull();
foreach (var property in typeof(Contact).GetProperties())
{
property
.GetValue(actualContact)
.ShouldBe(
property.GetValue(contact));
}
}
[Fact]
public async Task ReceiveMessageShouldGetContactFromDirectoryWhenNotInContacts()
{
// Arrange
var message = Dummy.CreateMessage();
var identity = message.From.ToIdentity();
var account = Dummy.CreateAccount();
account.Identity = identity;
DirectoryExtension
.GetDirectoryAccountAsync(identity, Arg.Any<CancellationToken>())
.Returns(account);
var target = GetTarget();
// Act
await target.ReceiveAsync(message, CancellationToken);
// Assert
target.ReceivedItems.Count.ShouldBe(1);
target.ReceivedItems[0].message.ShouldBe(message);
var actualContact = target.ReceivedItems[0].contact;
actualContact.ShouldNotBeNull();
actualContact.Name.ShouldBe(account.FullName);
foreach (var property in typeof(ContactDocument).GetProperties())
{
property
.GetValue(actualContact)
.ShouldBe(
property.GetValue(account));
}
}
[Fact]
public async Task ReceiveMessageTwiceShouldGetContactFromCacheOnSecondTime()
{
// Arrange
CacheLocally = true;
var message = Dummy.CreateMessage();
var identity = message.From.ToIdentity();
var contact = Dummy.CreateContact();
contact.Identity = identity;
ContactExtension
.GetAsync(identity, Arg.Any<CancellationToken>())
.Returns(contact);
var target = GetTarget();
// Act
await target.ReceiveAsync(message, CancellationToken);
await target.ReceiveAsync(message, CancellationToken);
// Assert
ContactExtension.Received(1).GetAsync(identity, CancellationToken);
}
[Fact]
public async Task ReceiveMessageTwiceShouldGetContactFromContactsTwiceWhenCaseIsDisabled()
{
// Arrange
CacheLocally = false;
var message = Dummy.CreateMessage();
var identity = message.From.ToIdentity();
var contact = Dummy.CreateContact();
contact.Identity = identity;
ContactExtension
.GetAsync(identity, Arg.Any<CancellationToken>())
.Returns(contact);
var target = GetTarget();
// Act
await target.ReceiveAsync(message, CancellationToken);
await target.ReceiveAsync(message, CancellationToken);
// Assert
ContactExtension.Received(2).GetAsync(identity, CancellationToken);
}
[Fact]
public async Task ReceiveMessageTwiceShouldGetContactFromContactsTwiceWhenCaseExpires()
{
// Arrange
CacheLocally = true;
var message = Dummy.CreateMessage();
var identity = message.From.ToIdentity();
var contact = Dummy.CreateContact();
contact.Identity = identity;
ContactExtension
.GetAsync(identity, Arg.Any<CancellationToken>())
.Returns(contact);
var target = GetTarget();
// Act
await target.ReceiveAsync(message, CancellationToken);
await Task.Delay(CacheExpiration + CacheExpiration);
await target.ReceiveAsync(message, CancellationToken);
// Assert
ContactExtension.Received(2).GetAsync(identity, CancellationToken);
}
}
public class TestContactMessageReceiver : ContactMessageReceiverBase
{
public TestContactMessageReceiver(
IContactExtension contactExtension,
IDirectoryExtension directoryExtension,
ILogger logger,
bool cacheLocally = true,
TimeSpan cacheExpiration = default) : base(contactExtension,
directoryExtension,
logger,
cacheLocally,
cacheExpiration)
{
ReceivedItems = new List<(Message, Contact)>();
}
public List<(Message message, Contact contact)> ReceivedItems { get; }
protected override Task ReceiveAsync(Message message, Contact contact, CancellationToken cancellationToken = default(CancellationToken))
{
ReceivedItems.Add((message, contact));
return Task.CompletedTask;
}
}
}
| 34.140097
| 144
| 0.579171
|
[
"Apache-2.0"
] |
BeltrameJP/blip-sdk-csharp
|
src/Take.Blip.Client.UnitTests/Receivers/ContactMessageReceiverBaseTests.cs
| 7,067
|
C#
|
// Portions of this source file are adapted from the Windows Presentation Foundation project.
// (https://github.com/dotnet/wpf/)
//
// Licensed to The Avalonia Project under MIT License, courtesy of The .NET Foundation.
using System;
using Avalonia.Controls.Metadata;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Metadata;
using Avalonia.Utilities;
namespace Avalonia.Controls.Primitives
{
[PseudoClasses(":vertical", ":horizontal")]
public class Track : Control
{
public static readonly DirectProperty<Track, double> MinimumProperty =
RangeBase.MinimumProperty.AddOwner<Track>(o => o.Minimum, (o, v) => o.Minimum = v);
public static readonly DirectProperty<Track, double> MaximumProperty =
RangeBase.MaximumProperty.AddOwner<Track>(o => o.Maximum, (o, v) => o.Maximum = v);
public static readonly DirectProperty<Track, double> ValueProperty =
RangeBase.ValueProperty.AddOwner<Track>(o => o.Value, (o, v) => o.Value = v);
public static readonly StyledProperty<double> ViewportSizeProperty =
ScrollBar.ViewportSizeProperty.AddOwner<Track>();
public static readonly StyledProperty<Orientation> OrientationProperty =
ScrollBar.OrientationProperty.AddOwner<Track>();
public static readonly StyledProperty<Thumb> ThumbProperty =
AvaloniaProperty.Register<Track, Thumb>(nameof(Thumb));
public static readonly StyledProperty<Button> IncreaseButtonProperty =
AvaloniaProperty.Register<Track, Button>(nameof(IncreaseButton));
public static readonly StyledProperty<Button> DecreaseButtonProperty =
AvaloniaProperty.Register<Track, Button>(nameof(DecreaseButton));
public static readonly StyledProperty<bool> IsDirectionReversedProperty =
AvaloniaProperty.Register<Track, bool>(nameof(IsDirectionReversed));
public static readonly StyledProperty<bool> IgnoreThumbDragProperty =
AvaloniaProperty.Register<Track, bool>(nameof(IsThumbDragHandled));
private double _minimum;
private double _maximum = 100.0;
private double _value;
static Track()
{
ThumbProperty.Changed.AddClassHandler<Track>((x, e) => x.ThumbChanged(e));
IncreaseButtonProperty.Changed.AddClassHandler<Track>((x, e) => x.ButtonChanged(e));
DecreaseButtonProperty.Changed.AddClassHandler<Track>((x, e) => x.ButtonChanged(e));
AffectsArrange<Track>(MinimumProperty, MaximumProperty, ValueProperty, OrientationProperty);
}
public Track()
{
UpdatePseudoClasses(Orientation);
}
public double Minimum
{
get { return _minimum; }
set { SetAndRaise(MinimumProperty, ref _minimum, value); }
}
public double Maximum
{
get { return _maximum; }
set { SetAndRaise(MaximumProperty, ref _maximum, value); }
}
public double Value
{
get { return _value; }
set { SetAndRaise(ValueProperty, ref _value, value); }
}
public double ViewportSize
{
get { return GetValue(ViewportSizeProperty); }
set { SetValue(ViewportSizeProperty, value); }
}
public Orientation Orientation
{
get { return GetValue(OrientationProperty); }
set { SetValue(OrientationProperty, value); }
}
[Content]
public Thumb Thumb
{
get { return GetValue(ThumbProperty); }
set { SetValue(ThumbProperty, value); }
}
public Button IncreaseButton
{
get { return GetValue(IncreaseButtonProperty); }
set { SetValue(IncreaseButtonProperty, value); }
}
public Button DecreaseButton
{
get { return GetValue(DecreaseButtonProperty); }
set { SetValue(DecreaseButtonProperty, value); }
}
public bool IsDirectionReversed
{
get { return GetValue(IsDirectionReversedProperty); }
set { SetValue(IsDirectionReversedProperty, value); }
}
public bool IsThumbDragHandled
{
get { return GetValue(IgnoreThumbDragProperty); }
set { SetValue(IgnoreThumbDragProperty, value); }
}
private double ThumbCenterOffset { get; set; }
private double Density { get; set; }
/// <summary>
/// Calculates the distance along the <see cref="Thumb"/> of a specified point along the
/// track.
/// </summary>
/// <param name="point">The specified point.</param>
/// <returns>
/// The distance between the Thumb and the specified pt value.
/// </returns>
public virtual double ValueFromPoint(Point point)
{
double val;
// Find distance from center of thumb to given point.
if (Orientation == Orientation.Horizontal)
{
val = Value + ValueFromDistance(point.X - ThumbCenterOffset, point.Y - (Bounds.Height * 0.5));
}
else
{
val = Value + ValueFromDistance(point.X - (Bounds.Width * 0.5), point.Y - ThumbCenterOffset);
}
return Math.Max(Minimum, Math.Min(Maximum, val));
}
/// <summary>
/// Calculates the change in the <see cref="Value"/> of the <see cref="Track"/> when the
/// <see cref="Thumb"/> moves.
/// </summary>
/// <param name="horizontal">The horizontal displacement of the thumb.</param>
/// <param name="vertical">The vertical displacement of the thumb.</param>
public virtual double ValueFromDistance(double horizontal, double vertical)
{
double scale = IsDirectionReversed ? -1 : 1;
if (Orientation == Orientation.Horizontal)
{
return scale * horizontal * Density;
}
else
{
// Increases in y cause decreases in Sliders value
return -1 * scale * vertical * Density;
}
}
protected override Size MeasureOverride(Size availableSize)
{
Size desiredSize = new Size(0.0, 0.0);
// Only measure thumb.
// Repeat buttons will be sized based on thumb
if (Thumb != null)
{
Thumb.Measure(availableSize);
desiredSize = Thumb.DesiredSize;
}
if (!double.IsNaN(ViewportSize))
{
// ScrollBar can shrink to 0 in the direction of scrolling
if (Orientation == Orientation.Vertical)
desiredSize = desiredSize.WithHeight(0.0);
else
desiredSize = desiredSize.WithWidth(0.0);
}
return desiredSize;
}
protected override Size ArrangeOverride(Size arrangeSize)
{
double decreaseButtonLength, thumbLength, increaseButtonLength;
var isVertical = Orientation == Orientation.Vertical;
var viewportSize = Math.Max(0.0, ViewportSize);
// If viewport is NaN, compute thumb's size based on its desired size,
// otherwise compute the thumb base on the viewport and extent properties
if (double.IsNaN(ViewportSize))
{
ComputeSliderLengths(arrangeSize, isVertical, out decreaseButtonLength, out thumbLength, out increaseButtonLength);
}
else
{
// Don't arrange if there's not enough content or the track is too small
if (!ComputeScrollBarLengths(arrangeSize, viewportSize, isVertical, out decreaseButtonLength, out thumbLength, out increaseButtonLength))
{
return arrangeSize;
}
}
// Layout the pieces of track
var offset = new Point();
var pieceSize = arrangeSize;
var isDirectionReversed = IsDirectionReversed;
if (isVertical)
{
CoerceLength(ref decreaseButtonLength, arrangeSize.Height);
CoerceLength(ref increaseButtonLength, arrangeSize.Height);
CoerceLength(ref thumbLength, arrangeSize.Height);
offset = offset.WithY(isDirectionReversed ? decreaseButtonLength + thumbLength : 0.0);
pieceSize = pieceSize.WithHeight(increaseButtonLength);
if (IncreaseButton != null)
{
IncreaseButton.Arrange(new Rect(offset, pieceSize));
}
offset = offset.WithY(isDirectionReversed ? 0.0 : increaseButtonLength + thumbLength);
pieceSize = pieceSize.WithHeight(decreaseButtonLength);
if (DecreaseButton != null)
{
DecreaseButton.Arrange(new Rect(offset, pieceSize));
}
offset = offset.WithY(isDirectionReversed ? decreaseButtonLength : increaseButtonLength);
pieceSize = pieceSize.WithHeight(thumbLength);
if (Thumb != null)
{
Thumb.Arrange(new Rect(offset, pieceSize));
}
ThumbCenterOffset = offset.Y + (thumbLength * 0.5);
}
else
{
CoerceLength(ref decreaseButtonLength, arrangeSize.Width);
CoerceLength(ref increaseButtonLength, arrangeSize.Width);
CoerceLength(ref thumbLength, arrangeSize.Width);
offset = offset.WithX(isDirectionReversed ? increaseButtonLength + thumbLength : 0.0);
pieceSize = pieceSize.WithWidth(decreaseButtonLength);
if (DecreaseButton != null)
{
DecreaseButton.Arrange(new Rect(offset, pieceSize));
}
offset = offset.WithX(isDirectionReversed ? 0.0 : decreaseButtonLength + thumbLength);
pieceSize = pieceSize.WithWidth(increaseButtonLength);
if (IncreaseButton != null)
{
IncreaseButton.Arrange(new Rect(offset, pieceSize));
}
offset = offset.WithX(isDirectionReversed ? increaseButtonLength : decreaseButtonLength);
pieceSize = pieceSize.WithWidth(thumbLength);
if (Thumb != null)
{
Thumb.Arrange(new Rect(offset, pieceSize));
}
ThumbCenterOffset = offset.X + (thumbLength * 0.5);
}
return arrangeSize;
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == OrientationProperty)
{
UpdatePseudoClasses(change.GetNewValue<Orientation>());
}
}
private static void CoerceLength(ref double componentLength, double trackLength)
{
if (componentLength < 0)
{
componentLength = 0.0;
}
else if (componentLength > trackLength || double.IsNaN(componentLength))
{
componentLength = trackLength;
}
}
private void ComputeSliderLengths(Size arrangeSize, bool isVertical, out double decreaseButtonLength, out double thumbLength, out double increaseButtonLength)
{
double min = Minimum;
double range = Math.Max(0.0, Maximum - min);
double offset = Math.Min(range, Value - min);
double trackLength;
// Compute thumb size
if (isVertical)
{
trackLength = arrangeSize.Height;
thumbLength = Thumb == null ? 0 : Thumb.DesiredSize.Height;
}
else
{
trackLength = arrangeSize.Width;
thumbLength = Thumb == null ? 0 : Thumb.DesiredSize.Width;
}
CoerceLength(ref thumbLength, trackLength);
double remainingTrackLength = trackLength - thumbLength;
decreaseButtonLength = remainingTrackLength * offset / range;
CoerceLength(ref decreaseButtonLength, remainingTrackLength);
increaseButtonLength = remainingTrackLength - decreaseButtonLength;
CoerceLength(ref increaseButtonLength, remainingTrackLength);
Density = range / remainingTrackLength;
}
private bool ComputeScrollBarLengths(Size arrangeSize, double viewportSize, bool isVertical, out double decreaseButtonLength, out double thumbLength, out double increaseButtonLength)
{
var min = Minimum;
var range = Math.Max(0.0, Maximum - min);
var offset = Math.Min(range, Value - min);
var extent = Math.Max(0.0, range) + viewportSize;
var trackLength = isVertical ? arrangeSize.Height : arrangeSize.Width;
double thumbMinLength = 10;
StyledProperty<double> minLengthProperty = isVertical ? MinHeightProperty : MinWidthProperty;
var thumb = Thumb;
if (thumb != null && thumb.IsSet(minLengthProperty))
{
thumbMinLength = thumb.GetValue(minLengthProperty);
}
thumbLength = trackLength * viewportSize / extent;
CoerceLength(ref thumbLength, trackLength);
thumbLength = Math.Max(thumbMinLength, thumbLength);
// If we don't have enough content to scroll, disable the track.
var notEnoughContentToScroll = MathUtilities.LessThanOrClose(range, 0.0);
var thumbLongerThanTrack = thumbLength > trackLength;
// if there's not enough content or the thumb is longer than the track,
// hide the track and don't arrange the pieces
if (notEnoughContentToScroll || thumbLongerThanTrack)
{
ShowChildren(false);
ThumbCenterOffset = Double.NaN;
Density = Double.NaN;
decreaseButtonLength = 0.0;
increaseButtonLength = 0.0;
return false; // don't arrange
}
else
{
ShowChildren(true);
}
// Compute lengths of increase and decrease button
double remainingTrackLength = trackLength - thumbLength;
decreaseButtonLength = remainingTrackLength * offset / range;
CoerceLength(ref decreaseButtonLength, remainingTrackLength);
increaseButtonLength = remainingTrackLength - decreaseButtonLength;
CoerceLength(ref increaseButtonLength, remainingTrackLength);
Density = range / remainingTrackLength;
return true;
}
private void ThumbChanged(AvaloniaPropertyChangedEventArgs e)
{
var oldThumb = (Thumb?)e.OldValue;
var newThumb = (Thumb?)e.NewValue;
if (oldThumb != null)
{
oldThumb.DragDelta -= ThumbDragged;
LogicalChildren.Remove(oldThumb);
VisualChildren.Remove(oldThumb);
}
if (newThumb != null)
{
newThumb.DragDelta += ThumbDragged;
LogicalChildren.Add(newThumb);
VisualChildren.Add(newThumb);
}
}
private void ButtonChanged(AvaloniaPropertyChangedEventArgs e)
{
var oldButton = (Button?)e.OldValue;
var newButton = (Button?)e.NewValue;
if (oldButton != null)
{
LogicalChildren.Remove(oldButton);
VisualChildren.Remove(oldButton);
}
if (newButton != null)
{
LogicalChildren.Add(newButton);
VisualChildren.Add(newButton);
}
}
private void ThumbDragged(object? sender, VectorEventArgs e)
{
if (IsThumbDragHandled)
return;
Value = MathUtilities.Clamp(
Value + ValueFromDistance(e.Vector.X, e.Vector.Y),
Minimum,
Maximum);
}
private void ShowChildren(bool visible)
{
// WPF sets Visible = Hidden here but we don't have that, and setting IsVisible = false
// will cause us to stop being laid out. Instead show/hide the child controls.
if (Thumb != null)
{
Thumb.IsVisible = visible;
}
if (IncreaseButton != null)
{
IncreaseButton.IsVisible = visible;
}
if (DecreaseButton != null)
{
DecreaseButton.IsVisible = visible;
}
}
private void UpdatePseudoClasses(Orientation o)
{
PseudoClasses.Set(":vertical", o == Orientation.Vertical);
PseudoClasses.Set(":horizontal", o == Orientation.Horizontal);
}
}
}
| 36.322245
| 190
| 0.574838
|
[
"MIT"
] |
ErrorCraft/Avalonia
|
src/Avalonia.Controls/Primitives/Track.cs
| 17,471
|
C#
|
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace NS.WebApp.MVC.Models
{
public class ResponseResultModel
{
[JsonPropertyName("title")]
public string Title { get; set; }
[JsonPropertyName("status")]
public int Status { get; set; }
[JsonPropertyName("errors")]
public ResponseErrorMessages Errors { get; set; }
}
public class ResponseErrorMessages
{
[JsonPropertyName("messages")]
public List<string> Messages { get; set; }
}
}
| 24.478261
| 57
| 0.623446
|
[
"Apache-2.0"
] |
asmutti/NerdStore
|
src/web/NS.WebApp.MVC/Models/ResponseResultModel.cs
| 565
|
C#
|
//===============================================================================
// Microsoft patterns & practices Enterprise Library
// Core
//===============================================================================
// Copyright © Microsoft Corporation. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
namespace Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel
{
/// <summary>
/// Implement this interface to create an object that can read a set
/// of <see cref="TypeRegistration"/> objects representing the current
/// Enterprise Library configuration and configure a dependency injection
/// container with that information.
///
/// </summary>
public interface IContainerConfigurator
{
/// <summary>
/// Consume the set of <see cref="TypeRegistration"/> objects and
/// configure the associated container.
/// </summary>
/// <param name="configurationSource">Configuration source to read registrations from.</param>
/// <param name="rootProvider"><see cref="ITypeRegistrationsProvider"/> that knows how to
/// read the <paramref name="configurationSource"/> and return all relevant type registrations.</param>
void RegisterAll(IConfigurationSource configurationSource, ITypeRegistrationsProvider rootProvider);
}
}
| 50.69697
| 112
| 0.598924
|
[
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] |
OS2CPRbroker/CPRbroker
|
PART/Source/Lib/EntLib50/Blocks/Common/Src/Configuration/ContainerModel/IContainerConfigurator.cs
| 1,676
|
C#
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ecr-public-2020-10-30.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.ECRPublic.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.ECRPublic.Model.Internal.MarshallTransformations
{
/// <summary>
/// DescribeRegistries Request Marshaller
/// </summary>
public class DescribeRegistriesRequestMarshaller : IMarshaller<IRequest, DescribeRegistriesRequest> , 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((DescribeRegistriesRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(DescribeRegistriesRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.ECRPublic");
string target = "SpencerFrontendService.DescribeRegistries";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2020-10-30";
request.HttpMethod = "POST";
request.ResourcePath = "/";
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetMaxResults())
{
context.Writer.WritePropertyName("maxResults");
context.Writer.Write(publicRequest.MaxResults);
}
if(publicRequest.IsSetNextToken())
{
context.Writer.WritePropertyName("nextToken");
context.Writer.Write(publicRequest.NextToken);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static DescribeRegistriesRequestMarshaller _instance = new DescribeRegistriesRequestMarshaller();
internal static DescribeRegistriesRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DescribeRegistriesRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
}
| 35.5
| 151
| 0.625608
|
[
"Apache-2.0"
] |
ChristopherButtars/aws-sdk-net
|
sdk/src/Services/ECRPublic/Generated/Model/Internal/MarshallTransformations/DescribeRegistriesRequestMarshaller.cs
| 3,905
|
C#
|
namespace Testing_4.Saga
{
using NServiceBus;
class MyOtherEvent :
IEvent
{
}
}
| 12.555556
| 26
| 0.539823
|
[
"Apache-2.0"
] |
A-Franklin/docs.particular.net
|
Snippets/Testing/Testing_4/Saga/MyOtherEvent.cs
| 107
|
C#
|
using BL.API.Services.Players.Queries;
using BL.API.Services.Stats.Model;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace BL.API.WebHost.Controllers
{
[ApiController]
[Route("api/{regionShortName}/[controller]")]
public class StatsController : ControllerBase
{
private readonly IMediator _mediator;
public StatsController(IMediator mediator)
{
_mediator = mediator;
}
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<AllStatsResponse>> GetAllStats(string regionShortName)
{
return Ok(await _mediator.Send(new GetAllStatsQuery.Query(regionShortName)));
}
}
}
| 28.466667
| 93
| 0.699063
|
[
"MIT"
] |
Silverful/BannerlordMM
|
BL.API/BL.API.WebHost/Controllers/StatsController.cs
| 856
|
C#
|
using Microsoft.Web.LibraryManager.Contracts;
namespace Microsoft.Web.LibraryManager.Vsix.Contracts
{
internal interface IDependenciesFactory
{
IDependencies FromConfigFile(string configFilePath);
}
}
| 22.3
| 60
| 0.7713
|
[
"Apache-2.0"
] |
RobJohnston/LibraryManager
|
src/LibraryManager.Vsix/Contracts/IDependenciesFactory.cs
| 225
|
C#
|
namespace Windows.UI.Xaml.Controls;
public class GridViewHeaderItem : ListViewBaseHeaderItem
{
}
| 16.333333
| 56
| 0.826531
|
[
"MIT"
] |
ljcollins25/Codeground
|
src/UnoApp/UnoDecompile/Uno.UI/Windows.UI.Xaml.Controls/GridViewHeaderItem.cs
| 98
|
C#
|
using System;
using System.Collections.Generic;
using System.Text;
using ArdalisRating.Factory;
namespace ArdalisRating
{
public class LandPolicyRater : Rater
{
public LandPolicyRater(RatingEngine ratingEng) : base(ratingEng)
{
}
public override void Rate(Policy policy)
{
Console.WriteLine("Rating LAND policy...");
Console.WriteLine("Validating policy.");
if (policy.BondAmount == 0 || policy.Valuation == 0)
{
Console.WriteLine("Land policy must specify Bond Amount and Valuation.");
return;
}
if (policy.BondAmount < 0.8m * policy.Valuation)
{
Console.WriteLine("Insufficient bond amount.");
return;
}
Rating = policy.BondAmount * 0.05m;
}
}
}
| 24.714286
| 89
| 0.568786
|
[
"MIT"
] |
ramji3ram/Pluralsighdemo
|
ArdalisRating/PolicyType/LandPolicyRater.cs
| 867
|
C#
|
using System;
using MoreLinq;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using BibliotecaViva.DTO;
using BibliotecaViva.DAO;
using BibliotecaViva.DTO.Dominio;
using BibliotecaViva.DAL.Interfaces;
namespace BibliotecaViva.DAL
{
public class SonarDAL : BaseDAL, ISonarDAL
{
private IPessoaDAL PessoaDAL { get; set; }
private IRegistroDAL RegistroDAL { get; set; }
public SonarDAL(bibliotecavivaContext dataContext) : base(dataContext)
{
}
public SonarRetorno Consultar(SonarConsulta sonar)
{
return new SonarRetorno()
{
Pessoas = PopularPessoas(BuscarPessoas(sonar)),
Registros = PopularRegistros(BuscarRegistros(sonar))
};
}
private List<PessoaDTO> PopularPessoas(List<PessoaDTO> pessoas)
{
var retorno = new List<PessoaDTO>();
foreach(var pessoa in pessoas)
retorno.AddRange(PessoaDAL.Consultar(pessoa));
return retorno.DistinctBy(pessoa => pessoa.Codigo).ToList();
}
private List<PessoaDTO> BuscarPessoas(SonarConsulta sonar)
{
return(from pessoaLocalizacao in DataContext.Pessoalocalizacaos
join
pessoa in DataContext.Pessoas
on pessoaLocalizacao.Pessoa equals pessoa.Codigo
join
localizacaoGeografica in DataContext.Localizacaogeograficas
on pessoaLocalizacao.Localizacaogeografica equals localizacaoGeografica.Codigo
where localizacaoGeografica.Latitude >= sonar.CoordenadaInicio[0] &&
localizacaoGeografica.Latitude <= sonar.CoordenadaFim[0] &&
localizacaoGeografica.Longitude >= sonar.CoordenadaInicio[1] &&
localizacaoGeografica.Longitude <= sonar.CoordenadaFim[1]
select new PessoaDTO()
{
Codigo = pessoa.Codigo,
Nome = pessoa.Nome,
Sobrenome = pessoa.Sobrenome
}).AsNoTracking().ToList();
}
private List<RegistroDTO> PopularRegistros(List<RegistroDTO> registros)
{
var retorno = new List<RegistroDTO>();
foreach(var registro in registros)
retorno.AddRange(RegistroDAL.Consultar(registro));
return retorno.DistinctBy(registro => registro.Codigo).ToList();
}
private List<RegistroDTO> BuscarRegistros(SonarConsulta sonar)
{
return(from registroLocalizacao in DataContext.Registrolocalizacaos
join
registro in DataContext.Registros
on registroLocalizacao.Registro equals registro.Codigo
join
localizacaoGeografica in DataContext.Localizacaogeograficas
on registroLocalizacao.Localizacaogeografica equals localizacaoGeografica.Codigo
join
idioma in DataContext.Idiomas
on registro.Idioma equals idioma.Codigo
where localizacaoGeografica.Latitude >= sonar.CoordenadaInicio[0] &&
localizacaoGeografica.Latitude <= sonar.CoordenadaFim[0] &&
localizacaoGeografica.Longitude >= sonar.CoordenadaInicio[1] &&
localizacaoGeografica.Longitude <= sonar.CoordenadaFim[1]
select new RegistroDTO()
{
Codigo = registro.Codigo,
Nome = registro.Nome,
Idioma = idioma.Nome
}).AsNoTracking().ToList();
}
}
}
| 39.443299
| 100
| 0.596184
|
[
"MIT"
] |
RodrigoMedeirosRS/Biblioteca_Viva
|
DAL/SonarDAL.cs
| 3,826
|
C#
|
namespace BDInSelfLove.Services.Data.Courses
{
using System.Linq;
using System.Threading.Tasks;
using BDInSelfLove.Data.Common.Repositories;
using BDInSelfLove.Data.Models;
using Microsoft.EntityFrameworkCore;
public class CourseService : ICourseService
{
private readonly IDeletableEntityRepository<Course> courseRepository;
private readonly IDeletableEntityRepository<CourseVideo> courseVideoRepository;
private readonly IDeletableEntityRepository<ApplicationUser> userRepository;
public CourseService(
IDeletableEntityRepository<Course> courseRepository,
IDeletableEntityRepository<CourseVideo> courseVideoRepository,
IDeletableEntityRepository<ApplicationUser> userRepository)
{
this.courseRepository = courseRepository;
this.courseVideoRepository = courseVideoRepository;
this.userRepository = userRepository;
}
public async Task<string> CreateCourse(string title, string thumbnailLink, string priceId, long price)
{
var course = new Course
{
Title = title,
ThumbnailLink = thumbnailLink,
PriceId = priceId,
Price = price,
};
await this.courseRepository.AddAsync(course);
await this.courseRepository.SaveChangesAsync();
return course.Id;
}
public async Task<int> CreateCourseVideo(string guid, string title, string courseId)
{
var courseVideo = new CourseVideo
{
Id = guid,
Title = title,
CourseId = courseId,
};
var course = await this.courseRepository.All().FirstOrDefaultAsync(x => x.Id.Equals(courseId));
if (course.CourseVideos.Count() == 0)
{
courseVideo.IsPreview = true;
}
course.CourseVideos.Add(courseVideo);
return await this.courseRepository.SaveChangesAsync();
}
public IQueryable<Course> GetAll()
{
return this.courseRepository.All();
}
public IQueryable<Course> GetById(string id)
{
return this.courseRepository.All().Where(c => c.Id.Equals(id)).Include(c => c.CourseVideos);
}
public IQueryable<CourseVideo> GetCoursePreviewVideo(string courseVideoId)
{
return this.courseRepository.All()
.Include(c => c.CourseVideos)
.Where(c => c.CourseVideos.Any(cv => cv.Id.Equals(courseVideoId)))
.Select(c => c.CourseVideos.First(cv => cv.IsPreview));
}
public IQueryable<CourseVideo> GetCourseVideo(string courseVideoId)
{
return this.courseVideoRepository.All()
.Where(x => x.Id.Equals(courseVideoId));
}
}
}
| 33.942529
| 110
| 0.606841
|
[
"MIT"
] |
ivanBalev/ASP.NET-Core
|
Services/BDInSelfLove.Services.Data/Courses/CourseService.cs
| 2,955
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Cats.Areas.EarlyWarning.Models;
using Cats.Helpers;
using Cats.Models;
using Cats.Services.EarlyWarning;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Cats.ViewModelBinder;
using Cats.Services.Security;
using log4net;
using Cats.Infrastructure;
namespace Cats.Areas.EarlyWarning.Controllers
{
public class RationController : Controller
{
private readonly IRationService _rationService;
private readonly IRationDetailService _rationDetailService;
private readonly ICommodityService _commodityService;
private readonly IUserAccountService _userAccountService;
private readonly ILog _log;
public RationController(IRationService rationService, ICommodityService commodityService,
IRationDetailService rationDetailService, IUserAccountService userAccountService,ILog log)
{
this._rationService = rationService;
this._rationDetailService = rationDetailService;
this._commodityService = commodityService;
_userAccountService = userAccountService;
_log = log;
}
//
// GET: /EarlyWarning/Ration/
public ActionResult Index()
{
var rations = _rationService.GetAllRation();
var rationViewModels = (from item in rations select BindRationViewModel(item)).OrderBy(o=>o.ReferenceNumber);
return View(rationViewModels);
}
public JsonResult Rations()
{
return Json(_rationService.GetAllRation(), JsonRequestBehavior.AllowGet);
}
public ActionResult Print(int id = 0)
{
if (id == 0)
{
RedirectToAction("Index");
}
var reportPath = Server.MapPath("~/Report/EarlyWarning/Ration.rdlc");
var rd = _rationService.FindById(id);
var reportData = (from rationdetail in rd.RationDetails
select new RationDetailViewModel
{
Amount = rationdetail.Amount,
RationName = rd.RefrenceNumber,
Commodity = rationdetail.Commodity.Name,
RationID = rationdetail.RationID
});
var dataSourceName = "RationDetailView";
var result = ReportHelper.PrintReport(reportPath, reportData, dataSourceName);
return File(result.RenderBytes, result.MimeType);
}
public ActionResult Details(int id)
{
ViewBag.RationID = id;
var ration = _rationService.FindById(id);
var rationViewModel = BindRationViewModel(ration);
var commdities = (from item in _commodityService.GetAllCommodity()
select new
{
item.CommodityID,
item.Name
});
ViewData["commodities"] = commdities;
ViewData["UnitMeasures"] = _commodityService.GetAllUnit();
return View(rationViewModel);
}
private RationDetailViewModel BindRationDetailViewModel(RationDetail rationDetail)
{
RationDetailViewModel rationViewModel = null;
if (rationDetail != null)
{
rationViewModel = new RationDetailViewModel();
rationViewModel.Amount = rationDetail.Amount;
rationViewModel.Commodity = _commodityService.FindById(rationDetail.CommodityID).Name;
rationViewModel.CommodityID = rationDetail.CommodityID;
rationViewModel.RationID = rationDetail.RationID;
rationViewModel.RationDetailID = rationDetail.RationDetailID;
rationViewModel.UnitID = rationDetail.UnitID.HasValue?rationDetail.UnitID.Value:-1;
// rationViewModel.UnitID = rationDetail.UnitID;
rationViewModel.RationName = _rationService.FindById(rationDetail.RationID).RefrenceNumber;
}
return rationViewModel;
}
public ActionResult Edit(int id)
{
var obj = _rationService.FindById(id);
var rationViewModel = BindRationViewModel(obj);
return PartialView("_Edit", rationViewModel);
}
private RationViewModel BindRationViewModel(Ration ration)
{
var userPref = _userAccountService.GetUserInfo(HttpContext.User.Identity.Name).DatePreference;
if (ration == null) return null;
var rationViewModel = new RationViewModel();
rationViewModel.RationID = ration.RationID;
rationViewModel.IsDefaultRation = ration.IsDefaultRation;
rationViewModel.CreatedBy = ration.CreatedBy;
rationViewModel.CreatedDate = ration.CreatedDate;
rationViewModel.UpdatedBy = ration.UpdatedBy;
rationViewModel.UpdatedDate = ration.UpdatedDate;
rationViewModel.ReferenceNumber = ration.RefrenceNumber;
//rationViewModel.CreatedDateEC = ration.CreatedDate.HasValue
// ? EthiopianDate.GregorianToEthiopian(ration.CreatedDate.Value)
// : "";
rationViewModel.UpdatedDateEC = ration.UpdatedDate.HasValue
? EthiopianDate.GregorianToEthiopian(ration.UpdatedDate.Value)
: "";
rationViewModel.DateCreated = ration.CreatedDate.ToCTSPreferedDateFormat(userPref);// RequistionDate.ToCTSPreferedDateFormat(UserAccountHelper.UserCalendarPreference());
return rationViewModel;
}
[HttpPost]
public ActionResult Edit(RationViewModel rationViewModel)
{
if (rationViewModel != null && ModelState.IsValid)
{
try
{
var orign = _rationService.FindById(rationViewModel.RationID);
orign.IsDefaultRation = rationViewModel.IsDefaultRation;
orign.UpdatedBy = UserAccountHelper.GetUser(HttpContext.User.Identity.Name).UserProfileID;
orign.UpdatedDate = DateTime.Today;
_rationService.EditRation(orign);
return Json(new { success = true });
}
catch (Exception ex)
{
var log = new Logger();
log.LogAllErrorsMesseges(ex,_log);
ModelState.AddModelError("Errors", ex.Message);
}
}
return PartialView("_Edit", rationViewModel);
}
[HttpGet]
public ActionResult Create()
{
return PartialView("_Create");
}
[HttpPost]
public ActionResult Create(Ration ration)
{
if (ration != null && ModelState.IsValid)
{
try
{
ration.CreatedBy = UserAccountHelper.GetUser(HttpContext.User.Identity.Name).UserProfileID;
ration.CreatedDate = DateTime.Today;
_rationService.AddRation(ration);
return RedirectToAction("Index");
}
catch (Exception ex)
{
var log = new Logger();
log.LogAllErrorsMesseges(ex,_log);
ModelState.AddModelError("Errors", ex.Message);
}
}
return PartialView("_Create", ration);
}
public ActionResult Ration_Read([DataSourceRequest] DataSourceRequest request)
{
var rations = _rationService.GetAllRation();
var rationViewModels = (from item in rations select BindRationViewModel(item)).OrderBy(o=>o.ReferenceNumber);
return Json(rationViewModels.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
public ActionResult RationDetail_Read([DataSourceRequest] DataSourceRequest request, int id)
{
var rationDetails = _rationDetailService.Get(t => t.RationID == id);
var rationViewModels = (from item in rationDetails select BindRationDetailViewModel(item));
return Json(rationViewModels.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
public JsonResult RationDetail(int id)
{
var rationDetails = _rationDetailService.Get(t => t.RationID == id);
var ration = (from item in rationDetails select new {item.Commodity.Name, item.Amount});
return Json(ration, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult RationDetail_Create([DataSourceRequest] DataSourceRequest request, RationDetailViewModel rationDetailViewModel,int id)
{
if (rationDetailViewModel != null && ModelState.IsValid)
{
rationDetailViewModel.RationID = id;
var rationCommodity =_rationDetailService.FindBy(
m => m.RationID == id && m.CommodityID == rationDetailViewModel.CommodityID).
FirstOrDefault();
if (rationCommodity==null)
{
_rationDetailService.AddRationDetail(BindRationDetail(rationDetailViewModel));
}
}
return Json(new[] { rationDetailViewModel }.ToDataSourceResult(request, ModelState));
}
private RationDetail BindRationDetail(RationDetailViewModel rationDetailViewModel)
{
if (rationDetailViewModel == null) return null;
var ration = new RationDetail()
{
RationDetailID = rationDetailViewModel.RationDetailID,
RationID = rationDetailViewModel.RationID,
CommodityID = rationDetailViewModel.CommodityID,
Amount = rationDetailViewModel.Amount,
UnitID=rationDetailViewModel.UnitID
};
return ration;
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult RationDetail_Update([DataSourceRequest] DataSourceRequest request, RationDetailViewModel rationDetailViewModel)
{
if (rationDetailViewModel != null && ModelState.IsValid)
{
var origin = _rationDetailService.FindById(rationDetailViewModel.RationDetailID);
origin.Amount = rationDetailViewModel.Amount;
_rationDetailService.EditRationDetail(origin);
}
return Json(new[] { rationDetailViewModel }.ToDataSourceResult(request, ModelState));
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult RationDetail_Destroy([DataSourceRequest] DataSourceRequest request, RationDetailViewModel rationDetailViewModel)
{
if (rationDetailViewModel != null && ModelState.IsValid)
{
_rationDetailService.DeleteById(rationDetailViewModel.RationDetailID);
}
return Json(ModelState.ToDataSourceResult());
}
private bool _disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this._disposed)
{
if (disposing)
{
_commodityService.Dispose();
_rationService.Dispose();
}
}
this._disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public ActionResult SetDefault(int id)
{
_rationService.SetDefault(id);
return RedirectToAction("Index");
}
}
}
| 42.244898
| 181
| 0.576248
|
[
"Apache-2.0"
] |
IYoni/cats
|
Web/App_Start/Areas/EarlyWarning/Controllers/RationController.cs
| 12,422
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace emmily.Common
{
public class CustomDateProvider : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
return null;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (!(arg is DateTime)) throw new NotSupportedException();
var dt = (DateTime)arg;
string suffix;
if (new[] { 11, 12, 13 }.Contains(dt.Day))
{
suffix = "th";
}
else if (dt.Day % 10 == 1)
{
suffix = "st";
}
else if (dt.Day % 10 == 2)
{
suffix = "nd";
}
else if (dt.Day % 10 == 3)
{
suffix = "rd";
}
else
{
suffix = "th";
}
return string.Format("{0:dddd, MMM} {1}{2}", arg, dt.Day, suffix);
}
}
}
| 24.442308
| 88
| 0.438238
|
[
"MIT"
] |
nmetulev/emmily
|
emmily/Common/CustomDateProvider.cs
| 1,273
|
C#
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.ApplicationAutoScaling")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Application Auto Scaling. Application Auto Scaling is a general purpose Auto Scaling service for supported elastic AWS resources. With Application Auto Scaling, you can automatically scale your AWS resources, with an experience similar to that of Amazon EC2 Auto Scaling.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[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)]
// 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("3.3")]
[assembly: AssemblyFileVersion("3.7.0.17")]
| 50.84375
| 351
| 0.760295
|
[
"Apache-2.0"
] |
KenHundley/aws-sdk-net
|
sdk/code-analysis/ServiceAnalysis/ApplicationAutoScaling/Properties/AssemblyInfo.cs
| 1,627
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Uno.Extensions;
using Uno.Logging;
using Windows.UI;
namespace Windows.UI.Xaml.Media.Animation
{
/// <summary>
/// Value animator. Base on the Android ValueAnimator, this object is similar semantically.
///
/// Used ONLY with DoubleAnimation, it will animate a float value on the animation loop
/// See https://web.archive.org/web/20160303015227/https://www.bigspaceship.com/ios-animation-intervals/
///
/// </summary>
internal static partial class AnimatorFactory
{
/// <summary>
/// Creates the actual animator instance
/// </summary>
private static IValueAnimator CreateDouble(Timeline timeline, double startingValue, double targetValue)
{
if (!timeline.GetIsHardwareAnimated())
{
return new FloatValueAnimator((float)startingValue, (float)targetValue);
}
// If we are animating a GPU-bound animation, create a GPU specific value animator
else
{
return new GPUFloatValueAnimator((float)startingValue, (float)targetValue, timeline.PropertyInfo.GetPathItems());
}
}
private static IValueAnimator CreateColor(Timeline timeline, ColorOffset startingValue, ColorOffset targetValue)
{
// TODO: GPU-bound color animations - https://github.com/unoplatform/uno/issues/2947
return new ColorValueAnimator(startingValue, targetValue);
}
}
}
| 31.681818
| 117
| 0.747489
|
[
"Apache-2.0"
] |
Abhishek-Sharma-Msft/uno
|
src/Uno.UI/UI/Xaml/Media/Animation/Animators/AnimatorFactory.iOSmacOS.cs
| 1,396
|
C#
|
using System.Web;
using System.Web.Mvc;
namespace Abp.App.TestMvc
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
| 19.142857
| 80
| 0.652985
|
[
"MIT"
] |
zhouyongtao/App.WebAPI
|
Abp.App.TestMvc/App_Start/FilterConfig.cs
| 270
|
C#
|
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Input;
using NetMQ;
using NetMQ.Sockets;
#endregion
namespace wssmono
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Map map = null;
Texture2D mapAtlas = null;
Vector2 cameraWorld = new Vector2 (50 * 18 + 12, 50 * 18 + 12);
List<Vector2> entPositions = null;
NetClient client = null;
SpriteFont font;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
graphics.IsFullScreen = true;
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
System.Console.WriteLine ("Loading map from json file");
TiledMap tiledMap = Map.LoadTiledMap (Content, out mapAtlas, "Content/data/test.json");
map = new Map ();
map.Initialize (tiledMap, mapAtlas);
entPositions = new List<Vector2> ();
//Create a bunch of test entities. For now we just make sure we create at least as many entities as the amount of updates we get from server.
for (int i = 0; i < 1000; ++i) {
entPositions.Add (new Vector2 (0, 0));
}
client = new NetClient ();
client.connectToServer ();
//font = Content.load<SpriteFont> ("Content/graphics/Times New Roman Bold 21");
//font = Content.Load<SpriteFont> ("Content/graphics/defaultFont");
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// For Mobile devices, this logic will close the Game when the Back button is pressed
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
{
Exit();
}
KeyboardState ks = Keyboard.GetState ();
if (ks.IsKeyDown (Keys.Escape)) {
Exit();
}
if (ks.IsKeyDown (Keys.Left) || ks.IsKeyDown(Keys.A)) {
cameraWorld.X -= (float)(100.0d * gameTime.ElapsedGameTime.TotalSeconds);
}
if (ks.IsKeyDown (Keys.Right) || ks.IsKeyDown(Keys.D)) {
cameraWorld.X += (float)(100.0 * (float)gameTime.ElapsedGameTime.TotalSeconds);
}
if (ks.IsKeyDown (Keys.Up) || ks.IsKeyDown(Keys.W)) {
cameraWorld.Y -= (float)(100.0 * (float)gameTime.ElapsedGameTime.TotalSeconds);
}
if (ks.IsKeyDown (Keys.Down) || ks.IsKeyDown(Keys.S)) {
cameraWorld.Y += (float)(100.0 * (float)gameTime.ElapsedGameTime.TotalSeconds);
}
map.Update (gameTime);
//update entity positions
client.getEntityPositions (ref entPositions);
//cameraWorld.X = entPositions [0].X;
//cameraWorld.Y = entPositions [1].Y;
cameraWorld = entPositions [1] * 18.0f;
// TODO: Add your update logic here
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.DeepPink);
//TODO: Add your drawing code here
//cameraWorld.X += 0.01f;
//Console.WriteLine (cameraWorld);
Vector2 viewCenter = new Vector2 (GraphicsDevice.Viewport.Width / 2.0f, GraphicsDevice.Viewport.Height / 2.0f);
Vector2 worldViewTransform = cameraWorld * -1.0f + viewCenter;
Rectangle spriteSource = new Rectangle ();
Int32 tileId = 1;
Vector2 texturePosition = new Vector2 (0, 0);
spriteBatch.Begin (SpriteSortMode.Immediate, BlendState.Opaque, SamplerState.PointWrap, DepthStencilState.None, RasterizerState.CullCounterClockwise); // We now have page region of tiles in world space we can render them in camera space.
map.Draw (spriteBatch, GraphicsDevice.Viewport, ref cameraWorld, ref viewCenter, ref worldViewTransform);
// Draw entitity sprites.
foreach (Vector2 position in entPositions) {
Vector2 vec = position*18;
map.getSprite (tileId, ref texturePosition, ref spriteSource);
vec += worldViewTransform;
spriteBatch.Draw (mapAtlas, vec, spriteSource, Color.White);
}
spriteBatch.End ();
//map.Draw (spriteBatch, Viewport);
base.Draw(gameTime);
}
}
}
| 32.461538
| 241
| 0.649471
|
[
"MIT"
] |
beyzend/wss
|
wss/clients/monogame/wssmono/wssmono/Game1.cs
| 5,486
|
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.
//
// Description:
// Maps namespaceURI and LocalName to appropriate element, properties, and events.
//
using System;
using System.Xml;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Reflection;
using MS.Utility;
#if !PBTCOMPILER
using System.Windows;
using System.Windows.Markup;
using System.Windows.Resources;
using System.Windows.Threading;
using SecurityHelper=MS.Internal.PresentationFramework.SecurityHelper;
using MS.Internal; // CriticalExceptions
#else
using System.Runtime.CompilerServices;
#endif
// Disabling 1634 and 1691:
// In order to avoid generating warnings about unknown message numbers and
// unknown pragmas when compiling C# source code with the C# compiler,
// you need to disable warnings 1634 and 1691. (Presharp Documentation)
#pragma warning disable 1634, 1691
#if PBTCOMPILER
namespace MS.Internal.Markup
#else
namespace System.Windows.Markup
#endif
{
///<summary>
/// Handles mapping between XML NamepaceURI and .NET namespace types
///</summary>
#if PBTCOMPILER
internal class XamlTypeMapper
#else
public partial class XamlTypeMapper
#endif
{
#region Public
#region Methods
#if !PBTCOMPILER
/// <summary>
/// Constructor
/// </summary>
/// <param name="assemblyNames">Assemblies XamlTypeMapper should use when resolving XAML</param>
public XamlTypeMapper(string[] assemblyNames)
{
if(null == assemblyNames)
{
throw new ArgumentNullException( "assemblyNames" );
}
_assemblyNames = assemblyNames;
_namespaceMaps = null;
}
#endif
/// <summary>
/// Constructor
/// </summary>
/// <param name="assemblyNames">Assemblies XamlTypeMapper should use when resolving XAML</param>
/// <param name="namespaceMaps">NamespaceMap the XamlTypeMapper should use when resolving XAML</param>
public XamlTypeMapper(
string[] assemblyNames,
NamespaceMapEntry[] namespaceMaps)
{
if(null == assemblyNames)
{
throw new ArgumentNullException( "assemblyNames" );
}
_assemblyNames = assemblyNames;
_namespaceMaps = namespaceMaps;
#if PBTCOMPILER
_hasInternals = false;
_hasLocalReference = false;
#endif
}
/// <summary>
/// Helper to map an Xaml tag to a DotNet Type
/// </summary>
/// <remarks>
/// Example:<para/>
/// If the xml contained the tags <base:Button xmlns:base="AvalonBase"/>
/// you would call XamlTypeMapper.GetType("AvalonBase","Button");
/// <para/>
/// Note the XmlNamespace "AvalonBase" is the actual namespace value, not
/// the base: prefix.
/// </remarks>
/// <param name="xmlNamespace">NamespaceURI of tag</param>
/// <param name="localName">localName of the Tag</param>
/// <returns>Type for the object. If no type was found NULL is returned</returns>
public Type GetType(
string xmlNamespace,
string localName)
{
if(null == xmlNamespace)
{
throw new ArgumentNullException( "xmlNamespace" );
}
if(null == localName)
{
throw new ArgumentNullException( "localName" );
}
TypeAndSerializer typeAndSerializer =
GetTypeOnly(xmlNamespace,localName);
return typeAndSerializer != null ? typeAndSerializer.ObjectType : null;
}
#if !PBTCOMPILER
/// <summary>
/// Programmatic counterpart to the <?Mapping ... ?> XAML PI. For example, <para/>
/// <?Mapping XmlNamespace="swc" ClrNamespace="System.Windows.ComponentModel" Assembly="PresentationFramework" ?>
/// </summary>
/// <param name="xmlNamespace">
/// The "swc" argument in the mapping PI example.
/// </param>
/// <param name="clrNamespace">
/// The "System.Windows.ComponentModel" argument in the mapping PI example.
/// </param>
/// <param name="assemblyName">
/// The "PresentationFramework" argument in the mapping PI example.
/// </param>
public void AddMappingProcessingInstruction(
string xmlNamespace,
string clrNamespace,
string assemblyName )
{
if( null == xmlNamespace )
{
throw new ArgumentNullException("xmlNamespace");
}
if( null == clrNamespace )
{
throw new ArgumentNullException("clrNamespace");
}
if( null == assemblyName )
{
throw new ArgumentNullException("assemblyName");
}
// Parameter validation : Check for String.Empty as well?
// Add mapping to the table keyed by xmlNamespace
ClrNamespaceAssemblyPair pair = new ClrNamespaceAssemblyPair(clrNamespace, assemblyName);
PITable[xmlNamespace] = pair;
// Add mapping to the table keyed by assembly and clrnamespace
string upperAssemblyName = assemblyName.ToUpper(
TypeConverterHelper.InvariantEnglishUS);
String fullName = clrNamespace + "#" + upperAssemblyName;
_piReverseTable[fullName] = xmlNamespace;
// Add mapping to the SchemaContext
if (_schemaContext != null)
{
_schemaContext.SetMappingProcessingInstruction(xmlNamespace, pair);
}
}
#endif
/// <summary>
/// This allows specifying a path to use when loading the named assembly.
/// </summary>
/// <param name="assemblyName">
/// The short name of the assembly, with no extension or path specified
/// </param>
/// <param name="assemblyPath">
/// The file path of the assembly
/// </param>
public void SetAssemblyPath(
string assemblyName,
string assemblyPath)
{
if( null == assemblyName )
{
throw new ArgumentNullException("assemblyName");
}
if( null == assemblyPath )
{
throw new ArgumentNullException("assemblyPath");
}
if (assemblyPath == string.Empty)
{
_lineNumber = 0; // Public API, so we don't know the line number.
ThrowException(SRID.ParserBadAssemblyPath);
}
if (assemblyName == string.Empty)
{
_lineNumber = 0; // Public API, so we don't know the line number.
ThrowException(SRID.ParserBadAssemblyName);
}
string asmName = assemblyName.ToUpper(CultureInfo.InvariantCulture);
lock (_assemblyPathTable)
{
_assemblyPathTable[asmName] = assemblyPath;
}
PreLoadDefaultAssemblies(asmName, assemblyPath);
#if !PBTCOMPILER
// Allow people to reset the path of previously loaded assemblies
// so they can be loaded again. The is the Dev build/load/build/load
// Designer scenario. (Don't mess with GACed assemblies)
Assembly assem = ReflectionHelper.GetAlreadyLoadedAssembly(asmName);
if (assem != null
#if NETFX
&& !assem.GlobalAssemblyCache
#endif
)
{
ReflectionHelper.ResetCacheForAssembly(asmName);
// No way to reset SchemaContext at assembly granularity, so just reset the whole context
if (_schemaContext != null)
{
_schemaContext = null;
}
}
#endif
}
#endregion Methods
#region Properties
/// <summary>
/// Instance of XamlTypeMapper to use if none is specified in a
/// ParserContext. XamlTypeMapper returned is the internal default.
/// </summary>
public static XamlTypeMapper DefaultMapper
{
get
{
return XmlParserDefaults.DefaultMapper;
}
}
#endregion Properties
#endregion Public
#region Internal
#region Initialization
#if !PBTCOMPILER
///<summary>
/// Initialize the XamlTypeMapper so that it is ready for a parse operation.
///</summary>
internal void Initialize()
{
_typeLookupFromXmlHashtable.Clear();
_namespaceMapHashList.Clear();
_piTable.Clear();
_piReverseTable.Clear();
lock (_assemblyPathTable)
{
_assemblyPathTable.Clear();
}
_referenceAssembliesLoaded = false;
}
#endif
// Return a new XamlTypeMapper that has the same instance variables as this instance,
// will all complex properties deep copied.
#if !PBTCOMPILER
internal XamlTypeMapper Clone()
{
XamlTypeMapper newMapper = new XamlTypeMapper(_assemblyNames.Clone() as string[]);
newMapper._mapTable = _mapTable;
newMapper._referenceAssembliesLoaded = _referenceAssembliesLoaded;
newMapper._lineNumber = _lineNumber;
newMapper._linePosition = _linePosition;
newMapper._namespaceMaps = _namespaceMaps.Clone() as NamespaceMapEntry[];
newMapper._typeLookupFromXmlHashtable = _typeLookupFromXmlHashtable.Clone() as Hashtable;
newMapper._namespaceMapHashList = _namespaceMapHashList.Clone() as Hashtable;
newMapper._typeInformationCache = CloneHybridDictionary(_typeInformationCache);
newMapper._piTable = CloneHybridDictionary(_piTable);
newMapper._piReverseTable = CloneStringDictionary(_piReverseTable);
newMapper._assemblyPathTable = CloneHybridDictionary(_assemblyPathTable);
return newMapper;
}
#endif
#if !PBTCOMPILER
private HybridDictionary CloneHybridDictionary(HybridDictionary dict)
{
HybridDictionary newDict = new HybridDictionary(dict.Count);
foreach ( DictionaryEntry de in dict )
{
newDict.Add(de.Key, de.Value);
}
return newDict;
}
#endif
#if !PBTCOMPILER
private Dictionary<string, string> CloneStringDictionary(Dictionary<string, string> dict)
{
Dictionary<string, string> newDict = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> kvp in dict)
{
newDict.Add(kvp.Key, kvp.Value);
}
return newDict;
}
#endif
#endregion Initialization
#region Assemblies
///<summary>
/// Returns the assembly path for the passed assembly. If none, return null.
///</summary>
internal string AssemblyPathFor(string assemblyName)
{
string path = null;
if (assemblyName != null)
{
// This method is used by SchemaContext, which needs to be thread-safe, so lock around it
lock (_assemblyPathTable)
{
path = _assemblyPathTable[assemblyName.ToUpper(
CultureInfo.InvariantCulture)] as string;
}
}
#if PBTCOMPILER
if (path == null)
{
// If the assembly name contains full assembly name, we should use the short
// assembly name to search the assembly path cache table.
int indexComma = assemblyName.IndexOf(",", StringComparison.Ordinal);
if (indexComma > 0)
{
string assemblyShortName = assemblyName.Substring(0, indexComma).ToUpper(CultureInfo.InvariantCulture);
path = _assemblyPathTable[assemblyShortName] as String;
}
}
#endif
return path;
}
/// <summary>
/// Load assemblies that are in the referenced assembly list passed to the XamlTypeMapper
/// by the compiler. Don't load known assemblies that should already be present,
/// since the references may not be the correct versions.
/// </summary>
private bool LoadReferenceAssemblies()
{
if (!_referenceAssembliesLoaded)
{
_referenceAssembliesLoaded = true;
foreach (DictionaryEntry entry in _assemblyPathTable)
{
ReflectionHelper.LoadAssembly(entry.Key as String, entry.Value as String);
}
return true;
}
else
{
// Already loaded, so they don't need to be loaded again
return false;
}
}
#endregion Assemblies
#region AssemblyLoading
private void PreLoadDefaultAssemblies(string asmName, string asmPath)
{
if (AssemblyWB == null && string.Compare(asmName, _assemblyNames[0], StringComparison.OrdinalIgnoreCase) == 0)
{
AssemblyWB = ReflectionHelper.LoadAssembly(asmName, asmPath);
}
else if (AssemblyPC == null && string.Compare(asmName, _assemblyNames[1], StringComparison.OrdinalIgnoreCase) == 0)
{
AssemblyPC = ReflectionHelper.LoadAssembly(asmName, asmPath);
}
else if (AssemblyPF == null && string.Compare(asmName, _assemblyNames[2], StringComparison.OrdinalIgnoreCase) == 0)
{
AssemblyPF = ReflectionHelper.LoadAssembly(asmName, asmPath);
}
else if (string.Compare(asmName, "SYSTEM.XML", StringComparison.OrdinalIgnoreCase) == 0)
{
// make sure System.Xml is at least loaded as ReflectionOnly
ReflectionHelper.LoadAssembly(asmName, asmPath);
}
else if (string.Compare(asmName, "SYSTEM", StringComparison.OrdinalIgnoreCase) == 0)
{
// make sure System is at least loaded as ReflectionOnly
ReflectionHelper.LoadAssembly(asmName, asmPath);
}
}
#endregion AssemblyLoading
#region Events
#if !PBTCOMPILER
/// <summary>
/// Helper to map an Attribute to a RoutedEvent
/// </summary>
/// <remarks>
/// Example: <para/>
/// If the xaml contained the tag <base:Button base:Click="MyClick" xmlns:base="BaseXmlNs"/>
/// you would call <para/>
///
/// Type owner = XamlTypeMapper.GetType("BaseXmlNs","Button"); <para/>
/// RoutedEvent = XamlTypeMapper.GetRoutedEvent(owner,"MyClick","BaseXmlNs");
/// </remarks>
/// <param name="owner">Type of the owner</param>
/// <param name="xmlNamespace">Xml NamespaceURI of the attribute</param>
/// <param name="localName">Local name of the attribute</param>
/// <returns>The RoutedEvent ID or null if no match was found</returns>
/// <ExternalAPI/>
internal RoutedEvent GetRoutedEvent(
Type owner,
string xmlNamespace,
string localName)
{
Type baseType = null;
string dynamicObjectName = null;
if(null == localName)
{
throw new ArgumentNullException( "localName" );
}
if(null == xmlNamespace)
{
throw new ArgumentNullException( "xmlNamespace" );
}
if (owner != null && !ReflectionHelper.IsPublicType(owner))
{
_lineNumber = 0; // Public API, so we don't know the line number.
ThrowException(SRID.ParserOwnerEventMustBePublic, owner.FullName );
}
RoutedEvent Event = GetDependencyObject(true,owner,xmlNamespace,
localName,ref baseType,ref dynamicObjectName)
as RoutedEvent;
return Event;
}
#endif
#endregion Events
#region Properties
#if !PBTCOMPILER
///<summary>
/// Converts the string representation of an Attribute Value to an appropriate
/// Type for the Property. This handles use of type converters and the special
/// *prefix:Type.Field syntax for enums, static properties and fields.
/// </summary>
///<param name="targetObject">Target object that the property needs to be set on</param>
///<param name="propType">Type of the property</param>
///<param name="propName">Name of the property. This is used only for
/// error reporting and some pre-validation</param>
///<param name="dpOrPiOrFi">DependencyProperty or PropertyInfo or FieldInfo. This is used
/// for evaluating the TypeConverter to be used for conversion</param>
///<param name="typeContext">Context for the type converter</param>
///<param name="parserContext">Context for enum, field and property resolution</param>
///<param name="value">string value of the property the Attribute</param>
///<param name="converterTypeId">typeId of converter to use for paring the attribute value</param>
///<returns>
/// An Object for the attribute value is returned.
/// Null is returned if no TypeConverter for the Property type.
///</returns>
internal Object ParseProperty(
object targetObject,
Type propType,
string propName,
object dpOrPiOrFi,
ITypeDescriptorContext typeContext,
ParserContext parserContext,
string value,
short converterTypeId)
{
_lineNumber = parserContext != null ? parserContext.LineNumber : 0;
_linePosition = parserContext != null ? parserContext.LinePosition : 0;
// If value is to be converted to a string, just return the string itself instead of
// going needlessly through the TC. But check that the target prop Type can accept strings.
if (converterTypeId < 0 && ((short)-converterTypeId == (short)KnownElements.StringConverter))
{
if (propType == typeof(object) || propType == typeof(string))
{
return value;
}
else
{
string message = SR.Get(SRID.ParserCannotConvertPropertyValueString, value, propName, propType.FullName);
XamlParseException.ThrowException(parserContext, _lineNumber, _linePosition, message, null);
}
}
Object obj = null; // Object to return
TypeConverter typeConvert;
if (converterTypeId != 0)
{
typeConvert = parserContext.MapTable.GetConverterFromId(converterTypeId, propType, parserContext);
}
else
{
// NOTE: This may still be a known converter. This is typically the case when adding
// a text Record. This should also be potentially optimized by resolving & writing out the
// TC at compile time.
// Reflect for per property type converter or type converter based on the property's type
typeConvert = GetPropertyConverter(propType, dpOrPiOrFi);
#if DEBUG
if( propType.Assembly.FullName == "PresentationFramework"
||
propType.Assembly.FullName == "PresentationCore"
||
propType.Assembly.FullName == "WindowsBase" )
{
Debug.WriteLine( "Reflected for type converter on " + propType.Name + "." + propName );
}
#endif
}
#if !STRESS
try
{
#endif
obj = typeConvert.ConvertFromString(typeContext, TypeConverterHelper.InvariantEnglishUS, value);
if( TraceMarkup.IsEnabled )
{
TraceMarkup.TraceActivityItem( TraceMarkup.TypeConvert,
typeConvert,
value,
obj );
}
#if !STRESS
}
catch (Exception e)
{
if( CriticalExceptions.IsCriticalException(e) || e is XamlParseException )
{
throw;
}
// If the targetObject can provide a fallback value for this property then use that instead
IProvidePropertyFallback iProvidePropertyFallback = targetObject as IProvidePropertyFallback;
if (iProvidePropertyFallback != null && iProvidePropertyFallback.CanProvidePropertyFallback(propName))
{
obj = iProvidePropertyFallback.ProvidePropertyFallback(propName, e);
if( TraceMarkup.IsEnabled )
{
TraceMarkup.TraceActivityItem( TraceMarkup.TypeConvertFallback,
typeConvert,
value,
obj );
}
}
// If we got the default object TypeConverter, then we know the conversion will
// fail, so create a more meaningful error message here.
else if (typeConvert.GetType() == typeof(TypeConverter))
{
string message;
if( propName != string.Empty )
{
// <SomeElement SomeProp="SomeText"/> and there's no TypeConverter
// to handle converting "SomeText" into an instance of something
// that can be set into SomeProp.
message = SR.Get(SRID.ParserDefaultConverterProperty, propType.FullName, propName, value);
}
else
{
// <SomeElement>SomeText</SomeElement> and there's no TypeConverter
// associated with the type SomeElement
message = SR.Get(SRID.ParserDefaultConverterElement, propType.FullName, value);
}
XamlParseException.ThrowException(parserContext, _lineNumber, _linePosition, message, null);
}
else
{
string message = TypeConverterFailure( value, propName, propType.FullName );
XamlParseException.ThrowException(parserContext, _lineNumber, _linePosition, message, e);
}
}
#endif
// Verify that the type converter actually gave us an instance of the correct object type.
if( obj != null )
{
if(!propType.IsAssignableFrom(obj.GetType()))
{
string message = TypeConverterFailure( value, propName, propType.FullName );
XamlParseException.ThrowException(parserContext, _lineNumber, _linePosition, message, null);
}
}
return obj;
}
private string TypeConverterFailure( string value, string propName, string propType )
{
string message;
if( propName != string.Empty )
{
// We were called to do type conversion on a string that's been
// assigned in an element attribute, but failed for whatever reason.
//
// <Rectangle Fill="Red"/>
//
// propName is 'Fill' in this case.
message = SR.Get(SRID.ParserCannotConvertPropertyValueString, value, propName, propType);
}
else
{
// We are being called by BamlRecordReader::GetObjectFromString
// which is not trying to convert a property. It's actually
// trying to get an element out of this.
//
// <SolidColorBrush>Red</SolidColorBrush>
//
// There is no associated propName available in this case, so we
// give a different error message.
message = SR.Get(SRID.ParserCannotConvertInitializationText, value, propType );
}
return message;
}
#endif
// ValidateNames does Name validation, and ValidateEnums does enum
// name validation. Note that both must be called to determine if a
// property is valid before it is set, but the order is not important. Hence
// ValidateNames can be called before writing out a BAML record, and
// ValidateEnums can be called later after the BAML record has been read.
/// <summary>
/// Validate the Name property.
/// This will throw an exception if the property is an
/// Name that does not follow the rules of only letters, digits and underscores in
/// Name names.
/// </summary>
internal void ValidateNames(
string value,
int lineNumber,
int linePosition)
{
// set the linenumber and position
_lineNumber = lineNumber;
_linePosition = linePosition;
if (value == string.Empty)
{
ThrowException(SRID.ParserBadName, value);
}
if (MarkupExtensionParser.LooksLikeAMarkupExtension(value))
{
string message = SR.Get(SRID.ParserBadUidOrNameME, value);
message += " ";
message += SR.Get(SRID.ParserLineAndOffset,
lineNumber.ToString(CultureInfo.CurrentCulture),
linePosition.ToString(CultureInfo.CurrentCulture));
XamlParseException parseException = new XamlParseException(message, lineNumber, linePosition);
throw parseException;
}
if (!NameValidationHelper.IsValidIdentifierName(value))
{
ThrowException(SRID.ParserBadName, value);
}
}
/// <summary>
/// Validate that if the type converter is
/// for enums you can't pass numbers to it.
/// </summary>
internal void ValidateEnums(
string propName,
Type propType,
string attribValue)
{
if (propType.IsEnum && attribValue != string.Empty)
{
// Handle enum strings of the form "one, two, three". Check that
// each of the values does NOT start with a digit. This doesn't
// validate that the enum is correct, just that there are no digits
// specified.
bool lookingForComma = false;
for (int i = 0; i < attribValue.Length; i++)
{
if (!Char.IsWhiteSpace(attribValue[i]))
{
if (lookingForComma)
{
if (attribValue[i] == ',')
{
lookingForComma = false;
}
}
else if (Char.IsDigit(attribValue[i]))
{
ThrowException(SRID.ParserNoDigitEnums, propName, attribValue);
}
else
{
lookingForComma = true;
}
}
}
}
}
/// <summary>
/// Get cached member info for the property name. This can be
/// a PropertyInfo for the property or a MethodInfo for the static
/// setter. This does not work for EventInfo, so don't call it.
/// </summary>
/// <param name="owner">Type of the owner of the property </param>
/// <param name="propName">Name of the property</param>
/// <param name="onlyPropInfo">True if the caller wants the PropertyInfo for the
/// case where both a MethodInfo and propertyInfo are cached for this property
/// </param>
/// <param name="infoRecord">The attribute info record retrieved from
/// the map table, if one is found. </param>
/// <remarks>
/// There is only one scenario under which two memberInfo need to be
/// cached for a given attribute. This is the case when there are both a
/// Clr wrapper and static Settor for a given DP. In that case we cache
/// an object array of two elements. Also the MethodInfo for the given DP
/// will be discovered first by the XamlReaderHelper while the PropertyInfo
/// will be discovered by the BamlRecordWriter.
/// </remarks>
private MemberInfo GetCachedMemberInfo(
Type owner,
string propName,
bool onlyPropInfo,
out BamlAttributeInfoRecord infoRecord)
{
infoRecord = null;
if (MapTable != null)
{
string fullName = owner.IsGenericType ? owner.Namespace + "." + owner.Name : owner.FullName;
object key = MapTable.GetAttributeInfoKey(fullName, propName);
infoRecord = MapTable.GetHashTableData(key) as BamlAttributeInfoRecord;
if (infoRecord != null)
{
return infoRecord.GetPropertyMember(onlyPropInfo) as MemberInfo;
}
}
return null;
}
#if !PBTCOMPILER
/// <summary>
/// Add cached member info for the property name.
/// </summary>
private void AddCachedAttributeInfo(
Type ownerType,
BamlAttributeInfoRecord infoRecord)
{
if (MapTable != null)
{
object key = MapTable.GetAttributeInfoKey(ownerType.FullName, infoRecord.Name);
MapTable.AddHashTableData(key, infoRecord);
}
}
/// <summary>
/// Helper function for getting Clr PropertyInfo on a type and updating the
/// passed attribute info record. Also update the property cache with this
/// attribute information if it was not already present.
/// </summary>
/// <remarks>
/// Note that the ObjectHashTable may contain
/// a BamlAttributeInfoRecord from a previous parse for the same property. If
/// we find one in the hash table, use its property info instead of reflecting.
/// </remarks>
internal void UpdateClrPropertyInfo(
Type currentParentType,
BamlAttributeInfoRecord attribInfo)
{
Debug.Assert(null != attribInfo, "null attribInfo");
Debug.Assert(null != currentParentType, "null currentParentType");
bool isInternal = false;
string propName = attribInfo.Name;
BamlAttributeInfoRecord cachedInfoRecord;
attribInfo.PropInfo = GetCachedMemberInfo(currentParentType, propName, true, out cachedInfoRecord)
as PropertyInfo;
if (attribInfo.PropInfo == null)
{
// If no cached property info, use the slow route of reflecting to get
// the property info.
attribInfo.PropInfo = PropertyInfoFromName(propName, currentParentType, !ReflectionHelper.IsPublicType(currentParentType), false, out isInternal);
attribInfo.IsInternal = isInternal;
if (attribInfo.PropInfo != null)
{
// If we successfully find a property info via reflection, cache it.
if (cachedInfoRecord != null)
{
cachedInfoRecord.SetPropertyMember(attribInfo.PropInfo);
cachedInfoRecord.IsInternal = attribInfo.IsInternal;
}
else
{
AddCachedAttributeInfo(currentParentType, attribInfo);
}
}
}
else
{
attribInfo.IsInternal = cachedInfoRecord.IsInternal;
}
}
private void UpdateAttachedPropertyMethdodInfo(BamlAttributeInfoRecord attributeInfo, bool isSetter)
{
MethodInfo attachedPropertyInfo = null;
Type propertyOwnerType = attributeInfo.OwnerType;
Debug.Assert(propertyOwnerType != null);
bool tryInternal = !ReflectionHelper.IsPublicType(propertyOwnerType);
string propName = (isSetter ? "Set" : "Get") + attributeInfo.Name;
BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy;
// Check Set\GetFoo method presence
try
{
if (!tryInternal)
{
// first try public methods
attachedPropertyInfo = propertyOwnerType.GetMethod(propName, flags);
}
if (attachedPropertyInfo == null)
{
// if public method not found, try non-public method next.
attachedPropertyInfo = propertyOwnerType.GetMethod(propName, flags | BindingFlags.NonPublic);
}
}
catch (AmbiguousMatchException)
{
}
int paramCount = isSetter ? 2 : 1;
if (attachedPropertyInfo != null && attachedPropertyInfo.GetParameters().Length == paramCount)
{
// the MethodInfo has to be public or internal.
Debug.Assert(attachedPropertyInfo.IsPublic ||
attachedPropertyInfo.IsAssembly ||
attachedPropertyInfo.IsFamilyOrAssembly);
if (isSetter)
{
attributeInfo.AttachedPropertySetter = attachedPropertyInfo;
}
else
{
attributeInfo.AttachedPropertyGetter = attachedPropertyInfo;
}
}
}
internal void UpdateAttachedPropertySetter(BamlAttributeInfoRecord attributeInfo)
{
if (attributeInfo.AttachedPropertySetter == null)
{
UpdateAttachedPropertyMethdodInfo(attributeInfo, true);
}
}
internal void UpdateAttachedPropertyGetter(BamlAttributeInfoRecord attributeInfo)
{
if (attributeInfo.AttachedPropertyGetter == null)
{
UpdateAttachedPropertyMethdodInfo(attributeInfo, false);
}
}
#endif
/// <summary>
/// Common helper method to resolve an xml XmlNamespace and LocalName to
/// either a EventInfo or a PropertyInfo.
/// </summary>
/// <param name="isEvent">True if Event, False look for Property</param>
/// <param name="owner">Type we should look for attribute on, can be null</param>
/// <param name="xmlNamespace">XmlNamespace or the Attribute</param>
/// <param name="localName">local Name of the Attribute</param>
/// <param name="propName">Name of the resolved property or event</param>
/// <returns>PropertyInfo or EventInfo for resolved property or event</returns>
internal MemberInfo GetClrInfo(
bool isEvent,
Type owner,
string xmlNamespace,
string localName,
ref string propName)
{
Debug.Assert(null != localName, "null localName");
Debug.Assert(null != xmlNamespace, "null xmlNamespace");
// adjust urtNamespace and localName if there are any periods in the localName.
string globalClassName = null;
int lastIndex = localName.LastIndexOf('.');
if (-1 != lastIndex)
{
// If using .net then match against the class.
globalClassName = localName.Substring(0, lastIndex);
localName = localName.Substring(lastIndex+1);
}
return GetClrInfoForClass(isEvent, owner, xmlNamespace, localName, globalClassName, ref propName);
}
#if PBTCOMPILER
// Checks to see if a given event handler delegate type is accessible.
static private bool IsAllowedEventDelegateType(Type delegateType)
{
if (!ReflectionHelper.IsPublicType(delegateType))
{
if (!ReflectionHelper.IsInternalType(delegateType) ||
!IsInternalAllowedOnType(delegateType))
{
return false;
}
}
return true;
}
// Checks to see if a given event's add method is accessible.
// Checks for protected add methods as well if requested.
private bool IsAllowedEvent(EventInfo ei, bool isProtectedAllowed)
{
MethodInfo mi = ei.GetAddMethod(true);
return IsAllowedMethod(mi, isProtectedAllowed);
}
// Checks to see if a given property's set method is accessible.
// Always checks for protected set methods as well.
internal bool IsAllowedPropertySet(PropertyInfo pi)
{
MethodInfo mi = pi.GetSetMethod(true);
return IsAllowedMethod(mi, true);
}
// Checks to see if a given property's get method is accessible.
// Checks for protected get methods as well if requested.
private bool IsAllowedPropertyGet(PropertyInfo pi, bool checkProtected)
{
MethodInfo mi = pi.GetGetMethod(true);
return IsAllowedMethod(mi, checkProtected);
}
// Checks to see if a given property's get method is accessible.
// Always checks for protected get methods as well.
internal bool IsAllowedPropertyGet(PropertyInfo pi)
{
MethodInfo mi = pi.GetGetMethod(true);
return IsAllowedMethod(mi, true);
}
// Checks to see if a given field member is accessible.
private bool IsAllowedField(FieldInfo fi)
{
bool allowed = false;
// No field, so not allowed
if (fi != null)
{
// field is public -- always allow.
allowed = fi.IsPublic;
if (!allowed)
{
// if not, try accessible internal fields.
// if the field from a base type, then it must be in the same assembly
// as the type from which it was reflected. If not, internals will not
// be allowed.
if (fi.ReflectedType.Assembly == fi.DeclaringType.Assembly)
{
// if reflected type is public, check to see if internals are allowed
// on that type (i.e local or friend). If not, the type has to be an
// internal allowed type due to the guaranteed central check in
// CreateTypeAndSerializer().
if (ReflectionHelper.IsPublicType(fi.ReflectedType))
{
allowed = IsInternalAllowedOnType(fi.ReflectedType);
}
else
{
allowed = true;
}
// Either ways, if reflected type is allowed only allow non-public
// fields that are internal.
allowed = allowed && (fi.IsAssembly || fi.IsFamilyOrAssembly);
}
}
}
return allowed;
}
// Checks to see if a given methodInfo (for a property's get\set method
// or an event's add method) is accessible.
private bool IsAllowedMethod(MethodInfo mi, bool checkProtected)
{
bool allowed = false;
// No method, so not allowed
if (mi != null)
{
// method is public -- always allow.
allowed = mi.IsPublic;
if (!allowed)
{
// method is not public.
// Next check to see if the mapper will allow looking for protected
// attributes. This will be the case if current methodInfo has been
// reflected off of the markup sub-classed root element, i.e one with
// an x:Class attribute, in which case IsProtectedAttributeAllowed will
// be true. So in this case allow protected if caller wishes for this
// by setting the checkProtected param to true.
if (checkProtected && IsProtectedAttributeAllowed)
{
// if so, allow protected or internal protected method.
allowed = mi.IsFamily || mi.IsFamilyOrAssembly;
}
if (!allowed)
{
// if not, try accessible internal methods.
// if the property or event inherits from a base type, then its
// accessor method must be in the same assembly as the type from
// which it was reflected. If not, internals will not be allowed.
if (mi.ReflectedType.Assembly == mi.DeclaringType.Assembly)
{
// if reflected type is public, check to see if internals are allowed
// on that type (i.e local or friend). If not, the type has to be an
// internal allowed type due to the guaranteed central check in
// CreateTypeAndSerializer().
if (ReflectionHelper.IsPublicType(mi.ReflectedType))
{
allowed = IsInternalAllowedOnType(mi.ReflectedType);
}
else
{
allowed = true;
}
// Either ways, if reflected type is allowed only allow non-public members
// that are internal.
allowed = allowed && (mi.IsAssembly || mi.IsFamilyOrAssembly);
}
}
}
}
return allowed;
}
#else
// Checks to see if a given property's set method is public.
// Used only in Xaml Load sceanrios.
internal bool IsAllowedPropertySet(PropertyInfo pi)
{
MethodInfo mi = pi.GetSetMethod(true);
return (mi != null && mi.IsPublic);
}
// Checks to see if a given property's get method is public.
// Used only in Xaml Load sceanrios.
internal bool IsAllowedPropertyGet(PropertyInfo pi)
{
MethodInfo mi = pi.GetGetMethod(true);
return (mi != null && mi.IsPublic);
}
// Checks to see if a given property's set method is accessible.
// Used only in compiled Baml Load sceanrios.
static internal bool IsAllowedPropertySet(PropertyInfo pi, bool allowProtected, out bool isPublic)
{
MethodInfo mi = pi.GetSetMethod(true);
bool isProtected = allowProtected && mi != null && mi.IsFamily;
// return isPublic == true only if the property is public on a base declaring Type.
// if the property is public on the reflected internal type itself, then we still
// need to call the generated helper to set the property.
isPublic = mi != null && mi.IsPublic && ReflectionHelper.IsPublicType(mi.DeclaringType);
return (mi != null && (mi.IsPublic || mi.IsAssembly || mi.IsFamilyOrAssembly || isProtected));
}
// Checks to see if a given property's get method is accessible.
// Used only in compiled Baml Load sceanrios.
static private bool IsAllowedPropertyGet(PropertyInfo pi, bool allowProtected, out bool isPublic)
{
MethodInfo mi = pi.GetGetMethod(true);
bool isProtected = allowProtected && mi != null && mi.IsFamily;
// return isPublic == true only if the property is public on a base declaring Type.
// if the property is public on the reflected internal type itself, then we still
// need to call the generated helper to get the property.
isPublic = mi != null && mi.IsPublic && ReflectionHelper.IsPublicType(mi.DeclaringType);
return (mi != null && (mi.IsPublic || mi.IsAssembly || mi.IsFamilyOrAssembly || isProtected));
}
// Checks to see if a given event's add method is accessible.
// Used only in compiled Baml Load sceanrios.
static private bool IsAllowedEvent(EventInfo ei, bool allowProtected, out bool isPublic)
{
MethodInfo mi = ei.GetAddMethod(true);
bool isProtected = allowProtected && mi != null && mi.IsFamily;
// return isPublic == true only if the event is public on a base declaring Type.
// if the event is public on the reflected internal type itself, then we still
// need to call the generated helper to hook up the event.
isPublic = mi != null && mi.IsPublic && ReflectionHelper.IsPublicType(mi.DeclaringType);
return (mi != null && (mi.IsPublic || mi.IsAssembly || mi.IsFamilyOrAssembly || isProtected));
}
#endif
// Checks to see if a given event's add method is public.
// Used in all (xaml load, xaml compile & compiled Baml Load sceanrios.
static private bool IsPublicEvent(EventInfo ei)
{
MethodInfo mi = ei.GetAddMethod(true);
return (mi != null && mi.IsPublic);
}
#if !PBTCOMPILER
/// <summary>
/// Allows a sub-classed XamlTypeMapper called under Full Trust to participate
/// in deciding if an internal type should be accessible.
/// </summary>
/// <param name="type">The internal type</param>
/// <returns>
/// When overriden, should return true if accessible, false if not.
/// Returns false by default, if no one overrides.
/// </returns>
protected virtual bool AllowInternalType(Type type)
{
return false;
}
private bool IsInternalTypeAllowedInFullTrust(Type type)
{
bool isAllowed = false;
// If the type is internal, then allow them to participate
// in deciding if that internal type should be accessible.
if (ReflectionHelper.IsInternalType(type))
{
isAllowed = AllowInternalType(type);
}
return isAllowed;
}
#endif
/// <summary>
/// Common helper method to resolve an xml XmlNamespace and LocalName to
/// either a EventInfo or a PropertyInfo.
/// </summary>
/// <param name="isEvent">True if Event, False look for Property</param>
/// <param name="owner">Type we should look for attribute on, can be null</param>
/// <param name="xmlNamespace">XmlNamespace or the Attribute</param>
/// <param name="localName">local Name of the Attribute with no class</param>
/// <param name="globalClassName">Class Name of the Attribute, or null if not present</param>
/// <param name="propName">Name of the resolved property or event</param>
/// <returns>PropertyInfo or EventInfo for resolved property or event</returns>
internal MemberInfo GetClrInfoForClass (
bool isEvent,
Type owner,
string xmlNamespace,
string localName,
string globalClassName,
ref string propName)
{
MemberInfo mi = null;
#if PBTCOMPILER
if (owner == null || ReflectionHelper.IsPublicType(owner))
{
#endif
// first, try normal lookup for public properties and events only.
mi = GetClrInfoForClass(isEvent, owner, xmlNamespace, localName, globalClassName, false, ref propName);
#if PBTCOMPILER
}
if (mi == null && owner != null)
{
// if lookup on internal type or if public property or event lookup failed,
// try internal ones as well, or protected if the type happens to be a
// code-generated root.
mi = GetClrInfoForClass(isEvent, owner, xmlNamespace, localName, globalClassName, true, ref propName);
}
#endif
return mi;
}
private MemberInfo GetClrInfoForClass(
bool isEvent,
Type owner,
string xmlNamespace,
string localName,
string globalClassName,
bool tryInternal,
ref string propName)
{
bool isInternal = false;
MemberInfo memberInfo = null;
BindingFlags defaultBinding = BindingFlags.Public;
#if PBTCOMPILER
if (tryInternal)
{
defaultBinding |= BindingFlags.NonPublic;
}
#endif
propName = null;
ParameterInfo[] pis = null;
// if this is a globalClass then resolve the type and then call the dpFromName
if (null != globalClassName)
{
TypeAndSerializer typeAndSerializer =
GetTypeOnly(xmlNamespace, globalClassName);
if (typeAndSerializer != null && typeAndSerializer.ObjectType != null)
{
BamlAttributeInfoRecord infoRecord;
Type objectType = typeAndSerializer.ObjectType;
memberInfo = GetCachedMemberInfo(objectType, localName, false, out infoRecord);
if (memberInfo == null)
{
if (isEvent)
{
// See if attached event first
memberInfo = objectType.GetMethod("Add" + localName + "Handler",
defaultBinding |
BindingFlags.Static |
BindingFlags.FlattenHierarchy);
// Make sure that we found a method of the right signature.
// Otherwise discard what you found.
if (memberInfo != null)
{
MethodInfo mi = memberInfo as MethodInfo;
if (mi != null)
{
pis = mi.GetParameters();
Type dependencyObjectType = KnownTypes.Types[(int)KnownElements.DependencyObject];
if (pis == null || pis.Length != 2 || !dependencyObjectType.IsAssignableFrom(pis[0].ParameterType))
{
memberInfo = null;
}
#if PBTCOMPILER
if (tryInternal && memberInfo != null && !IsAllowedMethod(mi, false))
{
ThrowException(SRID.ParserCantSetAttribute, "bubbling event", objectType.Name + "." + localName, "Add Handler method");
}
#endif
}
}
if (memberInfo == null)
{
// Not an attached event so try Clr event
memberInfo = objectType.GetEvent(localName,
defaultBinding |
BindingFlags.Instance |
BindingFlags.FlattenHierarchy);
if (memberInfo != null)
{
EventInfo ei = memberInfo as EventInfo;
#if PBTCOMPILER
if (!IsAllowedEventDelegateType(ei.EventHandlerType))
#else
if (!ReflectionHelper.IsPublicType(ei.EventHandlerType))
#endif
{
ThrowException(SRID.ParserEventDelegateTypeNotAccessible, ei.EventHandlerType.FullName, objectType.Name + "." + localName);
}
#if PBTCOMPILER
if (tryInternal)
{
// Check if the event add method accessor itself is accessible.
// Also if this is a non-public event on a public type, it will
// check to make sure that the public type is accessible\allowed.
if (!IsAllowedEvent(ei, false))
{
ThrowException(SRID.ParserCantSetAttribute, "event", objectType.Name + "." + localName, "add");
}
}
else
{
#endif
// Check if the event add method accessor itself is public.
if (!IsPublicEvent(ei))
{
#if PBTCOMPILER
memberInfo = null;
#else
ThrowException(SRID.ParserCantSetAttribute, "event", objectType.Name + "." + localName, "add");
#endif
}
#if PBTCOMPILER
}
#endif
}
}
}
else
{
// See if attached property first - start from a Setter
memberInfo = objectType.GetMethod("Set" + localName,
defaultBinding |
BindingFlags.Static |
BindingFlags.FlattenHierarchy);
if (memberInfo != null && ((MethodInfo)memberInfo).GetParameters().Length != 2)
{
memberInfo = null;
}
// Try read-only case (Getter only)
if (memberInfo == null)
{
memberInfo = objectType.GetMethod("Get" + localName,
defaultBinding |
BindingFlags.Static |
BindingFlags.FlattenHierarchy);
if (memberInfo != null && ((MethodInfo)memberInfo).GetParameters().Length != 1)
{
memberInfo = null;
}
}
#if PBTCOMPILER
if (tryInternal && memberInfo != null && !IsAllowedMethod(memberInfo as MethodInfo, false))
{
ThrowException(SRID.ParserCantSetAttribute, "attached property", objectType.Name + "." + localName, "Set method");
}
#endif
if (memberInfo == null)
{
// Not an attached property, so try clr property
memberInfo = PropertyInfoFromName(localName, objectType, tryInternal, true, out isInternal);
// If we've found a property info, then the owner had better
// be the same type as or a subclass of the objectType, or
// they are in different inheritance hierarchies.
if (memberInfo != null)
{
if (owner != null &&
!objectType.IsAssignableFrom(owner))
{
ThrowException(SRID.ParserAttachedPropInheritError,
String.Format(CultureInfo.CurrentCulture, "{0}.{1}", objectType.Name, localName),
owner.Name);
}
}
}
if (null != memberInfo)
{
if (infoRecord != null)
{
#if !PBTCOMPILER
// DP's aren't present in the PBT case
if (infoRecord.DP == null)
{
infoRecord.DP = MapTable.GetDependencyProperty(infoRecord);
}
#endif
infoRecord.SetPropertyMember(memberInfo);
}
}
}
}
}
}
else if (null != owner)
{
Type baseType = owner;
// See if the owner knows about this class.
// Look for a parent type until we find a match or fail.
if (null != baseType)
{
BamlAttributeInfoRecord infoRecord;
memberInfo = GetCachedMemberInfo(baseType, localName, false, out infoRecord);
if (memberInfo == null)
{
if (isEvent)
{
// See if attached event first
memberInfo = baseType.GetMethod("Add" + localName + "Handler",
defaultBinding | BindingFlags.Static | BindingFlags.FlattenHierarchy);
// Make sure that we found a method of the right signature.
// Otherwise discard what you found.
if (memberInfo != null)
{
MethodInfo mi = memberInfo as MethodInfo;
if (mi != null)
{
pis = mi.GetParameters();
Type dependencyObjectType = KnownTypes.Types[(int)KnownElements.DependencyObject];
if (pis == null || pis.Length != 2 || !dependencyObjectType.IsAssignableFrom(pis[0].ParameterType))
{
memberInfo = null;
}
#if PBTCOMPILER
if (tryInternal && memberInfo != null && !IsAllowedMethod(mi, true))
{
ThrowException(SRID.ParserCantSetAttribute, "bubbling event", owner.Name + "." + localName, "Add Handler method");
}
#endif
}
}
if (memberInfo == null)
{
// Not an attached event, so try for a clr event.
memberInfo = baseType.GetEvent(localName,
BindingFlags.Instance | BindingFlags.FlattenHierarchy | defaultBinding);
if (memberInfo != null)
{
EventInfo ei = memberInfo as EventInfo;
#if PBTCOMPILER
if (!IsAllowedEventDelegateType(ei.EventHandlerType))
#else
if (!ReflectionHelper.IsPublicType(ei.EventHandlerType))
#endif
{
ThrowException(SRID.ParserEventDelegateTypeNotAccessible, ei.EventHandlerType.FullName, owner.Name + "." + localName);
}
#if PBTCOMPILER
if (tryInternal)
{
// Check if the event add method accessor itself is accessible.
// Also if this is a non-public event on a public type, it will
// not check to make sure that the public type is accessible\allowed
// since that would have all ready been done in the caller of this fucntion.
if (!IsAllowedEvent(ei, true))
{
ThrowException(SRID.ParserCantSetAttribute, "event", owner.Name + "." + localName, "add");
}
}
else
{
#endif
// check if the event add method accessor itself is public.
if (!IsPublicEvent(ei))
{
#if PBTCOMPILER
memberInfo = null;
#else
ThrowException(SRID.ParserCantSetAttribute, "event", owner.Name + "." + localName, "add");
#endif
}
#if PBTCOMPILER
}
#endif
}
}
}
else
{
// See if attached property first - start from a Setter
memberInfo = baseType.GetMethod("Set" + localName,
defaultBinding |
BindingFlags.Static |
BindingFlags.FlattenHierarchy);
if (memberInfo != null && ((MethodInfo)memberInfo).GetParameters().Length != 2)
{
memberInfo = null;
}
// Try read-only case (Getter only)
if (memberInfo == null)
{
memberInfo = baseType.GetMethod("Get" + localName,
defaultBinding |
BindingFlags.Static |
BindingFlags.FlattenHierarchy);
if (memberInfo != null && ((MethodInfo)memberInfo).GetParameters().Length != 1)
{
memberInfo = null;
}
}
#if PBTCOMPILER
if (tryInternal && memberInfo != null && !IsAllowedMethod(memberInfo as MethodInfo, true))
{
ThrowException(SRID.ParserCantSetAttribute, "attached property", owner.Name + "." + localName, "Set method");
}
#endif
if (memberInfo == null)
{
// Not an attached property, so try for a clr property.
memberInfo = PropertyInfoFromName(localName, baseType, tryInternal, true, out isInternal);
}
if (null != memberInfo)
{
if (infoRecord != null)
{
#if !PBTCOMPILER
// DP's aren't present in the PBT case
if (infoRecord.DP == null)
{
infoRecord.DP = MapTable.GetDependencyProperty(infoRecord);
}
#endif
infoRecord.SetPropertyMember(memberInfo);
}
}
}
}
}
}
if (null != memberInfo)
{
propName = localName;
}
return memberInfo;
}
#if !PBTCOMPILER
/// <summary>
/// Helper method to get an event on an owner, walking up the class hierarchy
/// when doing so
/// </summary>
/// <param name="owner">Type we should look for the event on</param>
/// <param name="eventName">Then name of the handler of the event</param>
/// <returns>EventInfo for resolved event</returns>
internal EventInfo GetClrEventInfo(
Type owner,
string eventName)
{
Debug.Assert(null != eventName, "null eventName");
Debug.Assert(null != owner, "null owner");
EventInfo eventInfo = null;
// Look up the parent chain until we find a match or fail by
// going off the top of the chain.
while (owner != null)
{
eventInfo = owner.GetEvent(eventName, BindingFlags.Instance | BindingFlags.Public);
if (eventInfo != null)
{
break;
}
owner = GetCachedBaseType(owner);
}
return eventInfo;
}
/// <summary>
/// Helper method to resolve an xml namespace and localName to
/// either a RoutedEvent or a DependencyProperty. If they are not present,
/// still resolve using a guess at the valid setter name to look for.
/// </summary>
/// <remarks>
/// Note that this will not resolve clr properties. Call GetClrInfo to do that.
/// </remarks>
/// <param name="isEvent">True if Event, False look for Property</param>
/// <param name="owner">Type we should look for attribute on, can be null</param>
/// <param name="xmlNamespace">XmlNamespace or the Attribute</param>
/// <param name="localName">local Name of the Attribute</param>
/// <param name="baseType">Base type the object was found on</param>
/// <param name="dynamicObjectName">registered name of the Object on the type.</param>
/// <returns>resolved object, which can be a RoutedEvent, a DependencyProperty
/// or the MethodInfo for the event or property setter</returns>
internal object GetDependencyObject(
bool isEvent,
Type owner,
string xmlNamespace,
string localName,
ref Type baseType,
ref string dynamicObjectName)
{
Debug.Assert(null != localName, "null localName");
Debug.Assert(null != xmlNamespace, "null xmlNamespace");
object memInfo = null;
string globalClassName = null;
dynamicObjectName = null;
// Extract the class name if there are any periods in the localName.
int lastIndex = localName.LastIndexOf('.');
if (-1 != lastIndex)
{
// if using .net then match against the class.
globalClassName = localName.Substring(0,lastIndex);
localName = localName.Substring(lastIndex+1);
}
// If this is a globalClassName then resolve the type and then call
// DependencyProperty.FromName.
if (null != globalClassName)
{
TypeAndSerializer typeAndSerializer =
GetTypeOnly(xmlNamespace,globalClassName);
if (typeAndSerializer != null && typeAndSerializer.ObjectType != null)
{
baseType = typeAndSerializer.ObjectType;
if (isEvent)
{
memInfo = RoutedEventFromName(localName,baseType);
}
else
{
memInfo = DependencyProperty.FromName(localName, baseType);
}
if (null != memInfo)
{
Debug.Assert(null != baseType, "baseType not set");
dynamicObjectName = localName;
}
}
}
else
{
NamespaceMapEntry[] namespaceMaps = GetNamespaceMapEntries(xmlNamespace);
if (null == namespaceMaps)
{
return null;
}
baseType = owner;
// See if the owner knows about this class.
// Look for a parent type with any namespace matching the property
while (null != baseType)
{
bool foundNamespaceMatch = false;
// Look at each namespace for a match with this baseType
for (int count = 0;
count < namespaceMaps.Length && !foundNamespaceMatch;
count ++)
{
NamespaceMapEntry namespaceMap = namespaceMaps[count];
// see if the urtNamespace in the namespace map is valid
// for the type we are trying to apply
if (namespaceMap.ClrNamespace == GetCachedNamespace(baseType))
{
foundNamespaceMatch = true;
}
}
if (foundNamespaceMatch)
{
// For 'normal' properties and events that are not prefixed by
// a class name, only attempt to get dependency IDs and Events.
// The caller should use GetClrInfo to get CLR properties for
// 'normal' properties and events if this attempt fails.
if (isEvent)
{
memInfo = RoutedEventFromName(localName,baseType);
}
else
{
memInfo = DependencyProperty.FromName(localName, baseType);
}
}
// Only do one loop for events, since all base classes are checked in
// a single operation. For properties, loop through the base classes here.
if (null != memInfo || isEvent)
{
// for assembly and typeName use the original, not the base
// type we found it on.
dynamicObjectName = localName;
break;
}
else
{
baseType = GetCachedBaseType(baseType);
}
}
}
return memInfo;
}
///<summary>
/// Returns a DependencyProperty given a local name and an xml namespace
///</summary>
///<param name="localName">
/// The property name
///</param>
///<param name="xmlNamespace">
/// Xml namespace associated with name
///</param>
///<param name="ownerType">
/// The Type where this DP was registered.
///</param>
///<returns>
/// Returns a DependencyProperty the attached property
///</returns>
internal DependencyProperty DependencyPropertyFromName(
string localName,
string xmlNamespace,
ref Type ownerType)
{
Debug.Assert(null != localName, "null localName");
Debug.Assert(null != xmlNamespace, "null xmlNamespace");
// Adjust localName if there are any periods that indicate a global class. Use
// this class name as the owner type and return it. Otherwise just use the
// passed name and owner.
int lastIndex = localName.LastIndexOf('.');
if (-1 != lastIndex)
{
string globalClassName = localName.Substring(0,lastIndex);
localName = localName.Substring(lastIndex+1);
TypeAndSerializer typeAndSerializer =
GetTypeOnly(xmlNamespace, globalClassName);
if (typeAndSerializer == null || typeAndSerializer.ObjectType == null)
{
ThrowException(SRID.ParserNoType, globalClassName);
}
ownerType = typeAndSerializer.ObjectType;
}
if(null == ownerType)
{
throw new ArgumentNullException( "ownerType" );
}
return DependencyProperty.FromName(localName, ownerType);
}
#endif
/// <summary>
/// Return the property that has an attached XmlLang attribute. This identifies this
/// property as being the one to receive xml:lang attribute values when parsing, or
/// the holder of the CultureInfo related string. The XamlTypeMapper caches this
/// along with the TypeAndSerializer information for fast retrieval.
/// </summary>
internal PropertyInfo GetXmlLangProperty(
string xmlNamespace, // xml namespace for the type
string localName) // local name of the type without any '.'
{
TypeAndSerializer typeAndSerializer = GetTypeOnly(xmlNamespace, localName);
if (typeAndSerializer == null || typeAndSerializer.ObjectType == null)
{
return null;
}
if (typeAndSerializer.XmlLangProperty == null)
{
BamlAssemblyInfoRecord bairPF = MapTable.GetAssemblyInfoFromId(-1);
if (typeAndSerializer.ObjectType.Assembly == bairPF.Assembly)
{
if (KnownTypes.Types[(int)KnownElements.FrameworkElement].IsAssignableFrom(typeAndSerializer.ObjectType) ||
KnownTypes.Types[(int)KnownElements.FrameworkContentElement].IsAssignableFrom(typeAndSerializer.ObjectType))
{
typeAndSerializer.XmlLangProperty = (KnownTypes.Types[(int)KnownElements.FrameworkElement]).GetProperty("Language",
BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
}
}
else
{
string xmlLangPropertyName = null;
bool xmlLangPropertyFound = false;
#if !PBTCOMPILER
AttributeCollection attributes = TypeDescriptor.GetAttributes(typeAndSerializer.ObjectType);
if (attributes != null)
{
XmlLangPropertyAttribute xlpa = attributes[typeof(XmlLangPropertyAttribute)] as XmlLangPropertyAttribute;
if (xlpa != null)
{
xmlLangPropertyFound = true;
xmlLangPropertyName = xlpa.Name;
}
}
#else
Type typeValue = null;
xmlLangPropertyName = ReflectionHelper.GetCustomAttributeData(typeAndSerializer.ObjectType,
KnownTypes.Types[(int)KnownElements.XmlLangPropertyAttribute],
false,
ref xmlLangPropertyFound,
out typeValue);
#endif
if ( xmlLangPropertyFound )
{
if( xmlLangPropertyName != null && xmlLangPropertyName.Length > 0)
{
typeAndSerializer.XmlLangProperty = typeAndSerializer.ObjectType.GetProperty(
xmlLangPropertyName,
BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
}
if( typeAndSerializer.XmlLangProperty == null )
{
// Either the given name could not be found, or there
// was no name specified at all. (null or empty string.)
// The latter case may get a special meaning in the future,
// but for now they're all errors.
ThrowException(SRID.ParserXmlLangPropertyValueInvalid);
}
}
}
}
return typeAndSerializer.XmlLangProperty;
}
///<summary>
/// Returns a PropertyInfo from an attribute name, given the ownerType of
/// the property.
///</summary>
///<param name="localName">
/// The attribute name
///</param>
///<param name="ownerType">
/// The Type that owns the attribute
///</param>
///<param name="tryInternal">
/// Indicates if this function should search for non-public properties as well
///</param>
///<param name="tryPublicOnly">
/// Indicates if this function should search for public properties only, regardless
/// of tryInternal as is the case in XamlLoad sceanrios.
///</param>
///<param name="isInternal">
/// Indicates if this fucntion actually found a non-public property
///</param>
///<returns>
/// Returns a PropertyInfo for the property
///</returns>
private PropertyInfo PropertyInfoFromName(
string localName,
Type ownerType,
bool tryInternal,
bool tryPublicOnly,
out bool isInternal)
{
PropertyInfo info = null;
isInternal = false;
TypeInformationCacheData typeInfo = GetCachedInformationForType(ownerType);
Debug.Assert(typeInfo != null, "Must have cached type info at this point");
PropertyAndType propAndType = typeInfo.GetPropertyAndType(localName);
// peterost - This is a TEMPORARY workaround to
// properties that have been overridden in some classes using the
// "new" operator. This should be removed when properties such as
// Window.Width and ColumnDefintion.Width are rationalized.
if (propAndType == null || !propAndType.PropInfoSet)
{
try
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.Public;
#if PBTCOMPILER
if (tryInternal)
{
flags |= BindingFlags.NonPublic;
}
info = ownerType.GetProperty(localName, flags);
#else
if (!tryInternal)
{
info = ownerType.GetProperty(localName, flags);
}
// Xaml load scenarios should not look for internals - tryPublicOnly == true
// If the above load failed then try again looking at internals, unless
// tryPublicOnly tells us not to do that.
if (info == null && !tryPublicOnly)
{
info = ownerType.GetProperty(localName, flags | BindingFlags.NonPublic);
if (info != null)
{
isInternal = true;
}
}
#endif
}
catch (AmbiguousMatchException)
{
PropertyInfo[] infos = ownerType.GetProperties(
BindingFlags.Instance | BindingFlags.Public);
for (int i = 0; i < infos.Length; i++)
{
if (infos[i].Name == localName)
{
info = infos[i];
break;
}
}
}
#if PBTCOMPILER
if (tryInternal || info != null)
{
#endif
typeInfo.SetPropertyAndType(localName, info, ownerType, isInternal);
#if PBTCOMPILER
}
#endif
}
else
{
info = propAndType.PropInfo;
isInternal = propAndType.IsInternal;
}
return info;
}
#if !PBTCOMPILER
///<summary>
/// Returns a RoutedEvent from an attribute name
///</summary>
///<param name="localName">
/// The attribute name
///</param>
///<param name="ownerType">
/// The Type that owns the attribute
///</param>
///<returns>
/// Returns a RoutedEvent for the name
///</returns>
internal RoutedEvent RoutedEventFromName(
string localName,
Type ownerType)
{
RoutedEvent Event = null;
Type currentType = ownerType;
// Force load the Statics by walking up the hierarchy and running class constructors
while (null != currentType)
{
MS.Internal.WindowsBase.SecurityHelper.RunClassConstructor(currentType);
currentType = GetCachedBaseType(currentType);
}
// EventManager takes care of going up the hierarchy, so we don't need to loop here
// to do it. Just do one call.
Event = EventManager.GetRoutedEventFromName(localName,ownerType);
return Event;
}
#endif
/// <summary>
/// Given an object that is either a PropertyInfo, MethodInfo for the static
/// setter, or DependencyProperty, return the type of the property. This assumes
/// the Avalon rule that a DependencyProperty has a static setter where the
/// second parameter gives the type of the property.
/// </summary>
internal static Type GetPropertyType(object propertyMember)
{
Type propertyType;
bool propertyCanWrite;
GetPropertyType(propertyMember, out propertyType, out propertyCanWrite);
return propertyType;
}
/// <summary>
/// Given an object that is either a PropertyInfo, MethodInfo for the static
/// setter, or DependencyProperty, return the type of the property. This assumes
/// the Avalon rule that a DependencyProperty has a static setter where the
/// second parameter gives the type of the property.
/// </summary>
internal static void GetPropertyType(
object propertyMember,
out Type propertyType,
out bool propertyCanWrite)
{
#if !PBTCOMPILER
DependencyProperty dp = propertyMember as DependencyProperty;
if (dp != null)
{
propertyType = dp.PropertyType;
propertyCanWrite = !dp.ReadOnly;
}
else
{
#endif
PropertyInfo propertyInfo = propertyMember as PropertyInfo;
if (propertyInfo != null)
{
propertyType = propertyInfo.PropertyType;
propertyCanWrite = propertyInfo.CanWrite;
}
else
{
MethodInfo methodInfo = propertyMember as MethodInfo;
if (methodInfo != null)
{
ParameterInfo[] parameters = methodInfo.GetParameters();
propertyType = parameters.Length == 1 ? methodInfo.ReturnType : parameters[1].ParameterType;
propertyCanWrite = parameters.Length == 1 ? false : true;
}
else
{
// If its not a propertyinfo, methodinfo, or dependencyproperty,
// all we know is that it must be an object...
propertyType = typeof(object);
propertyCanWrite = false;
}
}
#if !PBTCOMPILER
}
#endif
}
/// <summary>
/// Given an object that is either a PropertyInfo, MethodInfo for the static
/// setter, or DependencyProperty, return the name of the property. This assumes
/// the Avalon rule that a DependencyProperty has a static getter "Get" + name.
/// </summary>
internal static string GetPropertyName(object propertyMember)
{
#if !PBTCOMPILER
DependencyProperty dp = propertyMember as DependencyProperty;
if (dp != null)
{
return dp.Name;
}
#endif
PropertyInfo propertyInfo = propertyMember as PropertyInfo;
if (propertyInfo != null)
{
return propertyInfo.Name;
}
else
{
MethodInfo methodInfo = propertyMember as MethodInfo;
if (methodInfo != null)
{
return methodInfo.Name.Substring("Get".Length);
}
}
return null;
}
/// <summary>
/// Given an object that is either a PropertyInfo, MethodInfo for the static
/// setter, or DependencyProperty, return the type of the object that declares
/// or owns this property.
/// </summary>
internal static Type GetDeclaringType(object propertyMember)
{
Type validType = null;
MemberInfo memInfo = propertyMember as MemberInfo;
if (memInfo != null)
{
validType = memInfo.DeclaringType;
}
else
{
#if !PBTCOMPILER
Debug.Assert( propertyMember is DependencyProperty);
validType = ((DependencyProperty)propertyMember).OwnerType;
#endif
}
return validType;
}
#endregion Properties
#region Types
#if !PBTCOMPILER
/// <summary>
/// Return the type that corresponds to typeName, given that the type is
/// located as a subelement or property on the passed element.
/// </summary>
/// <param name="typeName">
/// The full xaml name of a type, including an xml namespace prefix, if needed.
/// The name is of the form prefix:typename, such as MyNs:MyNewButton
/// </param>
/// <param name="element">
/// A DependencyObject that is logical parent for the type to be resolved. This
/// is required because it is this element (or its ancestors) that contains
/// namespace mapping data that is needed to resolve the typeName.
/// </param>
/// <returns>
/// The resolved clr type. Null if not found
/// </returns>
internal static Type GetTypeFromName(string typeName, DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException( "element" );
}
if (typeName == null)
{
throw new ArgumentNullException( "typeName" );
}
// Now map the prefix to an xml namespace uri
int colonIndex = typeName.IndexOf(':');
string prefix = string.Empty;
if (colonIndex > 0)
{
prefix = typeName.Substring(0, colonIndex);
typeName = typeName.Substring(colonIndex+1, typeName.Length-colonIndex-1);
}
// First, get the xmlns dictionary to map prefixes to xml namespace uris
XmlnsDictionary prefixDictionary = element.GetValue(XmlAttributeProperties.XmlnsDictionaryProperty)
as XmlnsDictionary;
object xmlNamespaceObject = (prefixDictionary != null) ? prefixDictionary[prefix] : null;
// Then get the list of NamespaceMapEntry objects that maps the xml namespace uri to one
// or more clr namespace / assembly pairs. This should be stored on the root element
// of the tree.
Hashtable namespaceMaps = element.GetValue(XmlAttributeProperties.XmlNamespaceMapsProperty)
as Hashtable;
NamespaceMapEntry[] namespaces = (namespaceMaps != null && xmlNamespaceObject != null) ? namespaceMaps[xmlNamespaceObject] as NamespaceMapEntry[] : null;
if (namespaces == null)
{
// If the namespace prefix is empty, we may not have
// loaded the default namespace. Get this from
// the token reader. NOTE: This is a temporary stopgap
// until we figure out exact requirements for namespace
// resolution as it applies to styles, etc.
if (prefix == string.Empty)
{
List<ClrNamespaceAssemblyPair> namespaceAssemblyPair = GetClrNamespacePairFromCache(XamlReaderHelper.DefaultNamespaceURI);
foreach (ClrNamespaceAssemblyPair usd in namespaceAssemblyPair)
{
if (usd.AssemblyName != null)
{
Assembly assy = ReflectionHelper.LoadAssembly(usd.AssemblyName, null);
if (assy != null)
{
string fullTypeName = String.Format(TypeConverterHelper.InvariantEnglishUS, "{0}.{1}", usd.ClrNamespace, typeName);
Type t = assy.GetType(fullTypeName);
if (t != null)
return t;
}
}
}
}
// Stopgap didn't work, so fail now.
return null;
}
// Check all the clr namespace / assembly pairs to see if there is a type
// that matches the passed short name. Return it if found.
for (int i = 0; i < namespaces.Length; i++)
{
Assembly assy = namespaces[i].Assembly;
if (assy != null)
{
string fullTypeName = String.Format(TypeConverterHelper.InvariantEnglishUS, "{0}.{1}", namespaces[i].ClrNamespace, typeName);
Type t = assy.GetType(fullTypeName);
if (t != null)
{
return t;
}
}
}
// Didn't find a match, so return null.
return null;
}
#endif
// Given a qualified member Name, returns its declaring Type and its name as a string.
internal Type GetTargetTypeAndMember(string valueParam,
ParserContext context,
bool isTypeExpected,
out string memberName)
{
string typeName = valueParam;
string prefix = String.Empty;
int typeIndex = typeName.IndexOf(':');
if (typeIndex >= 0)
{
prefix = typeName.Substring(0, typeIndex);
typeName = typeName.Substring(typeIndex + 1);
}
memberName = null;
Type targetType = null;
typeIndex = typeName.LastIndexOf('.');
if (typeIndex >= 0)
{
memberName = typeName.Substring(typeIndex + 1);
typeName = typeName.Substring(0, typeIndex);
string namespaceUri = context.XmlnsDictionary[prefix];
TypeAndSerializer tas = GetTypeOnly(namespaceUri, typeName);
if (tas != null)
{
targetType = tas.ObjectType;
}
if (targetType == null)
{
ThrowException(SRID.ParserNoType, typeName);
}
}
else if (!isTypeExpected && prefix.Length == 0)
{
// A Type may not be expected for e.g. for TemplateBinding param
// values. In this case there must also not be a prefix. If there
// is one it will just point to a namespace and not a Type.
memberName = typeName;
}
else
{
// A type was expected but we didn't find one. So throw.
ThrowException(SRID.ParserBadMemberReference, valueParam);
}
return targetType;
}
// Given a qualified member Name, returns its declaring Type and its name as a string.
internal Type GetDependencyPropertyOwnerAndName(string memberValue,
ParserContext context,
Type defaultTargetType,
out string memberName)
{
Type targetType = GetTargetTypeAndMember(memberValue, context, false, out memberName);
if (targetType == null)
{
targetType = defaultTargetType;
if (targetType == null)
{
// if there was also no default target type then throw.
ThrowException(SRID.ParserBadMemberReference, memberValue);
}
}
Debug.Assert(memberName != null);
string fieldName = memberName + "Property";
MemberInfo memberInfo = GetStaticMemberInfo(targetType, fieldName, true);
Debug.Assert(memberInfo != null);
// Need to get the actual type that declares the DP in order to
// correctly find a possible hit in the KnownProperties table.
if (memberInfo.DeclaringType != targetType)
{
targetType = memberInfo.DeclaringType;
}
return targetType;
}
// Gets the PropertyInfo or FieldInfo of a member.
internal MemberInfo GetStaticMemberInfo(Type targetType, string memberName, bool fieldInfoOnly)
{
Debug.Assert(targetType != null);
// first try public members only.
MemberInfo mi = GetStaticMemberInfo(targetType, memberName, fieldInfoOnly, false);
#if PBTCOMPILER
if (mi == null)
{
// If not found, then try non-public members next.
mi = GetStaticMemberInfo(targetType, memberName, fieldInfoOnly, true);
if (mi != null)
{
// if found, check access levels to see if it should really be allowed.
bool isAllowed = false;
PropertyInfo pi = mi as PropertyInfo;
if (pi != null)
{
isAllowed = IsAllowedPropertyGet(pi, false);
}
else
{
isAllowed = IsAllowedField(mi as FieldInfo);
}
if (!isAllowed)
{
ThrowException(SRID.ParserStaticMemberNotAllowed, memberName, targetType.Name);
}
}
}
#endif
if (mi == null)
{
ThrowException(SRID.ParserInvalidStaticMember, memberName, targetType.Name);
}
return mi;
}
private MemberInfo GetStaticMemberInfo(Type targetType, string memberName, bool fieldInfoOnly, bool tryInternal)
{
MemberInfo memberInfo = null;
BindingFlags bf = BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Static;
if (tryInternal)
{
bf |= BindingFlags.NonPublic;
}
if (!fieldInfoOnly)
{
memberInfo = targetType.GetProperty(memberName, bf);
}
if (memberInfo == null)
{
memberInfo = targetType.GetField(memberName, bf);
}
return memberInfo;
}
/// <summary>
/// Get the Type that type corresponds to a localName in
/// the given namespace. Note that localName can be of the form classname.typename,
/// and can not include a namespace prefix.
/// </summary>
/// <remarks>
/// Return the actual type and the serializer for that type as a
/// TypeAndSerializer object from the cache. Note that in this call
/// the Serializer information may not be present if a new TypeAndSerializer
/// instance is created. Be sure to check the IsSerializerTypeSet flag.
/// </remarks>
internal TypeAndSerializer GetTypeOnly (
string xmlNamespace, // xml namespace for the type
string localName) // local name of the type without any '.'
{
Debug.Assert(null != xmlNamespace,"null value passed for xmlNamespace");
Debug.Assert(null != localName,"null value passed for localName");
// check if object is in the Hash.
String hashString = xmlNamespace + ":" + localName;
TypeAndSerializer typeAndSerializer =
_typeLookupFromXmlHashtable[hashString] as TypeAndSerializer;
if (null == typeAndSerializer)
{
if (!_typeLookupFromXmlHashtable.Contains(hashString))
{
typeAndSerializer = CreateTypeAndSerializer(xmlNamespace, localName);
_typeLookupFromXmlHashtable[hashString] = typeAndSerializer;
}
}
return typeAndSerializer;
}
/// <summary>
/// Get the Type and serializer for that type corresponding to a localName in
/// the given namespace. Note that localName can be of the form classname.typename,
/// and can not include a namespace prefix.
/// </summary>
/// <remarks>
/// Return the actual type and the serializer for that type as a
/// TypeAndSerializer object from the cache. If there is no
/// serializer defined, as is the case for clr objects, then null is set
/// for the SerializerType in the returned TypeAndSerializer. Also if this type is
/// associated with a property we will check for serializer attributes on the property first.
/// If no matching attribute is found for the property we resort to search for the attribute on the given type.
/// </remarks>
internal TypeAndSerializer GetTypeAndSerializer (
string xmlNamespace, // xml namespace for the type
string localName, // local name of the type without any '.'
object dpOrPiorMi) // property associated with the type
{
Debug.Assert(null != xmlNamespace,"null value passed for xmlNamespace");
Debug.Assert(null != localName,"null value passed for localName");
// check if object is in the Hash.
String hashString = xmlNamespace + ":" + localName;
TypeAndSerializer typeAndSerializer =
_typeLookupFromXmlHashtable[hashString] as TypeAndSerializer;
if (null == typeAndSerializer)
{
if (!_typeLookupFromXmlHashtable.Contains(hashString))
{
typeAndSerializer = CreateTypeAndSerializer(xmlNamespace, localName);
_typeLookupFromXmlHashtable[hashString] = typeAndSerializer;
}
}
// If we've found a TypeAndSerializer, check whether we have reflected for the
// serializer information yet. If not, then do it now.
if (typeAndSerializer != null && !typeAndSerializer.IsSerializerTypeSet)
{
// Check for SerializerAttribute on the type. The serializer for the type is evaluated
// the very first time we create a new data strcuture for the given type.
typeAndSerializer.SerializerType = GetXamlSerializerForType(typeAndSerializer.ObjectType);
typeAndSerializer.IsSerializerTypeSet = true;
}
return typeAndSerializer;
}
#if PBTCOMPILER
private static bool IsFriendAssembly(Assembly assembly)
{
// WinFX assemblies can never be friends of compiled assemblies, so just bail out.
if (assembly == XamlTypeMapper.AssemblyPF ||
assembly == XamlTypeMapper.AssemblyPC ||
assembly == XamlTypeMapper.AssemblyWB)
{
return false;
}
return ReflectionHelper.IsFriendAssembly(assembly);
}
private static bool IsInternalAllowedOnType(Type type)
{
bool isInternalAllowed = ReflectionHelper.LocalAssemblyName == type.Assembly.GetName().Name ||
IsFriendAssembly(type.Assembly);
_hasInternals = _hasInternals || isInternalAllowed;
return isInternalAllowed;
}
private static bool IsInternalAllowedOnType(NamespaceMapEntry namespaceMap)
{
bool isInternalAllowed = namespaceMap.LocalAssembly || IsFriendAssembly(namespaceMap.Assembly);
_hasInternals = _hasInternals || isInternalAllowed;
return isInternalAllowed;
}
internal static bool HasInternals
{
get { return _hasInternals; }
set { _hasInternals = value; }
}
internal static bool HasLocalReference
{
get
{
return _hasLocalReference;
}
}
#endif
/// <summary>
/// Create a TypeAndSerializer object for the passed data, if a valid Type
/// is found.
/// </summary>
private TypeAndSerializer CreateTypeAndSerializer(
string xmlNamespace, // xml namespace for the type
string localName) // local name of the type without any '.'
{
TypeAndSerializer typeAndSerializer = null;
NamespaceMapEntry[] namespaceMaps = GetNamespaceMapEntries(xmlNamespace);
if (namespaceMaps != null)
{
// We'll do a first pass with only known types
// and then do a second pass with full reflection
bool knownTypesOnly = true;
for (int count = 0; count < namespaceMaps.Length;)
{
NamespaceMapEntry namespaceMap = namespaceMaps[count];
if (null != namespaceMap)
{
Type objectType = GetObjectType(namespaceMap, localName, knownTypesOnly);
if (null != objectType)
{
// A non-public type is never allowable, except for internal types
// in local or friend assemblies, so catch it here.
if (!ReflectionHelper.IsPublicType(objectType))
{
#if PBTCOMPILER
// Don't allow internal known types in case we have any.
if (knownTypesOnly ||
!ReflectionHelper.IsInternalType(objectType) ||
!IsInternalAllowedOnType(namespaceMap))
#else
// Give Full Trust callers a chance to resolve legitimate internal types.
// This can be used by tools like designers and localizers running in FT.
if (!IsInternalTypeAllowedInFullTrust(objectType))
#endif
{
ThrowException(SRID.ParserPublicType, objectType.Name);
}
}
// Create new data structure to store information for the current type
typeAndSerializer = new TypeAndSerializer();
typeAndSerializer.ObjectType = objectType;
break;
}
}
count++;
if (knownTypesOnly && (count == namespaceMaps.Length))
{
// Reset for second pass
knownTypesOnly = false;
count = 0;
}
}
}
return typeAndSerializer;
}
/// <summary>
/// Return the Type that corresponds to a localName within a given clr namespace
/// in a given assembly
/// </summary>
/// <param name="namespaceMap">Specifies the CLR namespace and Assembly to look in</param>
/// <param name="localName">The name of the type</param>
/// <param name="knownTypesOnly">Search only known types</param>
/// <returns>Type of object that corresponds to localName</returns>
private Type GetObjectType(
NamespaceMapEntry namespaceMap,
string localName,
bool knownTypesOnly)
{
Debug.Assert(namespaceMap.ClrNamespace != null,"Null CLR Namespace");
Debug.Assert(localName != null,"Null localName");
Type type = null;
// Construct the full type name by concatenating the clr namespace and the local name
if (knownTypesOnly)
{
short typeID = BamlMapTable.GetKnownTypeIdFromName(namespaceMap.AssemblyName, namespaceMap.ClrNamespace, localName);
if (typeID != 0)
{
type = BamlMapTable.GetKnownTypeFromId(typeID);
}
}
else
{
Assembly assembly ;
#if PBTCOMPILER
try
{
#endif
// This may not work if the assembly is not present at compile time, so allow for that.
// At runtime it had better be there, so don't ignore it.
assembly = namespaceMap.Assembly;
#if PBTCOMPILER
}
catch (FileNotFoundException)
{
assembly = null;
}
#endif
if (null != assembly)
{
// Type loads may fail if all the prerequisite assemblies haven't been loaded
// yet. In this case, try one more time after loaded all assemblies that the
// compiler may have told the XamlTypeMapper about.
string fullTypeName = namespaceMap.ClrNamespace + "." + localName;
try
{
type = assembly.GetType(fullTypeName);
}
catch (Exception e)
{
if (CriticalExceptions.IsCriticalException(e))
{
throw;
}
else
{
if (LoadReferenceAssemblies())
{
try
{
type = assembly.GetType(fullTypeName);
}
catch (ArgumentException)
{
// A null type is allowable, and the caller will catch it
type = null;
}
}
}
}
}
}
return type;
}
internal int GetCustomBamlSerializerIdForType(Type objectType)
{
// support for xaml -> custom binary and custom binary -> object.
if (objectType == KnownTypes.Types[(int)KnownElements.Brush])
{
return (int)KnownElements.XamlBrushSerializer;
}
else if (objectType == KnownTypes.Types[(int)KnownElements.Geometry] ||
objectType == KnownTypes.Types[(int)KnownElements.StreamGeometry])
{
//
// The only type of geometry that can be serialized to a string is
// a StreamGeometry, so if objectType is Geometry and we're getting here
// then the attribute must in fact be a StreamGeometry.
//
return (int)KnownElements.XamlPathDataSerializer;
}
else if (objectType == KnownTypes.Types[(int)KnownElements.Point3DCollection])
{
return (int)KnownElements.XamlPoint3DCollectionSerializer;
}
else if (objectType == KnownTypes.Types[(int)KnownElements.Vector3DCollection])
{
return (int)KnownElements.XamlVector3DCollectionSerializer;
}
else if (objectType == KnownTypes.Types[(int)KnownElements.PointCollection])
{
return (int)KnownElements.XamlPointCollectionSerializer;
}
else if (objectType == KnownTypes.Types[(int)KnownElements.Int32Collection])
{
return (int)KnownElements.XamlInt32CollectionSerializer;
}
return 0;
}
/// <summary>
/// Sees if type has a Xaml serializer attribute that gives the
/// type name of the serializer and figure out the type.
/// </summary>
internal Type GetXamlSerializerForType(Type objectType)
{
// support for xaml -> baml and baml -> objects
if (objectType == KnownTypes.Types[(int)KnownElements.Style])
{
return typeof(XamlStyleSerializer);
}
else if (KnownTypes.Types[(int)KnownElements.FrameworkTemplate].IsAssignableFrom(objectType))
{
return typeof(XamlTemplateSerializer);
}
return null;
}
#if !PBTCOMPILER
internal static Type GetInternalTypeHelperTypeFromAssembly(ParserContext pc)
{
Assembly a = pc.StreamCreatedAssembly;
if (a == null)
{
return null;
}
Type ithType = a.GetType(GeneratedNamespace + "." + GeneratedInternalTypeHelperClassName);
if (ithType == null)
{
// if GITH is not found, try to see if a root namespace was implicitly added to it.
// This would be the case for assemblies built with VB that had a RootNamespace
// property specified in the project file.
RootNamespaceAttribute rnsa = (RootNamespaceAttribute)Attribute.GetCustomAttribute(a, typeof(RootNamespaceAttribute));
if (rnsa != null)
{
string rootNamespace = rnsa.Namespace;
ithType = a.GetType(rootNamespace + "." + GeneratedNamespace + "." + GeneratedInternalTypeHelperClassName);
}
}
return ithType;
}
private static InternalTypeHelper GetInternalTypeHelperFromAssembly(ParserContext pc)
{
InternalTypeHelper ith = null;
Type ithType = GetInternalTypeHelperTypeFromAssembly(pc);
if (ithType != null)
{
ith = (InternalTypeHelper)Activator.CreateInstance(ithType);
}
return ith;
}
internal static object CreateInternalInstance(ParserContext pc, Type type)
{
object instance = Activator.CreateInstance(type,
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.CreateInstance,
null,
null,
TypeConverterHelper.InvariantEnglishUS);
return instance;
}
internal static object GetInternalPropertyValue(ParserContext pc, object rootElement, PropertyInfo pi, object target)
{
object propValue = null;
bool isPublicProperty = false;
bool allowProtected = (rootElement is IComponentConnector) && (rootElement == target);
bool isAllowedProperty = IsAllowedPropertyGet(pi, allowProtected, out isPublicProperty);
if (isAllowedProperty)
{
propValue = pi.GetValue(target, BindingFlags.Default, null, null, TypeConverterHelper.InvariantEnglishUS);
}
return propValue;
}
internal static bool SetInternalPropertyValue(ParserContext pc, object rootElement, PropertyInfo pi, object target, object value)
{
bool isPublicProperty = false;
bool allowProtected = (rootElement is IComponentConnector) && (rootElement == target);
bool isAllowedProperty = IsAllowedPropertySet(pi, allowProtected, out isPublicProperty);
if (isAllowedProperty)
{
pi.SetValue(target, value, BindingFlags.Default, null, null, TypeConverterHelper.InvariantEnglishUS);
return true;
}
return false;
}
internal static Delegate CreateDelegate(ParserContext pc, Type delegateType, object target, string handler)
{
Delegate d = null;
bool isAllowedDelegateType = ReflectionHelper.IsPublicType(delegateType) || ReflectionHelper.IsInternalType(delegateType);
if (isAllowedDelegateType)
{
d = Delegate.CreateDelegate(delegateType, target, handler);
}
return d;
}
internal static bool AddInternalEventHandler(ParserContext pc, object rootElement, EventInfo eventInfo, object target, Delegate handler)
{
bool isPublicEvent = false;
bool allowProtected = rootElement == target;
bool isAllowedEvent = IsAllowedEvent(eventInfo, allowProtected, out isPublicEvent);
if (isAllowedEvent)
{
eventInfo.AddEventHandler(target, handler);
return true;
}
return false;
}
#endif
// Return true if this is a locally compiled assembly
internal bool IsLocalAssembly(string namespaceUri)
{
bool localAssembly = false;
#if PBTCOMPILER
NamespaceMapEntry[] namespaceMaps = GetNamespaceMapEntries(namespaceUri);
localAssembly = (namespaceMaps != null && namespaceMaps.Length == 1 && namespaceMaps[0].LocalAssembly);
#endif
return localAssembly;
}
/// <summary>
/// Given a string of the format MyNs:MyButton return the type that it refers to. This uses
/// the XmlnsDictionary in the passed parse context to resolve prefixes on the
/// type names
/// </summary>
internal Type GetTypeFromBaseString(
string typeString,
ParserContext context,
bool throwOnError)
{
string xmlns = string.Empty;
Type keyObject = null;
// Check if the typeString is of the form xmlns:type. If so, get
// the appropriate mapped NamespaceURI. If not, use the default URI
int colonIndex = typeString.IndexOf(':');
if (colonIndex == -1)
{
xmlns = context.XmlnsDictionary[string.Empty];
if (xmlns == null)
{
ThrowException(SRID.ParserUndeclaredNS, string.Empty);
}
}
else
{
string prefix = typeString.Substring(0, colonIndex);
xmlns = context.XmlnsDictionary[prefix];
if (xmlns == null)
{
ThrowException(SRID.ParserUndeclaredNS, prefix);
}
else
{
typeString = typeString.Substring(colonIndex + 1);
}
}
#if !PBTCOMPILER
// Optimize for SystemMetric types that are very frequently used.
if (string.CompareOrdinal(xmlns, XamlReaderHelper.DefaultNamespaceURI) == 0)
{
switch (typeString)
{
case "SystemParameters":
keyObject = typeof(SystemParameters);
break;
case "SystemColors":
keyObject = typeof(SystemColors);
break;
case "SystemFonts":
keyObject = typeof(SystemFonts);
break;
}
}
#endif
if (keyObject == null)
{
keyObject = GetType(xmlns, typeString);
}
if (keyObject == null && throwOnError)
{
// if local type, then don't throw as it may be resolved in pass2.
// it is upto the caller who has context about compilation passes
// to throw as appropriate in Pass2 if the type is still not found.
if (!IsLocalAssembly(xmlns))
{
_lineNumber = context != null ? context.LineNumber : 0;
_linePosition = context != null ? context.LinePosition : 0;
ThrowException(SRID.ParserResourceKeyType, typeString);
}
}
return keyObject;
}
#if PBTCOMPILER
internal Type GetTypeArgsType(
string typeString,
ParserContext context,
out string localTypeArgClassName,
out string localTypeArgNamespace)
{
Type t = null;
localTypeArgClassName = string.Empty;
localTypeArgNamespace = string.Empty;
// Check if the typeString is of the form xmlns:type. If so, get
// the appropriate mapped NamespaceURI. If not, use the default URI
int colonIndex = typeString.IndexOf(':');
if (colonIndex == -1)
{
string xmlns = context.XmlnsDictionary[string.Empty];
if (xmlns == null)
{
ThrowException(SRID.ParserUndeclaredNS, string.Empty);
}
else
{
t = GetType(xmlns, typeString);
}
}
else
{
string prefix = typeString.Substring(0, colonIndex);
string xmlns = context.XmlnsDictionary[prefix];
if (xmlns == null)
{
ThrowException(SRID.ParserUndeclaredNS, prefix);
}
else
{
NamespaceMapEntry[] namespaceMaps = GetNamespaceMapEntries(xmlns);
typeString = typeString.Substring(colonIndex + 1);
bool isLocalArg = namespaceMaps != null &&
namespaceMaps.Length == 1 &&
namespaceMaps[0].LocalAssembly;
if (isLocalArg)
{
localTypeArgNamespace = namespaceMaps[0].ClrNamespace;
localTypeArgClassName = typeString;
}
else
{
t = GetType(xmlns, typeString);
}
}
}
return t;
}
#endif
/// <summary>
/// Helper method given a type returns the Cached information for the type. If there
/// is no existing cached information for that type, a new cache object is created
/// and added to the cache.
/// </summary>
private TypeInformationCacheData GetCachedInformationForType(Type type)
{
TypeInformationCacheData typeInformationCacheData;
typeInformationCacheData = _typeInformationCache[type] as TypeInformationCacheData;
if (null == typeInformationCacheData)
{
typeInformationCacheData = new TypeInformationCacheData(type.BaseType);
typeInformationCacheData.ClrNamespace = type.Namespace;
_typeInformationCache[type] = typeInformationCacheData;
}
return typeInformationCacheData;
}
#if !PBTCOMPILER
/// <summary>
/// Returns the type's BaseType. This is cached because the .net Type.BaseType()
/// call is expensive.
/// </summary>
private Type GetCachedBaseType(Type t)
{
TypeInformationCacheData typeInformation = GetCachedInformationForType(t);
return typeInformation.BaseType;
}
/***************************************************************************\
*
* XamlTypeMapper.ProcessNameString
*
* Given a name in markup, extract and process the prefix if any.
*
\***************************************************************************/
internal static string ProcessNameString(ParserContext parserContext, ref string nameString)
{
// For certain parts of the styling markup, a property is specified as an
// attribute value. This may include the namespace specification. Normally
// when we encounter this in an attribute the XML parser processes the name-
// space for us. But when it's the value we'll have to deal with it our-
// selves. Look for the namespace specifier and extract it for namespace lookup.
// "foons:BarClass.BazProp" -> "http://www.example.com" + "BarClass.BazProp"
// The colon is what we look for to determine if there's a namespace prefix specifier.
int nsIndex = nameString.IndexOf(':');
string nsPrefix = string.Empty;
if( nsIndex != -1 )
{
// Found a namespace prefix separator, so create replacement propertyName.
// String processing - split "foons" from "BarClass.BazProp"
nsPrefix = nameString.Substring (0, nsIndex);
nameString = nameString.Substring (nsIndex + 1);
}
// Find the namespace, even if its the default one
string namespaceURI = parserContext.XmlnsDictionary[nsPrefix];
if (namespaceURI == null)
{
parserContext.XamlTypeMapper.ThrowException(SRID.ParserPrefixNSProperty, nsPrefix, nameString);
}
return namespaceURI;
}
/***************************************************************************\
*
* XamlTypeMapper.ParsePropertyName
*
* Given a property name, find the associated DependencyProperty and return it.
*
\***************************************************************************/
internal static DependencyProperty ParsePropertyName(
ParserContext parserContext,
string propertyName,
ref Type ownerType)
{
string namespaceURI = ProcessNameString(parserContext, ref propertyName);
DependencyProperty dp = parserContext.XamlTypeMapper.DependencyPropertyFromName(
propertyName,
namespaceURI,
ref ownerType);
return dp;
}
/***************************************************************************\
*
* XamlTypeMapper.ParseEventName
*
* Given an event name, find the associated RoutedEvent and return it.
*
\***************************************************************************/
internal static RoutedEvent ParseEventName(
ParserContext parserContext,
string eventName,
Type ownerType)
{
string namespaceURI = ProcessNameString(parserContext, ref eventName);
RoutedEvent Event = parserContext.XamlTypeMapper.GetRoutedEvent(
ownerType, namespaceURI, eventName);
return Event;
}
#endif
/// <summary>
/// Return an object of the passed type.
/// </summary>
/// <remarks>
/// If the type is a KnownElement (which it likely will be) it is faster
/// to create it using the KnownTypes hardcoded constructors, so check that
/// first before using the Activator.CreateInstance fallback.
/// </remarks>
internal object CreateInstance(Type t)
{
object o = null;
#if !PBTCOMPILER
short typeId = BamlMapTable.GetKnownTypeIdFromType(t);
if (typeId < 0)
{
o = MapTable.CreateKnownTypeFromId(typeId);
}
else
{
#endif
o = Activator.CreateInstance(t,
BindingFlags.Instance | BindingFlags.CreateInstance | BindingFlags.Public,
null,
null,
TypeConverterHelper.InvariantEnglishUS);
#if !PBTCOMPILER
}
#endif
return o;
}
#endregion Types
#region Namespaces
// Return true if the passed namespace is known, meaning that it maps
// to a set of assemblies and clr namespaces
internal bool IsXmlNamespaceKnown(
string xmlNamespace,
out string newXmlNamespace)
{
bool result;
// if the namespace is empty, then there's no need to do all the extra work associated with getting the
// namespace map entries. Just return false.
if (String.IsNullOrEmpty(xmlNamespace))
{
result = false;
newXmlNamespace = null;
}
else
{
NamespaceMapEntry[] namespaceMaps = GetNamespaceMapEntries(xmlNamespace);
if (_xmlnsCache == null)
{
#if PBTCOMPILER
Debug.Assert(false, "Should initialize cache prior to compiling");
#else
_xmlnsCache = new XmlnsCache();
#endif
}
newXmlNamespace = _xmlnsCache.GetNewXmlnamespace(xmlNamespace);
// if the xmlNamespace has valid entries or is mapped to another namespace, then it is known.
result = (namespaceMaps != null && namespaceMaps.Length > 0) ||
!String.IsNullOrEmpty(newXmlNamespace);
}
return result; // return variable isn't needed, just makes debugging easier.
}
#if !PBTCOMPILER
//
// Pass xmlNamespace to AssemblyList mapping to xmlnsCache so that the xmlnsCache
// can take the assembly list to get the right xmlns->clrns mapping later.
//
internal void SetUriToAssemblyNameMapping(string xmlNamespace, short[] assemblyIds)
{
//
// If the xmlNamespace is for a mapping, there is no need to ask for xmlnsCache
// to get xmlns->clrns mapping.
//
if (xmlNamespace.StartsWith(XamlReaderHelper.MappingProtocol, StringComparison.Ordinal))
{
return;
}
if (_xmlnsCache == null)
{
_xmlnsCache = new XmlnsCache();
}
string[] asmNameList = null;
if (assemblyIds != null && assemblyIds.Length > 0)
{
asmNameList = new string[assemblyIds.Length];
for (int i = 0; i < assemblyIds.Length; i++)
{
BamlAssemblyInfoRecord assemblyInfo = MapTable.GetAssemblyInfoFromId(assemblyIds[i]);
asmNameList[i] = assemblyInfo.AssemblyFullName;
}
}
_xmlnsCache.SetUriToAssemblyNameMapping(xmlNamespace, asmNameList);
}
#endif
///<summary>
/// Returns a NamespaceMapEntry array given a xmlNamespace. Each
/// NamespaceMapEntry contains information the XamlTypeMapper uses for Mapping between an xml
/// XmlNamespace and what Assembly, Namespace to look in.
///</summary>
///<param name="xmlNamespace">
/// The xmlNamespace for the Map
///</param>
///<returns>
/// Returns an Array of NamespaceMapEntry
///</returns>
internal NamespaceMapEntry[] GetNamespaceMapEntries(string xmlNamespace)
{
NamespaceMapEntry[] namespaceMaps = null;
// check out hash and if already have resolved the Uri
// don't resolve again.
namespaceMaps = _namespaceMapHashList[xmlNamespace] as NamespaceMapEntry[];
if (null == namespaceMaps)
{
ArrayList namespaceMapArray = new ArrayList(6);
// this is the first time the XmlNamespace has been requested
// add items from the namespaceMap and then walk the assembly
// list to find matching items.
if (null != _namespaceMaps)
{
// need to find out the total number of entries by asking each hash
// review, may be better to sort these firt time through
// assumption here that the namespaceMap entries are small.
for (int i = 0; i < _namespaceMaps.Length; i++)
{
NamespaceMapEntry namespaceMap = _namespaceMaps[i];
if (namespaceMap.XmlNamespace == xmlNamespace)
{
namespaceMapArray.Add(namespaceMap);
}
}
}
List<ClrNamespaceAssemblyPair> namespaceAssemblyPair;
// Check for Processing instructions for mapping. If that fails,
// check for Xmlns definition files.
if (PITable.Contains(xmlNamespace))
{
namespaceAssemblyPair = new List<ClrNamespaceAssemblyPair>(1);
namespaceAssemblyPair.Add((ClrNamespaceAssemblyPair)PITable[xmlNamespace]);
}
else
{
namespaceAssemblyPair = GetClrNamespacePairFromCache(xmlNamespace);
}
// now walk through any using statements we got and add them
if (null != namespaceAssemblyPair)
{
for (int j = 0; j < namespaceAssemblyPair.Count; j++)
{
ClrNamespaceAssemblyPair mapping = namespaceAssemblyPair[j];
string usingAssemblyName = null;
string path = AssemblyPathFor(mapping.AssemblyName);
// using could either have an assembly or not, if it does
// have an assembly just need to add this one entry, if
// no assembly map in the referenced assemblies.
if (
#if PBTCOMPILER
mapping.LocalAssembly ||
#endif
(!(String.IsNullOrEmpty(mapping.AssemblyName)) && !(String.IsNullOrEmpty(mapping.ClrNamespace))) )
{
usingAssemblyName = mapping.AssemblyName;
NamespaceMapEntry nsMap = new NamespaceMapEntry(xmlNamespace,
usingAssemblyName,mapping.ClrNamespace,path);
#if PBTCOMPILER
nsMap.LocalAssembly = mapping.LocalAssembly;
// if xaml has local components, then it could have internals
// but there is no way to determine this until pass2. But we
// need to set this here in order to generate the InternalTypeHelper
// in pass1.
if (nsMap.LocalAssembly)
{
_hasLocalReference = true;
}
#endif
namespaceMapArray.Add(nsMap);
}
if (!String.IsNullOrEmpty(mapping.ClrNamespace))
{
// Also add in any assembly from the AssemblyNames collection
for (int k = 0; k < _assemblyNames.Length; k++)
{
if (usingAssemblyName == null)
{
namespaceMapArray.Add(new NamespaceMapEntry(xmlNamespace,
_assemblyNames[k],
mapping.ClrNamespace,
path));
}
else
{
// If we have a using Assembly, then only add assemblies from
// AssemblyNames that match the using Assembly.
int charIndex = _assemblyNames[k].LastIndexOf('\\');
if (charIndex > 0 &&
_assemblyNames[k].Substring(charIndex + 1) == usingAssemblyName)
{
namespaceMapArray.Add(new NamespaceMapEntry(xmlNamespace,
_assemblyNames[k],
mapping.ClrNamespace,
path));
}
}
}
}
}
}
// convert to a namespaceMap
namespaceMaps = (NamespaceMapEntry[]) namespaceMapArray.ToArray(typeof(NamespaceMapEntry));
// add to hash even if not items so we don't do this work again.
if (null != namespaceMaps)
{
_namespaceMapHashList.Add(xmlNamespace,namespaceMaps);
}
}
return namespaceMaps;
}
#if PBTCOMPILER
/// <summary>
/// Invalide the namespace mapping cache associated with a namespace. This should be done
/// when the PITable has been changed and the mapping cache might have been built for the
/// namespace already.
/// </summary>
/// <param name="xmlNamespace">The namespace to for whose cache to invalidate</param>
internal void InvalidateMappingCache(string xmlNamespace)
{
_namespaceMapHashList.Remove(xmlNamespace);
}
/// <summary>
/// Set up the XmlnsCache use for resolving namespaces to use only the assembly path
/// table that has been built up by the XamlTypeMapper.
/// </summary>
internal void InitializeReferenceXmlnsCache()
{
_xmlnsCache = new XmlnsCache(_assemblyPathTable);
}
#else
// Get the xml namespace from the _piReverseTable that corresponds to the
// passed type full name and assembly name
internal string GetXmlNamespace(
string clrNamespaceFullName,
string assemblyFullName)
{
string upperAssemblyName = assemblyFullName.ToUpper(
TypeConverterHelper.InvariantEnglishUS);
String fullName = clrNamespaceFullName + "#" + upperAssemblyName;
String ret;
if (_piReverseTable.TryGetValue(fullName, out ret) && ret != null)
{
return ret;
}
else
{
return string.Empty;
}
}
/// <summary>
/// Given a Type returns it's .net Namespace. This is cached because each call
/// to .urtNamspace allocates a string.
/// </summary>
private string GetCachedNamespace(Type t)
{
TypeInformationCacheData typeInformation = GetCachedInformationForType(t);
return typeInformation.ClrNamespace;
}
#endif
/// <summary>
/// Check an Xml namespace URI and loads the associated Clr namespaces and assemblies
/// into ClrNamespaceAssemblyPair structures.
/// Throws an exception if no valid namespaces are found.
/// </summary>
/// <param name="namespaceUri">Xml namespace that maps to one or more Clr namespace
/// and assembly pairs</param>
/// <returns>array of ClrNamespaceAssemblyPair structures</returns>
internal static List<ClrNamespaceAssemblyPair> GetClrNamespacePairFromCache(
string namespaceUri)
{
List<ClrNamespaceAssemblyPair> mappingArray = null;
if (_xmlnsCache == null)
{
#if PBTCOMPILER
Debug.Assert(false, "Should initialize cache prior to compiling");
#else
_xmlnsCache = new XmlnsCache();
#endif
}
mappingArray = _xmlnsCache.GetMappingArray(namespaceUri);
return mappingArray;
}
#endregion Namespaces
#region TypeConverters
// Returns the Type of the TypeConverter for the given type.
// Returns null if not found.
internal Type GetTypeConverterType(Type type)
{
Debug.Assert(null != type, "Null passed for type to GetTypeConverterType");
TypeInformationCacheData typeData = GetCachedInformationForType(type) as TypeInformationCacheData;
Type converterType = null;
if (null != typeData.TypeConverterType)
{
converterType = typeData.TypeConverterType;
return converterType;
}
// Check for known TypeConverters first. These are always public.
converterType = MapTable.GetKnownConverterTypeFromType(type);
if (converterType == null)
{
// If not found, next try looking for the TypeConverter for the type using reflection.
converterType = TypeConverterHelper.GetConverterType(type);
if (converterType == null)
{
converterType = TypeConverterHelper.GetCoreConverterTypeFromCustomType(type);
}
}
typeData.TypeConverterType = converterType;
return converterType;
}
#if !PBTCOMPILER
// Returns the TypeConverter for the given type
// Throws a XamlParseException if no TypeConverter is found.
internal TypeConverter GetTypeConverter(Type type)
{
Debug.Assert(null != type, "Null passed for type to GetTypeConverter");
TypeInformationCacheData typeData = GetCachedInformationForType(type) as TypeInformationCacheData;
TypeConverter typeConverter = null;
// if the TypeConverter for this type was ever successfully
// queried before it should have a non-null value.
if (null != typeData.Converter)
{
typeConverter = typeData.Converter;
return typeConverter;
}
// Check for known TypeConverters first. These are always public.
typeConverter = MapTable.GetKnownConverterFromType(type);
if (typeConverter == null)
{
// If not found, next try looking for the TypeConverter for the type using reflection.
Type converterType = TypeConverterHelper.GetConverterType(type);
if (converterType == null)
{
typeConverter = TypeConverterHelper.GetCoreConverterFromCustomType(type);
}
else
{
typeConverter = CreateInstance(converterType) as TypeConverter;
}
}
typeData.Converter = typeConverter;
if (null == typeConverter)
{
ThrowException(SRID.ParserNoTypeConv, type.Name);
}
return typeConverter;
}
#endif
// Returns the Type of the TypeConverter applied to the given property itself.
// Returns null if not found.
internal Type GetPropertyConverterType(Type propType, object dpOrPiOrMi)
{
Debug.Assert(null != propType, "Null passed for propType to GetPropertyConverterType");
Type converterType = null;
// If the current value being parsed is a property value then we must look
// if there is special TypeConverter specified as attribute for this property
if (null != dpOrPiOrMi)
{
#if PBTCOMPILER
TypeInformationCacheData typeData = GetCachedInformationForType(propType) as TypeInformationCacheData;
object ret = typeData.PropertyConverters[dpOrPiOrMi];
if (null != ret)
{
converterType = (Type)ret;
return converterType;
}
else
#endif
{
// Get the memberInfo from the DP, PropertyInfo(CLR) or MethodInfo(Attached) for the property
MemberInfo memberInfo = TypeConverterHelper.GetMemberInfoForPropertyConverter(dpOrPiOrMi);
if (memberInfo != null)
{
// If not found, next try looking for the TypeConverter on the property itself using reflection.
converterType = TypeConverterHelper.GetConverterType(memberInfo);
}
}
#if PBTCOMPILER
// Cache the per property TypeConverter type. This doesn't need to be cached at run-time
// since GetPropertyConverter will be used for getting the actual TypeConveretr instance.
// This saves us the cost of a HashTable.
typeData.SetPropertyConverter(dpOrPiOrMi, converterType);
#endif
}
return converterType;
}
#if !PBTCOMPILER
// Returns the TypeConverter applied to the given property iself.
// If not found returns the TypeConverter applied to the given property's type.
// Throws a XamlParseException if no TypeConverter is found.
internal TypeConverter GetPropertyConverter(Type propType, object dpOrPiOrMi)
{
Debug.Assert(null != propType, "Null passed for propType to GetPropertyConverter");
TypeConverter typeConverter = null;
TypeInformationCacheData typeData = GetCachedInformationForType(propType) as TypeInformationCacheData;
// If the current value being parsed is a property value then we must look
// if there is special TypeConverter specified as attribute for this property
if (null != dpOrPiOrMi)
{
object ret = typeData.PropertyConverters[dpOrPiOrMi];
if (null != ret)
{
typeConverter = (TypeConverter)ret;
return typeConverter;
}
// Get the memberInfo from the DP, PropertyInfo(CLR) or MethodInfo(Attached) for the property
MemberInfo memberInfo = TypeConverterHelper.GetMemberInfoForPropertyConverter(dpOrPiOrMi);
if (memberInfo != null)
{
// If not found, next try looking for the TypeConverter on the property itself using reflection.
Type converterType = TypeConverterHelper.GetConverterType(memberInfo);
if (converterType != null)
{
// create an instance of the TypeConverter if found
typeConverter = CreateInstance(converterType) as TypeConverter;
}
}
}
// If no TypeConverter is found on the property itself, try to find it based on the property's type
if (typeConverter == null)
{
typeConverter = GetTypeConverter(propType);
}
// Cache the per property TypeConverter
if (dpOrPiOrMi != null)
typeData.SetPropertyConverter(dpOrPiOrMi, typeConverter);
return typeConverter;
}
#endif
#endregion TypeConverters
#region Resources
/// <summary>
/// Given a string, return a key to be used in a dictionary relating to this string.
/// If the string is a simple string, just return that. If the string represents a
/// Typeof declaration, then return the Type that maps to that string.
/// Note that this can return null if the key is not resolved. It is up to the caller
/// to throw the appropriate error message in that case.
/// </summary>
internal object GetDictionaryKey(string keyString, ParserContext context)
{
if (keyString.Length > 0 &&
(Char.IsWhiteSpace(keyString[0]) ||
Char.IsWhiteSpace(keyString[keyString.Length-1])))
{
keyString = keyString.Trim();
}
return keyString;
}
#endregion Resources
#if !PBTCOMPILER
#region ConstructorInfos
/// <summary>
/// Fetches the cached ConstructorInfos if there exists one or
/// then creates a new one and caches it for later.
/// </summary>
internal ConstructorData GetConstructors(Type type)
{
// Create a cache if it does not already exist
if (_constructorInformationCache == null)
{
_constructorInformationCache = new HybridDictionary(3);
}
// Add an entry for the current type if it does not already exist
if (!_constructorInformationCache.Contains(type))
{
_constructorInformationCache[type] = new ConstructorData(type.GetConstructors(BindingFlags.Public | BindingFlags.Instance));
}
// Return the cached value
return (ConstructorData)_constructorInformationCache[type];
}
/// <summary>
/// Helper class that is used to store constructor information for a type
/// </summary>
internal class ConstructorData
{
#region Constructors
internal ConstructorData(ConstructorInfo[] constructors)
{
_constructors = constructors;
}
#endregion Constructors
#region Methods
/// <summary>
/// Fetches the cached ParameterInfos if there exists one or
/// then creates a new one and caches it for later.
/// </summary>
internal ParameterInfo[] GetParameters(int constructorIndex)
{
// Create a parameters Cache if it does not already exist
if (_parameters == null)
{
Debug.Assert(_constructors != null, "This operation is legal only after the constructors have been fetched");
_parameters = new ParameterInfo[_constructors.Length][];
}
// Add an entry for the current constructor if it does not already exist
if (_parameters[constructorIndex] == null)
{
_parameters[constructorIndex] = _constructors[constructorIndex].GetParameters();
}
// Return the cached value
return _parameters[constructorIndex];
}
#endregion Methods
#region Properties
internal ConstructorInfo[] Constructors
{
get { return _constructors; }
}
#endregion Properties
#region Data
private ConstructorInfo[] _constructors;
private ParameterInfo[][] _parameters;
#endregion Data
}
#endregion ConstructorInfos
#endif
#region TrimSurroundingWhitespace
/// <summary>
/// Returns the Cached TrimSurroundingWhitespace for the associated type
/// We cache this because the reflection lookup on the attribute
/// is slow.
/// </summary>
/// <param name="t">type to return the TrimSurroundingWhitespaceAttribute for</param>
/// <returns>The TrimSurroundingWhitespace value for t</returns>
internal bool GetCachedTrimSurroundingWhitespace(Type t)
{
TypeInformationCacheData typeInformation = GetCachedInformationForType(t);
// if first time asked for the layout Type get it.
if (!typeInformation.TrimSurroundingWhitespaceSet)
{
typeInformation.TrimSurroundingWhitespace = GetTrimSurroundingWhitespace(t);
typeInformation.TrimSurroundingWhitespaceSet = true;
}
return typeInformation.TrimSurroundingWhitespace;
}
/// <summary>
/// Helper function for use to find out the TrimSurroundingWhitespace
/// associated with a Type.
/// </summary>
private bool GetTrimSurroundingWhitespace(Type type)
{
Debug.Assert(null != type, "null value for type passed to GetWhitespace");
// in retail return default.
if (null != type)
{
#if !PBTCOMPILER
TrimSurroundingWhitespaceAttribute[] trimAttribute =
type.GetCustomAttributes(typeof(TrimSurroundingWhitespaceAttribute),true )
as TrimSurroundingWhitespaceAttribute[];
if (trimAttribute.Length > 0)
{
Debug.Assert(1 == trimAttribute.Length,"More than one TrimWhitespace Attribute");
return true;
}
#else
// Reflecting for attributes doesn't work on asmmeta files, so
// we have to hard code known layout types here. This is very
// fragile, but we'll fix it in M8.2. - It's end of M11 already though...
if (KnownTypes.Types[(int)KnownElements.LineBreak].IsAssignableFrom(type))
{
return true;
}
#endif
}
return false;
}
#endregion TrimSurroundingWhitespace
#region Exceptions
//
// ThrowException wrappers for 0-3 parameter SRIDs
//
private void ThrowException(string id)
{
ThrowExceptionWithLine(SR.Get(id), null);
}
internal void ThrowException(string id, string parameter)
{
ThrowExceptionWithLine(SR.Get(id, parameter), null);
}
private void ThrowException(string id, string parameter1, string parameter2)
{
ThrowExceptionWithLine(SR.Get(id, parameter1, parameter2), null);
}
private void ThrowException(string id, string parameter1, string parameter2, string parameter3)
{
ThrowExceptionWithLine(SR.Get(id, parameter1, parameter2, parameter3), null);
}
//
// ThrowException wrapper that just adds the line number & position.
//
internal void ThrowExceptionWithLine(string message, Exception innerException)
{
XamlParseException.ThrowException(message, innerException, _lineNumber, _linePosition);
}
#endregion Exceptions
#region Properties
/// <summary>
/// Hashtable where key is the xmlNamespace, and value is the
/// ClrNamespaceAssemblyPair structure containing clrNamespace and assembly
/// </summary>
internal HybridDictionary PITable
{
get { return _piTable; }
}
/// <summary>
/// This is the associated BamlMapTable that contains information about what is
/// in a baml stream. The XamlTypeMapper uses the map table (if present) as a cache
/// to store some assembly, type and property information. If it is not present
/// then this information is not cached and must be retrieved for every request.
/// </summary>
internal BamlMapTable MapTable
{
get { return _mapTable; }
set { _mapTable = value; }
}
/// <summary>
/// Line number used for error reporting
/// </summary>
internal int LineNumber
{
set { _lineNumber = value; }
}
/// <summary>
/// Line position used for error reporting
/// </summary>
internal int LinePosition
{
set { _linePosition = value; }
}
#if !PBTCOMPILER
/// <summary>
/// Return the hashtable that is keyed by xml namespace uri and
/// has values that are collection of NamespaceMapEntry objects for that
/// xml namespace.
/// </summary>
internal Hashtable NamespaceMapHashList
{
get { return _namespaceMapHashList; }
}
internal System.Xaml.XamlSchemaContext SchemaContext
{
get
{
if (_schemaContext == null)
{
_schemaContext = new XamlTypeMapperSchemaContext(this);
}
return _schemaContext;
}
}
#else
// true if the Type Mapper can allow protected attributes.
// This will be the case for a markup sub-classed root element only.
internal bool IsProtectedAttributeAllowed
{
get { return _isProtectedAttributeAllowed; }
set { _isProtectedAttributeAllowed = value; }
}
internal void ResetMapper()
{
_piTable.Clear();
_piReverseTable.Clear();
_lineNumber = 0;
_linePosition = 0;
_isProtectedAttributeAllowed = false;
NamespaceMapEntry[] defaultNsMaps = _namespaceMapHashList[XamlReaderHelper.DefaultNamespaceURI] as NamespaceMapEntry[];
NamespaceMapEntry[] definitionNsMaps = _namespaceMapHashList[XamlReaderHelper.DefinitionNamespaceURI] as NamespaceMapEntry[];
NamespaceMapEntry[] definitionMetroNsMaps = _namespaceMapHashList[XamlReaderHelper.DefinitionMetroNamespaceURI] as NamespaceMapEntry[];
_namespaceMapHashList.Clear();
if (null != defaultNsMaps)
{
_namespaceMapHashList.Add(XamlReaderHelper.DefaultNamespaceURI, defaultNsMaps);
}
if (null != definitionNsMaps)
{
_namespaceMapHashList.Add(XamlReaderHelper.DefinitionNamespaceURI, definitionNsMaps);
}
if (null != definitionMetroNsMaps)
{
_namespaceMapHashList.Add(XamlReaderHelper.DefinitionMetroNamespaceURI, definitionMetroNsMaps);
}
}
#endif
#endregion Properties
#region Data
// Class used for Type information data cache.
internal class TypeInformationCacheData
{
/// <summary>
/// Create a new instance of the type cache. Note that the type of this cached
/// data is not stored anywhere in this object. The type that this object pertains
/// to is stored as the key in the _typeInformationCache dictionary.
/// </summary>
internal TypeInformationCacheData(Type baseType)
{
_baseType = baseType;
}
/// <summary>
/// Urt Namespace for this type
/// </summary>
internal string ClrNamespace
{
#if !PBTCOMPILER
get { return _clrNamespace; }
#endif
set { _clrNamespace = value; }
}
#if !PBTCOMPILER
/// <summary>
/// The parent type in the inheritance hierarchy of this type. This is
/// stored here since BaseType lookups take some time.
/// </summary>
internal Type BaseType
{
get { return _baseType; }
}
/// <summary>
/// TypeConverter associted with this type, if there is one. This is stored
/// here so that GetTypeConverter does not need to be called as often.
/// </summary>
internal TypeConverter Converter
{
get { return _typeConverter; }
set { _typeConverter = value; }
}
#endif
// The type of the TypeConverter
internal Type TypeConverterType
{
get { return _typeConverterType; }
set { _typeConverterType = value; }
}
/// <summary>
/// TrimSurroundingWhitespace value for this type.
/// </summary>
internal bool TrimSurroundingWhitespace
{
get { return _trimSurroundingWhitespace; }
set { _trimSurroundingWhitespace = value; }
}
/// <summary>
/// Flag to indicate if we have cached the TrimSurroundingWhitespace
/// </summary>
internal bool TrimSurroundingWhitespaceSet
{
get { return _trimSurroundingWhitespaceSet; }
set { _trimSurroundingWhitespaceSet = value; }
}
/// <summary>
/// Get the DependencyProperty from the Hashtable of PropertyAndType
/// keyed by DependencyProperty name
/// </summary>
internal PropertyAndType GetPropertyAndType(string dpName)
{
if (_dpLookupHashtable == null)
{
_dpLookupHashtable = new Hashtable();
return null;
}
return _dpLookupHashtable[dpName] as PropertyAndType;
}
/// <summary>
/// Set a new PropertyAndType in the DependencyProperty information Hashtable.
/// </summary>
internal void SetPropertyAndType(
string dpName,
PropertyInfo dpInfo,
Type ownerType,
bool isInternal)
{
Debug.Assert(_dpLookupHashtable != null,
"GetPropertyAndType must always be called before SetPropertyAndType");
// add the type taking a lock
PropertyAndType pAndT = _dpLookupHashtable[dpName] as PropertyAndType;
if (pAndT == null)
{
_dpLookupHashtable[dpName] = new PropertyAndType(null, dpInfo, false, true, ownerType, isInternal);
}
else
{
pAndT.PropInfo = dpInfo;
pAndT.PropInfoSet = true;
pAndT.IsInternal = isInternal;
}
}
/// <summary>
/// TypeConverters based upon attributes on property
/// </summary>
internal HybridDictionary PropertyConverters
{
get
{
if (null == _propertyConverters)
{
_propertyConverters = new HybridDictionary();
}
return _propertyConverters;
}
}
/// <summary>
/// Set a new PropertyConverter for the given property.
/// NOTE: This method takes a lock on the table. So to set
/// values into the table you must use this method.
/// </summary>
internal void SetPropertyConverter(
object dpOrPi,
#if !PBTCOMPILER
TypeConverter converter)
#else
Type converter)
#endif
{
_propertyConverters[dpOrPi] = converter;
}
// Private data members
string _clrNamespace;
Type _baseType;
bool _trimSurroundingWhitespace;
Hashtable _dpLookupHashtable; // Hashtable of PropertyAndType keyed by dp name
HybridDictionary _propertyConverters = new HybridDictionary(); // Dictionary of TypeConverters keyed on dpOrPi
bool _trimSurroundingWhitespaceSet;
#if !PBTCOMPILER
TypeConverter _typeConverter;
#endif
Type _typeConverterType;
}
// DP setter method, PropertyInfo and Type record held in _dpLookupHashtable
internal class PropertyAndType
{
public PropertyAndType (MethodInfo dpSetter,
PropertyInfo dpInfo,
bool setterSet,
bool propInfoSet,
Type ot,
bool isInternal)
{
Setter = dpSetter;
PropInfo = dpInfo;
OwnerType = ot;
SetterSet = setterSet;
PropInfoSet = propInfoSet;
IsInternal = isInternal;
}
public PropertyInfo PropInfo;
public MethodInfo Setter;
public Type OwnerType;
public bool PropInfoSet;
public bool SetterSet;
public bool IsInternal;
}
// Constants that identify special types of string values
internal const string MarkupExtensionTypeString = "Type ";
internal const string MarkupExtensionStaticString = "Static ";
// internal const string MarkupExtensionNullString = "Null";
internal const string MarkupExtensionDynamicResourceString = "DynamicResource ";
// If the case or name of the assembly name changes in the Framework build,
// then the following will have to change also.
internal const string PresentationFrameworkDllName = "PresentationFramework";
// Namespace & classname of the generated helper class for accessing allowed internal types in PT.
internal const string GeneratedNamespace = "XamlGeneratedNamespace";
internal const string GeneratedInternalTypeHelperClassName = "GeneratedInternalTypeHelper";
internal const string MarkupExtensionTemplateBindingString = "TemplateBinding ";
#if PBTCOMPILER
private static bool _hasInternals = false;
private static bool _hasLocalReference = false;
private bool _isProtectedAttributeAllowed = false;
#endif
internal static Assembly AssemblyWB = null;
internal static Assembly AssemblyPC = null;
internal static Assembly AssemblyPF = null;
internal static void Clear()
{
#if PBTCOMPILER
_hasInternals = false;
_hasLocalReference = false;
#endif
AssemblyWB = null;
AssemblyPC = null;
AssemblyPF = null;
}
// Map table associated with this XamlTypeMapper. This contains information
// about what is stored in BAML. The XamlTypeMapper makes use of the caches in
// the BamlMapTable to store some assembly, type and property information.
BamlMapTable _mapTable;
// Array of assembly names that can be used when resolving clr namespaces
string[] _assemblyNames;
// array or namespace map entries such as `http:// mappings.
NamespaceMapEntry[] _namespaceMaps;
// HashTable of cached type lookups and the serializers for that type. These
// are always TypeAndSerializer objects
Hashtable _typeLookupFromXmlHashtable = new Hashtable();
// Hash table of mappings between xmlNamespace and mappings
Hashtable _namespaceMapHashList = new Hashtable();
// Hashtable where the key is the fullTypeName + '#' + propertyName and the value
HybridDictionary _typeInformationCache = new HybridDictionary();
#if !PBTCOMPILER
// Hashtable where the key is the type and the value is the set of constructors for that type
HybridDictionary _constructorInformationCache;
// A SchemaContext that respects the namespace mappings, PIs, and assembly paths
// passed in to this TypeMapper
private XamlTypeMapperSchemaContext _schemaContext;
#endif
// Hashtable where key is the xmlNamespace, and value is the
// ClrNamespaceAssemblyPair structure containing clrNamespace and assembly
HybridDictionary _piTable = new HybridDictionary();
// Hashtable where key is the clrNamespace + "#" + assemblyName and the
// value is the corresponding xmlNamespace. This is used for fast lookups
// of xmlnamespace if you know the assembly and clr namespace.
Dictionary<string, string> _piReverseTable = new Dictionary<string, string>();
// Hashtable where key is the assembly's short name that has been uppercased,
// and the value is a path where that assembly can be loaded from.
// Always lock on this object when writing to it
HybridDictionary _assemblyPathTable = new HybridDictionary();
// true if referenced assemblies in the _assemblyPathTable have been loaded
bool _referenceAssembliesLoaded = false;
// Line number and position in original Xaml file corresponding to the
// current BAML record.
int _lineNumber = 0;
int _linePosition = 0;
// Cache of namespace and assemblies.
private static XmlnsCache _xmlnsCache = null;
#endregion Data
#endregion Internal
}
// Type of object and type of Serializer for that type. If this type
// also contains an [XmlLang] property, this caches the property info also.
// These are contained in the _typeLookupFromXmlHashtable hastable
internal class TypeAndSerializer
{
public TypeAndSerializer()
{
}
public Type ObjectType = null;
public Type SerializerType = null;
public bool IsSerializerTypeSet = false;
public PropertyInfo XmlLangProperty;
}
/// <summary>
/// Contains information the XamlTypeMapper uses for Mapping between an xml
/// XmlNamespace and what Assembly, Namespace to look in.
/// </summary>
[DebuggerDisplay("'{_xmlNamespace}'={_clrNamespace}:{_assemblyName}")]
#if PBTCOMPILER
internal class NamespaceMapEntry
#else
public class NamespaceMapEntry
#endif
{
#region Constructors
///<summary>
/// NamespaceMapEntry default constructor
///</summary>
public NamespaceMapEntry()
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="xmlNamespace">The XML NamespaceURi</param>
/// <param name="assemblyName">Assembly to use when resolving a Tag</param>
/// <param name="clrNamespace">Namespace within the assembly</param>
public NamespaceMapEntry(string xmlNamespace,string assemblyName,string clrNamespace)
{
if (xmlNamespace == null)
throw new ArgumentNullException("xmlNamespace");
if (assemblyName == null)
throw new ArgumentNullException("assemblyName");
if (clrNamespace == null)
throw new ArgumentNullException("clrNamespace");
_xmlNamespace = xmlNamespace;
_assemblyName = assemblyName;
_clrNamespace = clrNamespace;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="xmlNamespace">The XML NamespaceURi</param>
/// <param name="assemblyName">Assembly to use when resolving a Tag</param>
/// <param name="clrNamespace">Namespace within the assembly</param>
/// <param name="assemblyPath">Path to use when loading assembly. This may be null.</param>
internal NamespaceMapEntry(
string xmlNamespace,
string assemblyName,
string clrNamespace,
string assemblyPath) : this(xmlNamespace, assemblyName, clrNamespace)
{
_assemblyPath = assemblyPath;
}
#endregion Constructors
#region Properties
/// <summary>
/// Xml namespace specified in the constructor
/// </summary>
public string XmlNamespace
{
get { return _xmlNamespace; }
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (_xmlNamespace == null)
{
_xmlNamespace = value;
}
}
}
/// <summary>
/// AssemblyName specified in the constructor
/// </summary>
public string AssemblyName
{
get { return _assemblyName; }
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (_assemblyName == null)
{
_assemblyName = value;
}
}
}
/// <summary>
/// ClrNamespace specified within the constructor
/// </summary>
public string ClrNamespace
{
get { return _clrNamespace; }
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (_clrNamespace == null)
{
_clrNamespace = value;
}
}
}
#endregion Properties
/// <summary>
/// returns instance of the assembly associate with this
/// namespace map
/// </summary>
internal Assembly Assembly
{
get
{
if (null == _assembly && _assemblyName.Length > 0)
{
#if PBTCOMPILER
// NOTE: At compile time a local assembly can already be loaded if being
// referenced by dehydrated assemblies and so we should attempt to return
// that.
if (_isLocalAssembly)
{
string assemblyNameLookup = _assemblyName.ToUpper(CultureInfo.InvariantCulture);
// Check if the assembly has already been loaded.
if (!ReflectionHelper.HasAlreadyReflectionOnlyLoaded(assemblyNameLookup))
{
return null;
}
}
#endif
_assembly = ReflectionHelper.LoadAssembly(_assemblyName, _assemblyPath);
}
return _assembly;
}
}
/// <summary>
/// Get and set the path to use when loading the assembly.
/// </summary>
internal string AssemblyPath
{
get { return _assemblyPath; }
set { _assemblyPath = value; }
}
#if PBTCOMPILER
internal bool LocalAssembly
{
get { return _isLocalAssembly; }
set { _isLocalAssembly = value; }
}
bool _isLocalAssembly;
#endif
#region Data
string _xmlNamespace;
string _assemblyName;
string _assemblyPath;
Assembly _assembly;
string _clrNamespace;
#endregion Data
}
// This is a convenience holder for all the possible IDs that Xaml understands which could
// be on an object element.
internal class XamlObjectIds
{
public string Name = null;
public string Uid = null;
public object Key = null;
}
#region XmlParserDefaults Class
// class for getting and setting mapping defaults.
internal static class XmlParserDefaults
{
#region Methods
/// <summary>
/// Instance of XamlTypeMapper to use if none is specified in the
/// ParserContext. XamlTypeMapper returned is has its assembly and namespace
/// maps initialized to those set
/// via SetDefaultXmlMapping() or one built from our internal defaults.
/// </summary>
internal static XamlTypeMapper DefaultMapper
{
get
{
return new XamlTypeMapper(GetDefaultAssemblyNames(),GetDefaultNamespaceMaps());
}
}
#endregion Methods
#region Properties
/// <summary>
/// Returns an array of the DefaultAssemblyNames
/// </summary>
internal static string[] GetDefaultAssemblyNames()
{
return (string[])_defaultAssemblies.Clone();
}
/// <summary>
/// Returns array of the DefaultNamespaceMaps
/// </summary>
internal static NamespaceMapEntry[] GetDefaultNamespaceMaps()
{
return (NamespaceMapEntry[])_defaultNamespaceMapTable.Clone();
}
#endregion Properties
#region Data
// array of our defaultAssemblies.
private static readonly string[] _defaultAssemblies = {"WindowsBase", "PresentationCore", "PresentationFramework"};
// array of namespaceMaps the map an xmlns namespaceURI
// to the assembly and urtNamespace to search in when resolving the xml
private static readonly NamespaceMapEntry[] _defaultNamespaceMapTable = { };
#endregion Data
}
#endregion XmlParserDefaults Class
}
| 40.113224
| 165
| 0.525236
|
[
"MIT"
] |
wjk/dotnet-wpf
|
src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Markup/XamlTypeMapper.cs
| 179,266
|
C#
|
using JetBrains.Annotations;
namespace Antares.Sdk.Health
{
/// <summary>
/// Health issue model class
/// </summary>
[PublicAPI]
public class HealthIssue
{
/// <summary>
/// The type of health issue.
/// </summary>
public string Type { get; private set; }
/// <summary>
/// The value or reason of the health issue.
/// </summary>
public string Value { get; private set; }
/// <summary>
/// Create a new health issue
/// </summary>
/// <param name="type">The type.</param>
/// <param name="value">The value.</param>
/// <returns>the created issue</returns>
public static HealthIssue Create(string type, string value)
{
return new HealthIssue
{
Type = type,
Value = value
};
}
}
}
| 24.756757
| 67
| 0.501092
|
[
"MIT"
] |
swisschain/Antares.Sdk
|
src/Antares.Sdk/Health/HealthIssue.cs
| 918
|
C#
|
using System;
using System.Collections.Generic;
namespace MVC_RabbitMQ.Entity
{
public partial class Owner
{
public Owner()
{
RepoData = new HashSet<RepoData>();
}
public int Id { get; set; }
public string AvatarUrl { get; set; }
public string EventsUrl { get; set; }
public string FollowersUrl { get; set; }
public string FollowingUrl { get; set; }
public string GistsUrl { get; set; }
public int GitHubId { get; set; }
public string GravatarId { get; set; }
public string HtmlUrl { get; set; }
public string Login { get; set; }
public string OrganizationsUrl { get; set; }
public string ReceivedEventsUrl { get; set; }
public string ReposUrl { get; set; }
public bool SiteAdmin { get; set; }
public string StarredUrl { get; set; }
public string SubscriptionsUrl { get; set; }
public string Type { get; set; }
public string Url { get; set; }
public virtual ICollection<RepoData> RepoData { get; set; }
}
}
| 31.742857
| 67
| 0.588659
|
[
"MIT"
] |
Koracas/Hello_ASP.NET_RabbitMQ
|
MVC_RabbitMQ/Entity/Owner.cs
| 1,113
|
C#
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
namespace BuildXL.Utilities.Configuration
{
/// <summary>
/// Defines the mode of forceSkipDeps (aka dirty build)
/// </summary>
public enum ForceSkipDependenciesMode : byte
{
/// <summary>
/// ForceSkipDeps is disabled
/// </summary>
Disabled,
/// <summary>
/// Dependencies are skipped if the inputs are present
/// </summary>
Always,
/// <summary>
/// Dependencies are skipped if they are from other modules and the inputs are present
/// </summary>
Module,
}
}
| 25.518519
| 95
| 0.560232
|
[
"MIT"
] |
BearerPipelineTest/BuildXL
|
Public/Src/Utilities/Configuration/ForceSkipDependenciesMode.cs
| 689
|
C#
|
// WARNING
//
// This file has been generated automatically by Xamarin Studio to store outlets and
// actions made in the UI designer. If it is removed, they will be lost.
// Manual changes to this file may not be handled correctly.
//
using Foundation;
using System.CodeDom.Compiler;
namespace CloudKitAtlas
{
[Register ("CKAssetViewController")]
partial class CKAssetViewController
{
[Outlet]
UIKit.UIImageView assetPreview { get; set; }
[Action ("DownloadPhoto:")]
partial void DownloadPhoto (Foundation.NSObject sender);
[Action ("TakePhoto:")]
partial void TakePhoto (Foundation.NSObject sender);
void ReleaseDesignerOutlets ()
{
if (assetPreview != null) {
assetPreview.Dispose ();
assetPreview = null;
}
}
}
}
| 23
| 84
| 0.719368
|
[
"Apache-2.0"
] |
ChristopherRamos/monotouch-samples
|
ios8/CloudKitAtlas/CloudKitAtlas/CKAssetViewController.designer.cs
| 759
|
C#
|
// <copyright file="AzureActiveDirectorySettings.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Apps.LearnNow.Models.Configuration
{
/// <summary>
/// A class which helps to provide Azure Active Directory settings for application.
/// </summary>
public class AzureActiveDirectorySettings
{
/// <summary>
/// Gets or sets application id URI.
/// </summary>
public string ApplicationIdURI { get; set; }
/// <summary>
/// Gets or sets valid issuer URL.
/// </summary>
public string ValidIssuers { get; set; }
/// <summary>
/// Gets or sets Azure Active Directory instance.
/// </summary>
public string Instance { get; set; }
/// <summary>
/// Gets or sets Graph API scope.
/// </summary>
public string GraphScope { get; set; }
}
}
| 28.909091
| 87
| 0.590147
|
[
"MIT"
] |
Aayushi1202/Coursecompanion
|
Source/Microsoft.Teams.Apps.LearnNow/Models/Configuration/AzureActiveDirectorySettings.cs
| 956
|
C#
|
using System.Linq;
using Solver.Base;
namespace Solver.Challenges.Day13
{
public class Day13Parser : IParser<Day13Input>
{
public Day13Input Parse(string[] values)
{
return new(int.Parse(values[0]),
values[1].Split(',').Select(r => r == "x" ? "0" : r).Select(int.Parse));
}
}
}
| 21.071429
| 76
| 0.654237
|
[
"MIT"
] |
klyse/AdventOfCode2020
|
Solver/Challenges/Day13/Day13Parser.cs
| 297
|
C#
|
namespace Aula06_Ex01
{
partial class frmCadastro
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tbcCadastro = new System.Windows.Forms.TabControl();
this.tbpRegistro = new System.Windows.Forms.TabPage();
this.btnAdicionar = new System.Windows.Forms.Button();
this.txtCodigo = new System.Windows.Forms.TextBox();
this.txtNome = new System.Windows.Forms.TextBox();
this.lblNome = new System.Windows.Forms.Label();
this.lblCodigo = new System.Windows.Forms.Label();
this.tdbTabela = new System.Windows.Forms.TabPage();
this.btnLimpar = new System.Windows.Forms.Button();
this.btnEliminar = new System.Windows.Forms.Button();
this.dgvTabela = new System.Windows.Forms.DataGridView();
this.Código = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Nome = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.btnLimparCad = new System.Windows.Forms.Button();
this.btnSairCad = new System.Windows.Forms.Button();
this.tbcCadastro.SuspendLayout();
this.tbpRegistro.SuspendLayout();
this.tdbTabela.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dgvTabela)).BeginInit();
this.SuspendLayout();
//
// tbcCadastro
//
this.tbcCadastro.Controls.Add(this.tbpRegistro);
this.tbcCadastro.Controls.Add(this.tdbTabela);
this.tbcCadastro.Location = new System.Drawing.Point(12, 12);
this.tbcCadastro.Name = "tbcCadastro";
this.tbcCadastro.SelectedIndex = 0;
this.tbcCadastro.Size = new System.Drawing.Size(561, 255);
this.tbcCadastro.TabIndex = 0;
//
// tbpRegistro
//
this.tbpRegistro.Controls.Add(this.btnAdicionar);
this.tbpRegistro.Controls.Add(this.txtCodigo);
this.tbpRegistro.Controls.Add(this.txtNome);
this.tbpRegistro.Controls.Add(this.lblNome);
this.tbpRegistro.Controls.Add(this.lblCodigo);
this.tbpRegistro.Location = new System.Drawing.Point(4, 22);
this.tbpRegistro.Name = "tbpRegistro";
this.tbpRegistro.Padding = new System.Windows.Forms.Padding(3);
this.tbpRegistro.Size = new System.Drawing.Size(553, 229);
this.tbpRegistro.TabIndex = 0;
this.tbpRegistro.Text = "Entrada de Dados";
this.tbpRegistro.UseVisualStyleBackColor = true;
//
// btnAdicionar
//
this.btnAdicionar.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnAdicionar.Location = new System.Drawing.Point(230, 153);
this.btnAdicionar.Name = "btnAdicionar";
this.btnAdicionar.Size = new System.Drawing.Size(119, 47);
this.btnAdicionar.TabIndex = 2;
this.btnAdicionar.Text = "Adicionar";
this.btnAdicionar.UseVisualStyleBackColor = true;
this.btnAdicionar.Click += new System.EventHandler(this.btnAdicionar_Click);
//
// txtCodigo
//
this.txtCodigo.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtCodigo.Location = new System.Drawing.Point(157, 29);
this.txtCodigo.Name = "txtCodigo";
this.txtCodigo.Size = new System.Drawing.Size(261, 32);
this.txtCodigo.TabIndex = 0;
this.txtCodigo.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtCodigo_KeyPress);
//
// txtNome
//
this.txtNome.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtNome.Location = new System.Drawing.Point(157, 101);
this.txtNome.Name = "txtNome";
this.txtNome.Size = new System.Drawing.Size(261, 32);
this.txtNome.TabIndex = 1;
//
// lblNome
//
this.lblNome.AutoSize = true;
this.lblNome.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblNome.Location = new System.Drawing.Point(75, 105);
this.lblNome.Name = "lblNome";
this.lblNome.Size = new System.Drawing.Size(67, 24);
this.lblNome.TabIndex = 1;
this.lblNome.Text = "Nome:";
//
// lblCodigo
//
this.lblCodigo.AutoSize = true;
this.lblCodigo.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblCodigo.Location = new System.Drawing.Point(75, 33);
this.lblCodigo.Name = "lblCodigo";
this.lblCodigo.Size = new System.Drawing.Size(76, 24);
this.lblCodigo.TabIndex = 0;
this.lblCodigo.Text = "Codigo:";
//
// tdbTabela
//
this.tdbTabela.Controls.Add(this.btnLimpar);
this.tdbTabela.Controls.Add(this.btnEliminar);
this.tdbTabela.Controls.Add(this.dgvTabela);
this.tdbTabela.Location = new System.Drawing.Point(4, 22);
this.tdbTabela.Name = "tdbTabela";
this.tdbTabela.Padding = new System.Windows.Forms.Padding(3);
this.tdbTabela.Size = new System.Drawing.Size(553, 229);
this.tdbTabela.TabIndex = 1;
this.tdbTabela.Text = "Consultar Dados";
this.tdbTabela.UseVisualStyleBackColor = true;
//
// btnLimpar
//
this.btnLimpar.Location = new System.Drawing.Point(458, 195);
this.btnLimpar.Name = "btnLimpar";
this.btnLimpar.Size = new System.Drawing.Size(75, 23);
this.btnLimpar.TabIndex = 1;
this.btnLimpar.Text = "Limpar";
this.btnLimpar.UseVisualStyleBackColor = true;
this.btnLimpar.Click += new System.EventHandler(this.btnLimpar_Click);
//
// btnEliminar
//
this.btnEliminar.Location = new System.Drawing.Point(377, 195);
this.btnEliminar.Name = "btnEliminar";
this.btnEliminar.Size = new System.Drawing.Size(75, 23);
this.btnEliminar.TabIndex = 0;
this.btnEliminar.Text = "Eliminar";
this.btnEliminar.UseVisualStyleBackColor = true;
this.btnEliminar.Click += new System.EventHandler(this.btnEliminar_Click);
//
// dgvTabela
//
this.dgvTabela.AllowUserToAddRows = false;
this.dgvTabela.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgvTabela.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Código,
this.Nome});
this.dgvTabela.Location = new System.Drawing.Point(0, 3);
this.dgvTabela.Name = "dgvTabela";
this.dgvTabela.Size = new System.Drawing.Size(550, 186);
this.dgvTabela.TabIndex = 0;
//
// Código
//
this.Código.HeaderText = "Código";
this.Código.Name = "Código";
this.Código.ReadOnly = true;
//
// Nome
//
this.Nome.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.Nome.HeaderText = "Nome";
this.Nome.Name = "Nome";
this.Nome.ReadOnly = true;
//
// btnLimparCad
//
this.btnLimparCad.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnLimparCad.Location = new System.Drawing.Point(366, 273);
this.btnLimparCad.Name = "btnLimparCad";
this.btnLimparCad.Size = new System.Drawing.Size(97, 37);
this.btnLimparCad.TabIndex = 3;
this.btnLimparCad.Text = "Limpar";
this.btnLimparCad.UseVisualStyleBackColor = true;
this.btnLimparCad.Click += new System.EventHandler(this.btnLimparCad_Click);
//
// btnSairCad
//
this.btnSairCad.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnSairCad.Location = new System.Drawing.Point(465, 273);
this.btnSairCad.Name = "btnSairCad";
this.btnSairCad.Size = new System.Drawing.Size(104, 37);
this.btnSairCad.TabIndex = 4;
this.btnSairCad.Text = "Sair";
this.btnSairCad.UseVisualStyleBackColor = true;
this.btnSairCad.Click += new System.EventHandler(this.btnSairCad_Click);
//
// frmCadastro
//
this.AcceptButton = this.btnAdicionar;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(585, 330);
this.Controls.Add(this.btnSairCad);
this.Controls.Add(this.btnLimparCad);
this.Controls.Add(this.tbcCadastro);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Name = "frmCadastro";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = " Cadastro";
this.tbcCadastro.ResumeLayout(false);
this.tbpRegistro.ResumeLayout(false);
this.tbpRegistro.PerformLayout();
this.tdbTabela.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dgvTabela)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TabControl tbcCadastro;
private System.Windows.Forms.TabPage tbpRegistro;
private System.Windows.Forms.Label lblCodigo;
private System.Windows.Forms.TabPage tdbTabela;
private System.Windows.Forms.DataGridView dgvTabela;
private System.Windows.Forms.Button btnAdicionar;
private System.Windows.Forms.TextBox txtNome;
private System.Windows.Forms.TextBox txtCodigo;
private System.Windows.Forms.Label lblNome;
private System.Windows.Forms.Button btnLimpar;
private System.Windows.Forms.Button btnEliminar;
private System.Windows.Forms.DataGridViewTextBoxColumn Código;
private System.Windows.Forms.DataGridViewTextBoxColumn Nome;
private System.Windows.Forms.Button btnLimparCad;
private System.Windows.Forms.Button btnSairCad;
}
}
| 49.595918
| 174
| 0.604806
|
[
"MIT"
] |
MatheusFranciscone/Projeto_MultiFunctions
|
Aula06_Ex01/Aula06_Ex01/Cadastro.Designer.cs
| 12,162
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace BCM.Models
{
[Serializable]
public class BCMRecipe : BCMAbstract
{
#region Filters
public static class StrFilters
{
public const string Type = "type";
public const string Count = "count";
public const string CraftExp = "exp";
public const string CraftArea = "area";
public const string CraftTime = "time";
public const string CraftTool = "tool";
public const string Tooltip = "tooltip";
public const string IsMatBased = "matbased";
public const string IsScrappable = "scrappable";
public const string IsWildCamp = "wildcamp";
public const string IsWildForge = "wildforge";
public const string Skill = "skill";
public const string Ingredients = "ingredients";
}
private static readonly Dictionary<int, string> _filterMap = new Dictionary<int, string>
{
{ 0, StrFilters.Type },
{ 1, StrFilters.Count },
{ 2, StrFilters.CraftExp },
{ 3, StrFilters.CraftArea },
{ 4, StrFilters.CraftTime },
{ 5, StrFilters.CraftTool },
{ 6, StrFilters.Tooltip },
{ 7, StrFilters.IsMatBased },
{ 8, StrFilters.IsScrappable },
{ 9, StrFilters.IsWildCamp },
{ 10, StrFilters.IsWildForge },
{ 11, StrFilters.Skill },
{ 12, StrFilters.Ingredients }
};
public static Dictionary<int, string> FilterMap => _filterMap;
#endregion
#region Properties
public int Type;
public int Count;
public int CraftExp;
public string CraftArea;
public double CraftTime;
public int CraftTool;
public string Tooltip;
public bool IsMatBased;
public bool IsScrappable;
public bool IsWildCamp;
public bool IsWildForge;
public string Skill;
public class BCMIngredient
{
public int Type;
public int Count;
}
public List<BCMIngredient> Ingredients = new List<BCMIngredient>();
#endregion;
public BCMRecipe(object obj, string typeStr, Dictionary<string, string> options, List<string> filters) : base(obj, typeStr, options, filters)
{
}
public override void GetData(object obj)
{
if (!(obj is Recipe recipe)) return;
if (IsOption("filter"))
{
foreach (var f in StrFilter)
{
switch (f)
{
case StrFilters.Type:
GetType(recipe);
break;
case StrFilters.Count:
GetCount(recipe);
break;
case StrFilters.CraftArea:
GetCraftArea(recipe);
break;
case StrFilters.CraftExp:
GetCraftExp(recipe);
break;
case StrFilters.CraftTime:
GetCraftTime(recipe);
break;
case StrFilters.CraftTool:
GetCraftTool(recipe);
break;
case StrFilters.IsMatBased:
GetMatsBased(recipe);
break;
case StrFilters.IsScrappable:
GetScrappable(recipe);
break;
case StrFilters.IsWildCamp:
GetWildCamp(recipe);
break;
case StrFilters.IsWildForge:
GetWildForge(recipe);
break;
case StrFilters.Skill:
GetSkill(recipe);
break;
case StrFilters.Tooltip:
GetTooltip(recipe);
break;
case StrFilters.Ingredients:
GetIngredients(recipe);
break;
default:
Log.Out($"{Config.ModPrefix} Unknown filter {f}");
break;
}
}
}
else
{
GetType(recipe);
GetCount(recipe);
GetCraftArea(recipe);
GetCraftExp(recipe);
GetCraftTime(recipe);
GetCraftTool(recipe);
GetMatsBased(recipe);
GetScrappable(recipe);
GetWildCamp(recipe);
GetWildForge(recipe);
GetSkill(recipe);
GetTooltip(recipe);
GetIngredients(recipe);
}
}
private void GetTooltip(Recipe recipe) => Bin.Add("Tooltip", Tooltip = recipe.tooltip);
private void GetSkill(Recipe recipe) => Bin.Add("Skill", Skill = ItemClass.list[recipe.itemValueType]?.CraftingSkillGroup);
private void GetWildForge(Recipe recipe) => Bin.Add("IsWildForge", IsWildForge = recipe.wildcardForgeCategory);
private void GetWildCamp(Recipe recipe) => Bin.Add("IsWildCamp", IsWildCamp = recipe.wildcardCampfireCategory);
private void GetScrappable(Recipe recipe) => Bin.Add("IsScrappable", IsScrappable = recipe.scrapable);
private void GetMatsBased(Recipe recipe) => Bin.Add("IsMatBased", IsMatBased = recipe.materialBasedRecipe);
private void GetCraftTool(Recipe recipe) => Bin.Add("CraftTool", CraftTool = recipe.craftingToolType);
private void GetCraftTime(Recipe recipe) => Bin.Add("CraftTime", CraftTime = Math.Round(recipe.craftingTime, 2));
private void GetCraftExp(Recipe recipe) => Bin.Add("CraftExp", CraftExp = recipe.craftExpGain);
private void GetCraftArea(Recipe recipe) => Bin.Add("CraftArea", CraftArea = recipe.craftingArea);
private void GetCount(Recipe recipe) => Bin.Add("Count", Count = recipe.count);
private void GetType(Recipe recipe) => Bin.Add("Type", Type = recipe.itemValueType);
private void GetIngredients(Recipe recipe)
{
foreach (var itemStack in recipe.ingredients)
{
Ingredients.Add(new BCMIngredient { Type = itemStack.itemValue.type, Count = itemStack.count });
}
if (Options.ContainsKey("min"))
{
Bin.Add("Ingredients", Ingredients.Select(ing => new[] { ing.Type, ing.Count }).Cast<object>().ToList());
}
else
{
Bin.Add("Ingredients", Ingredients);
}
}
}
}
| 32.344086
| 145
| 0.598072
|
[
"MIT"
] |
kangkang198778/BCM
|
BCManager/src/Models/BCMRecipe.cs
| 6,018
|
C#
|
using System.Linq;
using Ardalis.GuardClauses;
using CMS.DocumentEngine;
using CSharpFunctionalExtensions;
using FluentCacheKeys;
using Sandbox.Core.Domain.Intrastructure.Operations.Queries;
using Sandbox.Data.Kentico.Infrastructure.Queries;
using Sandbox.Delivery.Core.Features.Nodes;
using static Sandbox.Data.Kentico.Infrastructure.Queries.ContextCacheKeysCreator;
namespace Sandbox.Delivery.Data.Features.Nodes
{
public class NodeAliasPathByNodeGuidQueryHandler :
IQueryHandlerSync<NodeAliasPathByNodeGuidQuery, string>,
IQuerySyncCacheKeysCreator<NodeAliasPathByNodeGuidQuery, string>
{
private readonly IDocumentQueryContext context;
public NodeAliasPathByNodeGuidQueryHandler(IDocumentQueryContext context)
{
Guard.Against.Null(context, nameof(context));
this.context = context;
}
public Result<string> Execute(NodeAliasPathByNodeGuidQuery query)
{
var node = DocumentHelper
.GetDocuments()
.GetLatestSiteDocuments(context)
.WhereEquals(nameof(TreeNode.NodeGUID), query.NodeGuid)
.TopN(1)
.TypedResult
.FirstOrDefault();
if (node is null)
{
return Result.Failure<string>($"Could not find node [{query.NodeGuid}]");
}
return Result.Success(node.NodeAliasPath);
}
public string[] DependencyKeys(NodeAliasPathByNodeGuidQuery query, Result<string> result) =>
new[] { FluentCacheKey.ForPage().OfSite(context.SiteName).WithNodeGuid(query.NodeGuid) };
public object[] ItemNameParts(NodeAliasPathByNodeGuidQuery query) =>
NamePartsFromQuery(context, nameof(NodeAliasPathByNodeGuidQuery), query.NodeGuid);
}
}
| 35.346154
| 101
| 0.68444
|
[
"MIT"
] |
seangwright/clean-kentico12-mvc
|
src/delivery/Sandbox.Delivery.Data/Features/Nodes/NodeAliasPathByNodeGuidQueryHandler.cs
| 1,840
|
C#
|
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
* This software is subject to the Microsoft Public License (Ms-PL).
* A copy of the license can be found in the license.htm file included
* in this distribution.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq.Expressions;
using ServiceStack.Markdown;
namespace ServiceStack.Html
{
public static class InputExtensions
{
// CheckBox
public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name)
{
return CheckBox(htmlHelper, name, (object)null /* htmlAttributes */);
}
public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name, bool isChecked)
{
return CheckBox(htmlHelper, name, isChecked, (object)null /* htmlAttributes */);
}
public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name, bool isChecked, object htmlAttributes)
{
return CheckBox(htmlHelper, name, isChecked, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name, object htmlAttributes)
{
return CheckBox(htmlHelper, name, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name, IDictionary<string, object> htmlAttributes)
{
return CheckBoxHelper(htmlHelper, null, name, null /* isChecked */, htmlAttributes);
}
public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name, bool isChecked, IDictionary<string, object> htmlAttributes)
{
return CheckBoxHelper(htmlHelper, null, name, isChecked, htmlAttributes);
}
public static MvcHtmlString CheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression)
{
return CheckBoxFor(htmlHelper, expression, null /* htmlAttributes */);
}
public static MvcHtmlString CheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression, object htmlAttributes)
{
return CheckBoxFor(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString CheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression, IDictionary<string, object> htmlAttributes)
{
if (expression == null)
{
throw new ArgumentNullException("expression");
}
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
bool? isChecked = null;
if (metadata.Model != null)
{
bool modelChecked;
if (Boolean.TryParse(metadata.Model.ToString(), out modelChecked))
{
isChecked = modelChecked;
}
}
return CheckBoxHelper(htmlHelper, metadata, ExpressionHelper.GetExpressionText(expression), isChecked, htmlAttributes);
}
private static MvcHtmlString CheckBoxHelper(HtmlHelper htmlHelper, ModelMetadata metadata, string name, bool? isChecked, IDictionary<string, object> htmlAttributes)
{
RouteValueDictionary attributes = ToRouteValueDictionary(htmlAttributes);
bool explicitValue = isChecked.HasValue;
if (explicitValue)
{
attributes.Remove("checked"); // Explicit value must override dictionary
}
return InputHelper(htmlHelper, InputType.CheckBox, metadata, name, "true", !explicitValue /* useViewData */, isChecked ?? false, true /* setId */, false /* isExplicitValue */, attributes);
}
// Hidden
public static MvcHtmlString Hidden(this HtmlHelper htmlHelper, string name)
{
return Hidden(htmlHelper, name, null /* value */, null /* htmlAttributes */);
}
public static MvcHtmlString Hidden(this HtmlHelper htmlHelper, string name, object value)
{
return Hidden(htmlHelper, name, value, null /* hmtlAttributes */);
}
public static MvcHtmlString Hidden(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes)
{
return Hidden(htmlHelper, name, value, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString Hidden(this HtmlHelper htmlHelper, string name, object value, IDictionary<string, object> htmlAttributes)
{
return HiddenHelper(htmlHelper,
null,
value,
value == null /* useViewData */,
name,
htmlAttributes);
}
public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
return HiddenFor(htmlHelper, expression, (IDictionary<string, object>)null);
}
public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
return HiddenFor(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
return HiddenHelper(htmlHelper,
metadata,
metadata.Model,
false,
ExpressionHelper.GetExpressionText(expression),
htmlAttributes);
}
private static MvcHtmlString HiddenHelper(HtmlHelper htmlHelper, ModelMetadata metadata, object value, bool useViewData, string expression, IDictionary<string, object> htmlAttributes)
{
byte[] byteArrayValue = value as byte[];
if (byteArrayValue != null)
{
value = Convert.ToBase64String(byteArrayValue);
}
return InputHelper(htmlHelper, InputType.Hidden, metadata, expression, value, useViewData, false /* isChecked */, true /* setId */, true /* isExplicitValue */, htmlAttributes);
}
// Password
public static MvcHtmlString Password(this HtmlHelper htmlHelper, string name)
{
return Password(htmlHelper, name, null /* value */);
}
public static MvcHtmlString Password(this HtmlHelper htmlHelper, string name, object value)
{
return Password(htmlHelper, name, value, null /* htmlAttributes */);
}
public static MvcHtmlString Password(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes)
{
return Password(htmlHelper, name, value, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString Password(this HtmlHelper htmlHelper, string name, object value, IDictionary<string, object> htmlAttributes)
{
return PasswordHelper(htmlHelper, null /* metadata */, name, value, htmlAttributes);
}
public static MvcHtmlString PasswordFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
return PasswordFor(htmlHelper, expression, null /* htmlAttributes */);
}
public static MvcHtmlString PasswordFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
return PasswordFor(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString PasswordFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
{
if (expression == null)
{
throw new ArgumentNullException("expression");
}
return PasswordHelper(htmlHelper,
ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData),
ExpressionHelper.GetExpressionText(expression),
null /* value */,
htmlAttributes);
}
private static MvcHtmlString PasswordHelper(HtmlHelper htmlHelper, ModelMetadata metadata, string name, object value, IDictionary<string, object> htmlAttributes)
{
return InputHelper(htmlHelper, InputType.Password, metadata, name, value, false /* useViewData */, false /* isChecked */, true /* setId */, true /* isExplicitValue */, htmlAttributes);
}
// RadioButton
public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, object value)
{
return RadioButton(htmlHelper, name, value, (object)null /* htmlAttributes */);
}
public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes)
{
return RadioButton(htmlHelper, name, value, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, object value, IDictionary<string, object> htmlAttributes)
{
// Determine whether or not to render the checked attribute based on the contents of ViewData.
string valueString = Convert.ToString(value, CultureInfo.CurrentCulture);
bool isChecked = (!String.IsNullOrEmpty(name)) && (String.Equals(htmlHelper.EvalString(name), valueString, StringComparison.OrdinalIgnoreCase));
// checked attributes is implicit, so we need to ensure that the dictionary takes precedence.
RouteValueDictionary attributes = ToRouteValueDictionary(htmlAttributes);
if (attributes.ContainsKey("checked"))
{
return InputHelper(htmlHelper, InputType.Radio, null, name, value, false, false, true, true /* isExplicitValue */, attributes);
}
return RadioButton(htmlHelper, name, value, isChecked, htmlAttributes);
}
public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, object value, bool isChecked)
{
return RadioButton(htmlHelper, name, value, isChecked, (object)null /* htmlAttributes */);
}
public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, object value, bool isChecked, object htmlAttributes)
{
return RadioButton(htmlHelper, name, value, isChecked, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, object value, bool isChecked, IDictionary<string, object> htmlAttributes)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
// checked attribute is an explicit parameter so it takes precedence.
RouteValueDictionary attributes = ToRouteValueDictionary(htmlAttributes);
attributes.Remove("checked");
return InputHelper(htmlHelper, InputType.Radio, null, name, value, false, isChecked, true, true /* isExplicitValue */, attributes);
}
public static MvcHtmlString RadioButtonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value)
{
return RadioButtonFor(htmlHelper, expression, value, null /* htmlAttributes */);
}
public static MvcHtmlString RadioButtonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, object htmlAttributes)
{
return RadioButtonFor(htmlHelper, expression, value, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString RadioButtonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, IDictionary<string, object> htmlAttributes)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
return RadioButtonHelper(htmlHelper,
metadata,
metadata.Model,
ExpressionHelper.GetExpressionText(expression),
value,
null /* isChecked */,
htmlAttributes);
}
private static MvcHtmlString RadioButtonHelper(HtmlHelper htmlHelper, ModelMetadata metadata, object model, string name, object value, bool? isChecked, IDictionary<string, object> htmlAttributes)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
var attributes = ToRouteValueDictionary(htmlAttributes);
var explicitValue = isChecked.HasValue;
if (explicitValue)
{
attributes.Remove("checked"); // Explicit value must override dictionary
}
else
{
var valueString = Convert.ToString(value, CultureInfo.CurrentCulture);
isChecked = model != null &&
!String.IsNullOrEmpty(name) &&
String.Equals(model.ToString(), valueString, StringComparison.OrdinalIgnoreCase);
}
return InputHelper(htmlHelper, InputType.Radio, metadata, name, value, false /* useViewData */, isChecked ?? false, true /* setId */, true /* isExplicitValue */, attributes);
}
// TextBox
public static MvcHtmlString TextBox(this HtmlHelper htmlHelper, string name)
{
return TextBox(htmlHelper, name, null /* value */);
}
public static MvcHtmlString TextBox(this HtmlHelper htmlHelper, string name, object value)
{
return TextBox(htmlHelper, name, value, (object)null /* htmlAttributes */);
}
public static MvcHtmlString TextBox(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes)
{
return TextBox(htmlHelper, name, value, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString TextBox(this HtmlHelper htmlHelper, string name, object value, IDictionary<string, object> htmlAttributes)
{
return InputHelper(htmlHelper, InputType.Text, null, name, value, (value == null) /* useViewData */, false /* isChecked */, true /* setId */, true /* isExplicitValue */, htmlAttributes);
}
public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
return htmlHelper.TextBoxFor(expression, (IDictionary<string, object>)null);
}
public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
return htmlHelper.TextBoxFor(expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
return TextBoxHelper(htmlHelper,
metadata,
metadata != null ? metadata.Model : null,
ExpressionHelper.GetExpressionText(expression),
htmlAttributes);
}
private static MvcHtmlString TextBoxHelper(this HtmlHelper htmlHelper, ModelMetadata metadata, object model, string expression, IDictionary<string, object> htmlAttributes)
{
return InputHelper(htmlHelper, InputType.Text, metadata, expression, model, false /* useViewData */, false /* isChecked */, true /* setId */, true /* isExplicitValue */, htmlAttributes);
}
// Helper methods
private static MvcHtmlString InputHelper(HtmlHelper htmlHelper, InputType inputType, ModelMetadata metadata, string name, object value, bool useViewData, bool isChecked, bool setId, bool isExplicitValue, IDictionary<string, object> htmlAttributes)
{
var fullName = name;
if (String.IsNullOrEmpty(name))
{
throw new ArgumentException(MvcResources.Common_NullOrEmpty, "name");
}
var tagBuilder = new TagBuilder("input");
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.MergeAttribute("type", HtmlHelper.GetInputTypeString(inputType));
tagBuilder.MergeAttribute("name", fullName, true);
string valueParameter = Convert.ToString(value, CultureInfo.CurrentCulture);
bool usedModelState = false;
switch (inputType)
{
case InputType.CheckBox:
var modelStateWasChecked = htmlHelper.GetModelStateValue(fullName, typeof(bool)) as bool?;
if (modelStateWasChecked.HasValue)
{
isChecked = modelStateWasChecked.Value;
usedModelState = true;
}
goto case InputType.Radio;
case InputType.Radio:
if (!usedModelState)
{
var modelStateValue = htmlHelper.GetModelStateValue(fullName, typeof(string)) as string;
if (modelStateValue != null)
{
isChecked = String.Equals(modelStateValue, valueParameter, StringComparison.Ordinal);
usedModelState = true;
}
}
if (!usedModelState && useViewData)
{
isChecked = htmlHelper.EvalBoolean(fullName);
}
if (isChecked)
{
tagBuilder.MergeAttribute("checked", "checked");
}
tagBuilder.MergeAttribute("value", valueParameter, isExplicitValue);
break;
case InputType.Password:
if (value != null)
{
tagBuilder.MergeAttribute("value", valueParameter, isExplicitValue);
}
break;
default:
var attemptedValue = (string)htmlHelper.GetModelStateValue(fullName, typeof(string));
tagBuilder.MergeAttribute("value", attemptedValue ?? ((useViewData) ? htmlHelper.EvalString(fullName) : valueParameter), isExplicitValue);
break;
}
return tagBuilder.ToMvcHtmlString(TagRenderMode.SelfClosing);
}
private static RouteValueDictionary ToRouteValueDictionary(IDictionary<string, object> dictionary)
{
return dictionary == null ? new RouteValueDictionary() : new RouteValueDictionary(dictionary);
}
}
}
| 42.178147
| 250
| 0.724841
|
[
"BSD-3-Clause"
] |
Dashboard-X/ServiceStack
|
src/ServiceStack/Html/InputExtensions.cs
| 17,339
|
C#
|
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights;
namespace MVCFramework45.FunctionalTests.Controllers
{
public class HomeController : Controller
{
private TelemetryClient telemetryClient;
public HomeController(TelemetryClient telemetryClient)
{
this.telemetryClient = telemetryClient;
}
public IActionResult Index()
{
return View();
}
public IActionResult Exception()
{
throw new InvalidOperationException("Do not call the method called Exception");
}
public IActionResult About(int index)
{
ViewBag.Message = "Your application description page # " + index;
return View();
}
public IActionResult Contact()
{
this.telemetryClient.TrackEvent("GetContact");
this.telemetryClient.TrackMetric("ContactFile", 1);
this.telemetryClient.TrackTrace("Fetched contact details.", SeverityLevel.Information);
return View();
}
public IActionResult Dependency()
{
this.telemetryClient.TrackDependency("MyDependency", "MyCommand", DateTimeOffset.Now, TimeSpan.FromMilliseconds(1), success: true);
return View();
}
public IActionResult Error()
{
return View("~/Views/Shared/Error.cshtml");
}
}
}
| 27.909091
| 143
| 0.625407
|
[
"MIT"
] |
SergeyRazmyslov/ApplicationInsights-dotnet
|
NETCORE/test/MVCFramework.FunctionalTests/Controllers/HomeController.cs
| 1,537
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace eleave_view.hr {
public partial class balleave {
/// <summary>
/// grd_bal control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.GridView grd_bal;
/// <summary>
/// btnpdf control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnpdf;
/// <summary>
/// btnexl control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnexl;
}
}
| 32.186047
| 84
| 0.495665
|
[
"MIT"
] |
agailevictor/e_leave
|
eleave/eleave_view/hr/balleave.aspx.designer.cs
| 1,386
|
C#
|
namespace Aircompany.Models
{
public enum MilitaryPlaneType
{
FIGHTER,
BOMBER,
TRANSPORT
}
}
| 13
| 33
| 0.569231
|
[
"MIT"
] |
Haste-s/CleanCode
|
Net/Aircompany/Models/MilitaryPlaneType.cs
| 132
|
C#
|
//-----------------------------------------------------------------------------
// FILE: Test_NeonClusterApi.cs
// CONTRIBUTOR: Marcus Bowyer
// COPYRIGHT: Copyright (c) 2005-2021 by neonFORGE LLC. 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.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Neon.Common;
using Neon.IO;
using Neon.Kube;
using Neon.Kube.Xunit;
using Neon.Net;
using Neon.Service;
using Neon.Xunit;
using Xunit;
namespace TestKube
{
[Trait(TestTrait.Category, TestArea.NeonKube)]
[Collection(TestCollection.NonParallel)]
[CollectionDefinition(TestCollection.NonParallel, DisableParallelization = true)]
public class Test_NeonClusterApi : IClassFixture<ComposedFixture>
{
private ServiceMap serviceMap;
private ComposedFixture composedFixture;
private NeonServiceFixture<NeonClusterApi.Service> NeonClusterApiFixture;
private DockerFixture citusFixture;
private KubeKV client;
private string citusUser;
private string citusPassword;
private string citusDb;
public Test_NeonClusterApi(ComposedFixture composedFixture)
{
this.composedFixture = composedFixture;
this.serviceMap = CreateServiceMap();
citusUser = "neontest";
citusPassword = NeonHelper.GetCryptoRandomPassword(10);
citusDb = "postgres";
composedFixture.Start(
() =>
{
composedFixture.AddFixture(NeonServices.NeonSystemDb, new DockerFixture(),
dockerFixture =>
{
dockerFixture.CreateService(
name: NeonServices.NeonSystemDb,
image: "citusdata/citus",
dockerArgs: new string[]{
"-p",
"5432:5432",
},
env: new string[] {
$"POSTGRES_USER={citusUser}",
$"POSTGRES_PASSWORD={citusPassword}",
$"POSTGRES_DB={citusDb}"
});
});
composedFixture.AddServiceFixture<NeonClusterApi.Service>(NeonServices.NeonClusterApiService, new NeonServiceFixture<NeonClusterApi.Service>(), () => CreateNeonClusterApiService(), startTimeout: TimeSpan.FromMinutes(5));
});
this.citusFixture = (DockerFixture)composedFixture[NeonServices.NeonSystemDb];
this.NeonClusterApiFixture = (NeonServiceFixture<NeonClusterApi.Service>)composedFixture[NeonServices.NeonClusterApiService];
client = new KubeKV(serviceMap);
}
/// <summary>
/// Returns the service map.
/// </summary>
private ServiceMap CreateServiceMap()
{
var serviceMap = new ServiceMap();
//---------------------------------------------
// system database:
var description = new ServiceDescription()
{
Name = NeonServices.NeonSystemDb,
Address = "127.0.0.10"
};
description.Endpoints.Add(
new ServiceEndpoint()
{
Protocol = ServiceEndpointProtocol.Tcp,
Port = 5432
});
serviceMap.Add(description);
//---------------------------------------------
// web-service:
description = new ServiceDescription()
{
Name = NeonServices.NeonClusterApiService,
Address = "127.0.0.10"
};
description.Endpoints.Add(
new ServiceEndpoint()
{
Protocol = ServiceEndpointProtocol.Http,
PathPrefix = "/",
Port = 1234
});
serviceMap.Add(description);
return serviceMap;
}
/// <summary>
/// Returns the neon-cluster-api.
/// </summary>
/// <returns></returns>
public NeonClusterApi.Service CreateNeonClusterApiService()
{
var service = new NeonClusterApi.Service(NeonServices.NeonClusterApiService, CreateServiceMap());
service.SetEnvironmentVariable("CITUS_USER", citusUser);
service.SetEnvironmentVariable("CITUS_PASSWORD", citusPassword);
service.SetEnvironmentVariable("NEON_USER", KubeConst.NeonSystemDbAdminUser);
service.SetEnvironmentVariable("NEON_PASSWORD", NeonHelper.GetCryptoRandomPassword(10));
return service;
}
/// <summary>
/// Delete all values in the state table.
/// </summary>
/// <returns></returns>
private async Task ClearDatabaseAsync()
{
await client.RemoveAsync("*", regex: true);
}
public class JsonTestPerson
{
public string Name { get; set; }
public int Age { get; set; }
}
[Fact]
public async void GetValue()
{
// Verify that get works and returns null when key doesn't exist.
await ClearDatabaseAsync();
var key = "foo";
await Assert.ThrowsAsync<KubeKVException>(async () => await client.GetAsync<string>(key));
var value = "bar";
await client.SetAsync(key, value);
var result = await client.GetAsync<string>(key);
Assert.Equal(value, result);
}
[Fact]
public async void SetValue()
{
// Verify we can set different types of values.
await ClearDatabaseAsync();
var key = "foo";
var value = "bar";
await client.SetAsync(key, value);
var result = await client.GetAsync<string>(key);
Assert.Equal(value, result);
var marcus = new JsonTestPerson()
{
Name = "Marcus",
Age = 28
};
await client.SetAsync("marcus", marcus);
var person = await client.GetAsync<JsonTestPerson>("marcus");
Assert.Equal(marcus.Age, person.Age);
Assert.Equal(marcus.Name, person.Name);
}
[Fact]
public async void UpsertValue()
{
// Verify that we can update existing values.
await ClearDatabaseAsync();
var key = "foo";
var value = "bar";
await client.SetAsync(key, value);
var result = await client.GetAsync<string>(key);
Assert.Equal(value, result);
value = "baz";
await client.SetAsync(key, value);
result = await client.GetAsync<string>(key);
Assert.Equal(value, result);
}
[Fact]
public async void GetDefault()
{
// Verify that we get default value when key doesn't exist.
await ClearDatabaseAsync();
var key = "foo";
var result = await client.GetAsync<int>(key, 101);
Assert.Equal(101, result);
var nullResult = await client.GetAsync<string>(key, null);
Assert.Null(nullResult);
var value = 1;
await client.SetAsync(key, value);
result = await client.GetAsync<int>(key, 101);
Assert.Equal(1, result);
}
[Fact]
public async Task DeleteValue()
{
// Verify deleting with and without regex works
await ClearDatabaseAsync();
await client.SetAsync("foo-0", "0");
await client.SetAsync("foo-1", "1");
await client.SetAsync("foo-2", "2");
await client.SetAsync("bar-0", "0");
await client.SetAsync("bar-1", "1");
await client.SetAsync("bar-2", "2");
await client.SetAsync("0-baz-0", "0");
await client.SetAsync("1-baz-2", "0000");
await client.RemoveAsync("foo-1", regex: false);
await Assert.ThrowsAsync<KubeKVException>(async () => await client.GetAsync<string>("foo-1"));
var results = await client.ListAsync<dynamic>("*");
Assert.Equal(7, results.Count);
await client.RemoveAsync("^bar-*", regex: true);
results = await client.ListAsync<dynamic>("*");
Assert.Equal(4, results.Count);
await client.RemoveAsync("[0-9]+-[a-z]+-[0-9]", regex: true);
results = await client.ListAsync<dynamic>("*");
Assert.Equal(2, results.Count);
}
[Fact]
public async void ListValues()
{
// Verify list with/without regex works.
await ClearDatabaseAsync();
await client.SetAsync("foo-0", "0");
await client.SetAsync("foo-1", "1");
await client.SetAsync("foo-2", "2");
await client.SetAsync("bar-0", "0");
await client.SetAsync("bar-1", "1");
await client.SetAsync("bar-2", "2");
await client.SetAsync("0-baz-0", "0");
await client.SetAsync("1-baz-2", "0000");
var result = await client.ListAsync<dynamic>("foo*");
Assert.Equal(3, result.Count);
var results = await client.ListAsync<dynamic>("*");
Assert.Equal(8, results.Count);
results = await client.ListAsync<dynamic>("^bar-*");
Assert.Equal(3, results.Count);
results = await client.ListAsync<dynamic>("[0-9]+-[a-z]+-[0-9]");
Assert.Equal(2, results.Count);
}
}
}
| 32.432515
| 239
| 0.539298
|
[
"Apache-2.0"
] |
nforgeio/neonKUBE
|
Test/Test.Neon.Kube/Kube/Test_NeonKubeKv.cs
| 10,575
|
C#
|
#if !NETCORE_SUPPORT
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using NUnit.Framework;
using ServiceStack.Configuration;
using ServiceStack.OrmLite;
using ServiceStack.Text;
namespace ServiceStack.Common.Tests
{
[TestFixture]
public class EnvironmentAppSettingsTests
{
[Test]
public void Can_get_environment_variable()
{
var env = new EnvironmentVariableSettings();
var path = env.Get("PATH");
Assert.That(path, Is.Not.Null);
var unknown = env.Get("UNKNOWN");
Assert.That(unknown, Is.Null);
var envVars = env.GetAllKeys();
Assert.That(envVars.Count, Is.GreaterThan(0));
}
}
public class MultiAppSettingsTest : AppSettingsTest
{
public override AppSettingsBase GetAppSettings()
{
return new MultiAppSettings(
new DictionarySettings(GetConfigDictionary()),
new AppSettings());
}
public override Dictionary<string, string> GetConfigDictionary()
{
var configMap = base.GetConfigDictionary();
configMap.Remove("NullableKey");
return configMap;
}
}
public class AppConfigAppSettingsTest : AppSettingsTest
{
public override AppSettingsBase GetAppSettings()
{
return new AppSettings();
}
public override Dictionary<string, string> GetConfigDictionary()
{
var configMap = base.GetConfigDictionary();
configMap.Remove("NullableKey");
return configMap;
}
}
public class OrmLiteAppSettingsTest : AppSettingsTest
{
private OrmLiteAppSettings settings;
[OneTimeSetUp]
public void TestFixtureSetUp()
{
settings = new OrmLiteAppSettings(
new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider));
settings.InitSchema();
}
public override AppSettingsBase GetAppSettings()
{
var testConfig = (DictionarySettings)base.GetAppSettings();
using (var db = settings.DbFactory.Open())
{
db.DeleteAll<ConfigSetting>();
foreach (var config in testConfig.GetAll())
{
settings.Set(config.Key, config.Value);
}
}
return settings;
}
[Test]
public void Can_access_ConfigSettings_directly()
{
GetAppSettings();
using (var db = settings.DbFactory.Open())
{
var value = db.Scalar<string>(
"SELECT Value FROM ConfigSetting WHERE Id = @id", new { id = "RealKey" });
Assert.That(value, Is.EqualTo("This is a real value"));
}
}
[Test]
public void Can_preload_AppSettings()
{
GetAppSettings();
var allSettings = settings.GetAll();
var cachedSettings = new DictionarySettings(allSettings);
Assert.That(cachedSettings.Get("RealKey"), Is.EqualTo("This is a real value"));
}
[Test]
public void GetString_returns_null_On_Nonexistent_Key()
{
var appSettings = GetAppSettings();
var value = appSettings.GetString("GarbageKey");
Assert.IsNull(value);
}
[Test]
public void GetList_returns_emtpy_list_On_Null_Key()
{
var appSettings = GetAppSettings();
var result = appSettings.GetList("GarbageKey");
Assert.That(result.Count, Is.EqualTo(0));
}
[Test]
public void Does_GetOrCreate_New_Value()
{
var appSettings = (OrmLiteAppSettings)GetAppSettings();
var i = 0;
var key = "key";
var result = appSettings.GetOrCreate(key, () => key + ++i);
Assert.That(result, Is.EqualTo("key1"));
result = appSettings.GetOrCreate(key, () => key + ++i);
Assert.That(result, Is.EqualTo("key1"));
}
}
public class DictionarySettingsTest : AppSettingsTest
{
[Test]
public void GetRequiredString_Throws_Exception_On_Nonexistent_Key()
{
var appSettings = GetAppSettings();
try
{
appSettings.GetRequiredString("GarbageKey");
Assert.Fail("GetString did not throw a ConfigurationErrorsException");
}
catch (ConfigurationErrorsException ex)
{
Assert.That(ex.Message.Contains("GarbageKey"));
}
}
[Test]
public void Does_work_with_ParseKeyValueText()
{
var textFile = @"
EmptyKey
RealKey This is a real value
ListKey A,B,C,D,E
IntKey 42
DictionaryKey A:1,B:2,C:3,D:4,E:5
ObjectKey {SomeSetting:Test,SomeOtherSetting:12,FinalSetting:Final}";
var settings = textFile.ParseKeyValueText();
var appSettings = new DictionarySettings(settings);
Assert.That(appSettings.Get("EmptyKey"), Is.EqualTo(""));
Assert.That(appSettings.Get("RealKey"), Is.EqualTo("This is a real value"));
Assert.That(appSettings.Get("IntKey", defaultValue: 1), Is.EqualTo(42));
var list = appSettings.GetList("ListKey");
Assert.That(list, Has.Count.EqualTo(5));
Assert.That(list, Is.EqualTo(new List<string> { "A", "B", "C", "D", "E" }));
var map = appSettings.GetDictionary("DictionaryKey");
Assert.That(map, Has.Count.EqualTo(5));
Assert.That(map.Keys, Is.EqualTo(new List<string> { "A", "B", "C", "D", "E" }));
Assert.That(map.Values, Is.EqualTo(new List<string> { "1", "2", "3", "4", "5" }));
var value = appSettings.Get("ObjectKey", new SimpleAppSettings());
Assert.That(value, Is.Not.Null);
Assert.That(value.FinalSetting, Is.EqualTo("Final"));
Assert.That(value.SomeOtherSetting, Is.EqualTo(12));
Assert.That(value.SomeSetting, Is.EqualTo("Test"));
}
[Test]
public void Does_parse_byte_array_as_Base64()
{
var authKey = AesUtils.CreateKey();
var appSettings = new DictionarySettings(new Dictionary<string, string>
{
{ "AuthKey", Convert.ToBase64String(authKey) }
});
Assert.That(appSettings.Get<byte[]>("AuthKey"), Is.EquivalentTo(authKey));
}
}
public abstract class AppSettingsTest
{
public virtual AppSettingsBase GetAppSettings()
{
return new DictionarySettings(GetConfigDictionary())
{
ParsingStrategy = null,
};
}
public virtual Dictionary<string, string> GetConfigDictionary()
{
return new Dictionary<string, string>
{
{"NullableKey", null},
{"EmptyKey", string.Empty},
{"RealKey", "This is a real value"},
{"ListKey", "A,B,C,D,E"},
{"IntKey", "42"},
{"BadIntegerKey", "This is not an integer"},
{"DictionaryKey", "A:1,B:2,C:3,D:4,E:5"},
{"BadDictionaryKey", "A1,B:"},
{"ObjectNoLineFeed", "{SomeSetting:Test,SomeOtherSetting:12,FinalSetting:Final}"},
{"ObjectWithLineFeed", "{SomeSetting:Test,\r\nSomeOtherSetting:12,\r\nFinalSetting:Final}"},
};
}
[Test]
public void GetNullable_String_Returns_Null()
{
var appSettings = GetAppSettings();
var value = appSettings.GetNullableString("NullableKey");
Assert.That(value, Is.Null);
}
[Test]
public void GetString_Returns_Value()
{
var appSettings = GetAppSettings();
var value = appSettings.GetString("RealKey");
Assert.That(value, Is.EqualTo("This is a real value"));
}
[Test]
public void Get_Returns_Default_Value_On_Null_Key()
{
var appSettings = GetAppSettings();
var value = appSettings.Get("NullableKey", "default");
Assert.That(value, Is.EqualTo("default"));
}
[Test]
public void Get_Casts_To_Specified_Type()
{
var appSettings = GetAppSettings();
var value = appSettings.Get<int>("IntKey", 1);
Assert.That(value, Is.EqualTo(42));
}
[Test]
public void Get_Throws_Exception_On_Bad_Value()
{
var appSettings = GetAppSettings();
try
{
appSettings.Get<int>("BadIntegerKey", 1);
Assert.Fail("Get did not throw a ConfigurationErrorsException");
}
catch (ConfigurationErrorsException ex)
{
Assert.That(ex.Message.Contains("BadIntegerKey"));
}
}
[Test]
public void GetList_Parses_List_From_Setting()
{
var appSettings = GetAppSettings();
var value = appSettings.GetList("ListKey");
Assert.That(value, Has.Count.EqualTo(5));
Assert.That(value, Is.EqualTo(new List<string> { "A", "B", "C", "D", "E" }));
}
[Test]
public void GetDictionary_Parses_Dictionary_From_Setting()
{
var appSettings = GetAppSettings();
var value = appSettings.GetDictionary("DictionaryKey");
Assert.That(value, Has.Count.EqualTo(5));
Assert.That(value.Keys, Is.EqualTo(new List<string> { "A", "B", "C", "D", "E" }));
Assert.That(value.Values, Is.EqualTo(new List<string> { "1", "2", "3", "4", "5" }));
}
[Test]
public void GetDictionary_Throws_Exception_On_Null_Key()
{
var appSettings = GetAppSettings();
try
{
appSettings.GetDictionary("GarbageKey");
Assert.Fail("GetDictionary did not throw a ConfigurationErrorsException");
}
catch (ConfigurationErrorsException ex)
{
Assert.That(ex.Message.Contains("GarbageKey"));
}
}
[Test]
public void GetDictionary_Throws_Exception_On_Bad_Value()
{
var appSettings = GetAppSettings();
try
{
appSettings.GetDictionary("BadDictionaryKey");
Assert.Fail("GetDictionary did not throw a ConfigurationErrorsException");
}
catch (ConfigurationErrorsException ex)
{
Assert.That(ex.Message.Contains("BadDictionaryKey"));
}
}
[Test]
public void Get_Returns_ObjectNoLineFeed()
{
var appSettings = GetAppSettings();
appSettings.ParsingStrategy = AppSettingsStrategy.CollapseNewLines;
var value = appSettings.Get("ObjectNoLineFeed", new SimpleAppSettings());
Assert.That(value, Is.Not.Null);
Assert.That(value.FinalSetting, Is.EqualTo("Final"));
Assert.That(value.SomeOtherSetting, Is.EqualTo(12));
Assert.That(value.SomeSetting, Is.EqualTo("Test"));
value = appSettings.Get<SimpleAppSettings>("ObjectNoLineFeed");
Assert.That(value, Is.Not.Null);
Assert.That(value.FinalSetting, Is.EqualTo("Final"));
Assert.That(value.SomeOtherSetting, Is.EqualTo(12));
Assert.That(value.SomeSetting, Is.EqualTo("Test"));
}
[Test]
public void Get_Returns_ObjectWithLineFeed()
{
var appSettings = GetAppSettings();
appSettings.ParsingStrategy = AppSettingsStrategy.CollapseNewLines;
var value = appSettings.Get("ObjectWithLineFeed", new SimpleAppSettings());
Assert.That(value, Is.Not.Null);
Assert.That(value.FinalSetting, Is.EqualTo("Final"));
Assert.That(value.SomeOtherSetting, Is.EqualTo(12));
Assert.That(value.SomeSetting, Is.EqualTo("Test"));
value = appSettings.Get<SimpleAppSettings>("ObjectWithLineFeed");
Assert.That(value, Is.Not.Null);
Assert.That(value.FinalSetting, Is.EqualTo("Final"));
Assert.That(value.SomeOtherSetting, Is.EqualTo(12));
Assert.That(value.SomeSetting, Is.EqualTo("Test"));
}
[Test]
public void Can_write_to_AppSettings()
{
var appSettings = GetAppSettings();
var value = appSettings.Get("IntKey", 0);
Assert.That(value, Is.EqualTo(42));
appSettings.Set("IntKey", 99);
value = appSettings.Get("IntKey", 0);
Assert.That(value, Is.EqualTo(99));
}
public class SimpleAppSettings
{
public string SomeSetting { get; set; }
public int SomeOtherSetting { get; set; }
public string FinalSetting { get; set; }
}
[Test]
public void Can_get_all_keys()
{
var appSettings = GetAppSettings();
var allKeys = appSettings.GetAllKeys();
allKeys.Remove("servicestack:license");
Assert.That(allKeys, Is.EquivalentTo(GetConfigDictionary().Keys));
}
[Test]
public void Can_search_all_keys()
{
var appSettings = GetAppSettings();
var badKeys = appSettings.GetAllKeys().Where(x => x.Matches("Bad*"));
Assert.That(badKeys, Is.EquivalentTo(new[] { "BadIntegerKey", "BadDictionaryKey" }));
}
}
}
#endif
| 33.673709
| 109
| 0.544998
|
[
"Apache-2.0"
] |
BruceCowan-AI/ServiceStack
|
tests/ServiceStack.Common.Tests/Configuration/AppSettingsTests.cs
| 13,922
|
C#
|
namespace UAssetAPI.Kismet.Bytecode.Expressions
{
/// <summary>
/// A single Kismet bytecode instruction, corresponding to the <see cref="EExprToken.EX_NameConst"/> instruction.
/// </summary>
public class EX_NameConst : KismetExpression<FName>
{
/// <summary>
/// The token of this expression.
/// </summary>
public override EExprToken Token { get { return EExprToken.EX_NameConst; } }
public EX_NameConst()
{
}
/// <summary>
/// Reads out the expression from a BinaryReader.
/// </summary>
/// <param name="reader">The BinaryReader to read from.</param>
public override void Read(AssetBinaryReader reader)
{
Value = reader.XFERNAME();
}
/// <summary>
/// Writes the expression to a BinaryWriter.
/// </summary>
/// <param name="writer">The BinaryWriter to write from.</param>
/// <returns>The iCode offset of the data that was written.</returns>
public override int Write(AssetBinaryWriter writer)
{
return writer.XFERNAME(Value);
}
}
}
| 30.736842
| 117
| 0.58476
|
[
"MIT"
] |
DarthPointer/UAssetAPI
|
UAssetAPI/Kismet/Bytecode/Expressions/EX_NameConst.cs
| 1,170
|
C#
|
using FluentAssertions;
using Xunit;
namespace StrEnum.UnitTests.Parsing;
public class TryParseTests
{
public class Sport : StringEnum<Sport>
{
public static readonly Sport TrailRunning = Define("TRAIL_RUNNING");
}
[Theory]
[InlineData("TrailRunning", false)]
[InlineData("TRAIL_RUNNING", false)]
[InlineData("trailrunning", true)]
[InlineData("trail_running", true)]
public void TryParse_GivenAMatchingMemberByNameOrValue_ShouldFindThatMemberAndReturnTrue(
string nameOrValue, bool ignoreCase)
{
var parsed = Sport.TryParse(nameOrValue, ignoreCase, out var trailRunning);
parsed.Should().BeTrue();
trailRunning.Should().Be(Sport.TrailRunning);
}
[Fact]
public void TryParse_GivenAValueThatDoesntMatchAMember_ShouldReturnFalseAndSetMemberToNull()
{
var trailRunning = Sport.TrailRunning;
var parsed = Sport.TryParse("TRAIL", true, out trailRunning);
parsed.Should().BeFalse();
trailRunning.Should().BeNull();
}
}
| 28.432432
| 96
| 0.697719
|
[
"MIT"
] |
StrEnum/StrEnum
|
test/StrEnum.UnitTests/Parsing/TryParseTests.cs
| 1,054
|
C#
|
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using sc = System.Collections;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Billing.V1
{
/// <summary>Settings for <see cref="CloudCatalogClient"/> instances.</summary>
public sealed partial class CloudCatalogSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="CloudCatalogSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="CloudCatalogSettings"/>.</returns>
public static CloudCatalogSettings GetDefault() => new CloudCatalogSettings();
/// <summary>Constructs a new <see cref="CloudCatalogSettings"/> object with default settings.</summary>
public CloudCatalogSettings()
{
}
private CloudCatalogSettings(CloudCatalogSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
ListServicesSettings = existing.ListServicesSettings;
ListSkusSettings = existing.ListSkusSettings;
OnCopy(existing);
}
partial void OnCopy(CloudCatalogSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CloudCatalogClient.ListServices</c> and <c>CloudCatalogClient.ListServicesAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListServicesSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>CloudCatalogClient.ListSkus</c>
/// and <c>CloudCatalogClient.ListSkusAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListSkusSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="CloudCatalogSettings"/> object.</returns>
public CloudCatalogSettings Clone() => new CloudCatalogSettings(this);
}
/// <summary>
/// Builder class for <see cref="CloudCatalogClient"/> to provide simple configuration of credentials, endpoint etc.
/// </summary>
public sealed partial class CloudCatalogClientBuilder : gaxgrpc::ClientBuilderBase<CloudCatalogClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public CloudCatalogSettings Settings { get; set; }
partial void InterceptBuild(ref CloudCatalogClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CloudCatalogClient> task);
/// <summary>Builds the resulting client.</summary>
public override CloudCatalogClient Build()
{
CloudCatalogClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<CloudCatalogClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<CloudCatalogClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private CloudCatalogClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return CloudCatalogClient.Create(callInvoker, Settings);
}
private async stt::Task<CloudCatalogClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return CloudCatalogClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => CloudCatalogClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => CloudCatalogClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => CloudCatalogClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>CloudCatalog client wrapper, for convenient use.</summary>
/// <remarks>
/// A catalog of Google Cloud Platform services and SKUs.
/// Provides pricing information and metadata on Google Cloud Platform services
/// and SKUs.
/// </remarks>
public abstract partial class CloudCatalogClient
{
/// <summary>
/// The default endpoint for the CloudCatalog service, which is a host of "cloudbilling.googleapis.com" and a
/// port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "cloudbilling.googleapis.com:443";
/// <summary>The default CloudCatalog scopes.</summary>
/// <remarks>
/// The default CloudCatalog scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes);
/// <summary>
/// Asynchronously creates a <see cref="CloudCatalogClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="CloudCatalogClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="CloudCatalogClient"/>.</returns>
public static stt::Task<CloudCatalogClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new CloudCatalogClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="CloudCatalogClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="CloudCatalogClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="CloudCatalogClient"/>.</returns>
public static CloudCatalogClient Create() => new CloudCatalogClientBuilder().Build();
/// <summary>
/// Creates a <see cref="CloudCatalogClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="CloudCatalogSettings"/>.</param>
/// <returns>The created <see cref="CloudCatalogClient"/>.</returns>
internal static CloudCatalogClient Create(grpccore::CallInvoker callInvoker, CloudCatalogSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
CloudCatalog.CloudCatalogClient grpcClient = new CloudCatalog.CloudCatalogClient(callInvoker);
return new CloudCatalogClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC CloudCatalog client</summary>
public virtual CloudCatalog.CloudCatalogClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Lists all public cloud services.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Service"/> resources.</returns>
public virtual gax::PagedEnumerable<ListServicesResponse, Service> ListServices(ListServicesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists all public cloud services.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Service"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListServicesResponse, Service> ListServicesAsync(ListServicesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists all public cloud services.
/// </summary>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Service"/> resources.</returns>
public virtual gax::PagedEnumerable<ListServicesResponse, Service> ListServices(string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListServices(new ListServicesRequest
{
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Lists all public cloud services.
/// </summary>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Service"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListServicesResponse, Service> ListServicesAsync(string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListServicesAsync(new ListServicesRequest
{
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Lists all publicly available SKUs for a given cloud service.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Sku"/> resources.</returns>
public virtual gax::PagedEnumerable<ListSkusResponse, Sku> ListSkus(ListSkusRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists all publicly available SKUs for a given cloud service.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Sku"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListSkusResponse, Sku> ListSkusAsync(ListSkusRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists all publicly available SKUs for a given cloud service.
/// </summary>
/// <param name="parent">
/// Required. The name of the service.
/// Example: "services/DA34-426B-A397"
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Sku"/> resources.</returns>
public virtual gax::PagedEnumerable<ListSkusResponse, Sku> ListSkus(string parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListSkus(new ListSkusRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Lists all publicly available SKUs for a given cloud service.
/// </summary>
/// <param name="parent">
/// Required. The name of the service.
/// Example: "services/DA34-426B-A397"
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Sku"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListSkusResponse, Sku> ListSkusAsync(string parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListSkusAsync(new ListSkusRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Lists all publicly available SKUs for a given cloud service.
/// </summary>
/// <param name="parent">
/// Required. The name of the service.
/// Example: "services/DA34-426B-A397"
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Sku"/> resources.</returns>
public virtual gax::PagedEnumerable<ListSkusResponse, Sku> ListSkus(ServiceName parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListSkus(new ListSkusRequest
{
ParentAsServiceName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Lists all publicly available SKUs for a given cloud service.
/// </summary>
/// <param name="parent">
/// Required. The name of the service.
/// Example: "services/DA34-426B-A397"
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Sku"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListSkusResponse, Sku> ListSkusAsync(ServiceName parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListSkusAsync(new ListSkusRequest
{
ParentAsServiceName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
}
/// <summary>CloudCatalog client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// A catalog of Google Cloud Platform services and SKUs.
/// Provides pricing information and metadata on Google Cloud Platform services
/// and SKUs.
/// </remarks>
public sealed partial class CloudCatalogClientImpl : CloudCatalogClient
{
private readonly gaxgrpc::ApiCall<ListServicesRequest, ListServicesResponse> _callListServices;
private readonly gaxgrpc::ApiCall<ListSkusRequest, ListSkusResponse> _callListSkus;
/// <summary>
/// Constructs a client wrapper for the CloudCatalog service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="CloudCatalogSettings"/> used within this client.</param>
public CloudCatalogClientImpl(CloudCatalog.CloudCatalogClient grpcClient, CloudCatalogSettings settings)
{
GrpcClient = grpcClient;
CloudCatalogSettings effectiveSettings = settings ?? CloudCatalogSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callListServices = clientHelper.BuildApiCall<ListServicesRequest, ListServicesResponse>(grpcClient.ListServicesAsync, grpcClient.ListServices, effectiveSettings.ListServicesSettings);
Modify_ApiCall(ref _callListServices);
Modify_ListServicesApiCall(ref _callListServices);
_callListSkus = clientHelper.BuildApiCall<ListSkusRequest, ListSkusResponse>(grpcClient.ListSkusAsync, grpcClient.ListSkus, effectiveSettings.ListSkusSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callListSkus);
Modify_ListSkusApiCall(ref _callListSkus);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_ListServicesApiCall(ref gaxgrpc::ApiCall<ListServicesRequest, ListServicesResponse> call);
partial void Modify_ListSkusApiCall(ref gaxgrpc::ApiCall<ListSkusRequest, ListSkusResponse> call);
partial void OnConstruction(CloudCatalog.CloudCatalogClient grpcClient, CloudCatalogSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC CloudCatalog client</summary>
public override CloudCatalog.CloudCatalogClient GrpcClient { get; }
partial void Modify_ListServicesRequest(ref ListServicesRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_ListSkusRequest(ref ListSkusRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Lists all public cloud services.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Service"/> resources.</returns>
public override gax::PagedEnumerable<ListServicesResponse, Service> ListServices(ListServicesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListServicesRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListServicesRequest, ListServicesResponse, Service>(_callListServices, request, callSettings);
}
/// <summary>
/// Lists all public cloud services.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Service"/> resources.</returns>
public override gax::PagedAsyncEnumerable<ListServicesResponse, Service> ListServicesAsync(ListServicesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListServicesRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListServicesRequest, ListServicesResponse, Service>(_callListServices, request, callSettings);
}
/// <summary>
/// Lists all publicly available SKUs for a given cloud service.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Sku"/> resources.</returns>
public override gax::PagedEnumerable<ListSkusResponse, Sku> ListSkus(ListSkusRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListSkusRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListSkusRequest, ListSkusResponse, Sku>(_callListSkus, request, callSettings);
}
/// <summary>
/// Lists all publicly available SKUs for a given cloud service.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Sku"/> resources.</returns>
public override gax::PagedAsyncEnumerable<ListSkusResponse, Sku> ListSkusAsync(ListSkusRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListSkusRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListSkusRequest, ListSkusResponse, Sku>(_callListSkus, request, callSettings);
}
}
public partial class ListServicesRequest : gaxgrpc::IPageRequest
{
}
public partial class ListSkusRequest : gaxgrpc::IPageRequest
{
}
public partial class ListServicesResponse : gaxgrpc::IPageResponse<Service>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<Service> GetEnumerator() => Services.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
public partial class ListSkusResponse : gaxgrpc::IPageResponse<Sku>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<Sku> GetEnumerator() => Skus.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| 54.100386
| 232
| 0.659078
|
[
"Apache-2.0"
] |
garrettwong/google-cloud-dotnet
|
apis/Google.Cloud.Billing.V1/Google.Cloud.Billing.V1/CloudCatalogClient.g.cs
| 28,024
|
C#
|
// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
#pragma warning disable SA1402 // File may only contain a single class
using System;
using Xenko.Core;
using Xenko.Core.Collections;
using Xenko.Core.Mathematics;
using Xenko.Updater;
namespace Xenko.Animations
{
public abstract class AnimationCurveEvaluatorOptimizedGroup : AnimationCurveEvaluatorGroup
{
public abstract void Initialize(AnimationData animationData);
public abstract void SetChannelOffset(string name, int offset);
public static AnimationCurveEvaluatorOptimizedGroup Create<T>()
{
// Those types require interpolators
// TODO: Simple enough for now, but at some point we might want a mechanism to register them externally?
if (typeof(T) == typeof(float))
return new AnimationCurveEvaluatorOptimizedFloatGroup();
// TODO: Reintroduces explicit int path for now, since generic path does not work on iOS
if (typeof(T) == typeof(int))
return new AnimationCurveEvaluatorOptimizedIntGroup();
if (typeof(T) == typeof(Quaternion))
return new AnimationCurveEvaluatorOptimizedQuaternionGroup();
if (typeof(T) == typeof(Vector3))
return new AnimationCurveEvaluatorOptimizedVector3Group();
if (typeof(T) == typeof(Vector4))
return new AnimationCurveEvaluatorOptimizedVector4Group();
// Blittable
if (BlittableHelper.IsBlittable(typeof(T)))
return new AnimationCurveEvaluatorOptimizedBlittableGroup<T>();
// Objects
return new AnimationCurveEvaluatorOptimizedObjectGroup<T>();
}
}
public abstract class AnimationCurveEvaluatorOptimizedGroup<T> : AnimationCurveEvaluatorOptimizedGroup
{
private int animationSortedIndex;
protected AnimationData<T> animationData;
private CompressedTimeSpan currentTime;
protected FastListStruct<Channel> channels = new FastListStruct<Channel>(8);
public override Type ElementType => typeof(T);
public override void Initialize(AnimationData animationData)
{
Initialize((AnimationData<T>)animationData);
}
public void Initialize(AnimationData<T> animationData)
{
this.animationData = animationData;
foreach (var channel in animationData.AnimationInitialValues)
{
channels.Add(new Channel { InterpolationType = channel.InterpolationType, Offset = -1 });
}
// Setting infinite time means next time a rewind will be performed and initial values will be populated properly
currentTime = CompressedTimeSpan.MaxValue;
}
public override void Cleanup()
{
animationData = null;
channels.Clear();
}
public override void SetChannelOffset(string name, int offset)
{
var targetKeys = animationData.TargetKeys;
for (int i = 0; i < targetKeys.Length; ++i)
{
if (targetKeys[i] == name)
{
var channel = channels.Items[i];
channel.Offset = offset;
channels.Items[i] = channel;
break;
}
}
}
protected void SetTime(CompressedTimeSpan timeSpan)
{
// TODO: Add jump frames to do faster seeking.
// If user seek back, need to start from beginning
if (timeSpan < currentTime)
{
// Always start from beginning after a reset
animationSortedIndex = 0;
for (int channelIndex = 0; channelIndex < animationData.AnimationInitialValues.Length; ++channelIndex)
{
InitializeAnimation(ref channels.Items[channelIndex], ref animationData.AnimationInitialValues[channelIndex]);
}
}
currentTime = timeSpan;
var animationSortedValueCount = animationData.AnimationSortedValueCount;
var animationSortedValues = animationData.AnimationSortedValues;
if (animationSortedValueCount == 0)
return;
// Advance until requested time is reached
while (animationSortedIndex < animationSortedValueCount
&& animationSortedValues[animationSortedIndex / AnimationData.AnimationSortedValueBlock][animationSortedIndex % AnimationData.AnimationSortedValueBlock].RequiredTime <= currentTime)
{
//int channelIndex = animationSortedValues[animationSortedIndex / animationSortedValueBlock][animationSortedIndex % animationSortedValueBlock].ChannelIndex;
UpdateAnimation(ref animationSortedValues[animationSortedIndex / AnimationData.AnimationSortedValueBlock][animationSortedIndex % AnimationData.AnimationSortedValueBlock]);
animationSortedIndex++;
}
currentTime = timeSpan;
}
private static void InitializeAnimation(ref Channel animationChannel, ref AnimationInitialValues<T> animationValue)
{
animationChannel.ValuePrev = animationValue.Value1;
animationChannel.ValueStart = animationValue.Value1;
animationChannel.ValueEnd = animationValue.Value1;
animationChannel.ValueNext = animationValue.Value2;
}
private void UpdateAnimation(ref AnimationKeyValuePair<T> animationValue)
{
UpdateAnimation(ref channels.Items[animationValue.ChannelIndex], ref animationValue.Value);
}
private static void UpdateAnimation(ref Channel animationChannel, ref KeyFrameData<T> animationValue)
{
animationChannel.ValuePrev = animationChannel.ValueStart;
animationChannel.ValueStart = animationChannel.ValueEnd;
animationChannel.ValueEnd = animationChannel.ValueNext;
animationChannel.ValueNext = animationValue;
}
protected struct Channel
{
public int Offset;
public AnimationCurveInterpolationType InterpolationType;
public KeyFrameData<T> ValuePrev;
public KeyFrameData<T> ValueStart;
public KeyFrameData<T> ValueEnd;
public KeyFrameData<T> ValueNext;
}
}
public abstract class AnimationCurveEvaluatorOptimizedBlittableGroupBase<T> : AnimationCurveEvaluatorOptimizedGroup<T>
{
public override void Evaluate(CompressedTimeSpan newTime, IntPtr data, UpdateObjectData[] objects)
{
if (animationData == null)
return;
SetTime(newTime);
var channelCount = channels.Count;
var channelItems = channels.Items;
for (int i = 0; i < channelCount; ++i)
{
ProcessChannel(ref channelItems[i], newTime, data);
}
}
protected void ProcessChannel(ref Channel channel, CompressedTimeSpan currentTime, IntPtr data)
{
if (channel.Offset == -1)
return;
var startTime = channel.ValueStart.Time;
// TODO: Should we really do that?
// Sampling before start (should not really happen because we add a keyframe at TimeSpan.Zero, but let's keep it in case it changes later.
if (currentTime <= startTime)
{
Utilities.UnsafeWrite(data + channel.Offset, ref channel.ValueStart.Value);
return;
}
var endTime = channel.ValueEnd.Time;
// TODO: Should we really do that?
// Sampling after end
if (currentTime >= endTime)
{
Utilities.UnsafeWrite(data + channel.Offset, ref channel.ValueEnd.Value);
return;
}
float factor = (float)(currentTime.Ticks - startTime.Ticks) / (float)(endTime.Ticks - startTime.Ticks);
ProcessChannel(ref channel, currentTime, data, factor);
}
protected abstract void ProcessChannel(ref Channel channel, CompressedTimeSpan currentTime, IntPtr data, float factor);
}
public class AnimationCurveEvaluatorOptimizedObjectGroup<T> : AnimationCurveEvaluatorOptimizedGroup<T>
{
public override void Evaluate(CompressedTimeSpan newTime, IntPtr data, UpdateObjectData[] objects)
{
if (animationData == null)
return;
SetTime(newTime);
var channelCount = channels.Count;
var channelItems = channels.Items;
for (int i = 0; i < channelCount; ++i)
{
ProcessChannel(ref channelItems[i], newTime, objects);
}
}
protected void ProcessChannel(ref Channel channel, CompressedTimeSpan currentTime, UpdateObjectData[] objects)
{
if (channel.Offset == -1)
return;
var startTime = channel.ValueStart.Time;
// TODO: Should we really do that?
// Sampling before start (should not really happen because we add a keyframe at TimeSpan.Zero, but let's keep it in case it changes later.
if (currentTime <= startTime)
{
objects[channel.Offset].Value = channel.ValueStart.Value;
return;
}
// (This including sampling after end)
objects[channel.Offset].Value = channel.ValueStart.Value;
}
}
}
| 39.669355
| 201
| 0.626448
|
[
"MIT"
] |
Beefr/xenko
|
sources/engine/Xenko.Engine/Animations/AnimationCurveEvaluatorOptimizedGroup.cs
| 9,838
|
C#
|
namespace Kudu.Contracts.Settings
{
public static class SettingsKeys
{
/// <remarks>
/// Legacy value that is superseded by DeploymentBranch
/// </remarks>
internal const string Branch = "branch";
public const string DeploymentBranch = "deployment_branch";
public const string BuildArgs = "SCM_BUILD_ARGS";
public const string ScriptGeneratorArgs = "SCM_SCRIPT_GENERATOR_ARGS";
public const string TraceLevel = "SCM_TRACE_LEVEL";
public const string CommandIdleTimeout = "SCM_COMMAND_IDLE_TIMEOUT";
public const string LogStreamTimeout = "SCM_LOGSTREAM_TIMEOUT";
public const string GitUsername = "SCM_GIT_USERNAME";
public const string GitEmail = "SCM_GIT_EMAIL";
public const string ScmType = "ScmType";
public const string UseShallowClone = "SCM_USE_SHALLOW_CLONE";
public const string Command = "COMMAND";
public const string Project = "PROJECT";
public const string WorkerCommand = "WORKER_COMMAND";
public const string TargetPath = "SCM_TARGET_PATH";
public const string RepositoryPath = "SCM_REPOSITORY_PATH";
public const string NoRepository = "SCM_NO_REPOSITORY";
public const string WebSiteComputeMode = "WEBSITE_COMPUTE_MODE";
public const string WebSiteSiteMode = "WEBSITE_SITE_MODE";
public const string JobsInterval = "SCM_JOBS_INTERVAL";
public const string JobsIdleTimeoutInSeconds = "SCM_JOBS_IDLE_TIMEOUT";
public const string MaxJobRunsHistoryCount = "SCM_MAX_JOB_RUNS";
public const string PostDeploymentActionsDirectory = "SCM_POST_DEPLOYMENT_ACTIONS_PATH";
}
}
| 50.147059
| 96
| 0.710264
|
[
"Apache-2.0"
] |
silentworks/kudu
|
Kudu.Contracts/Settings/SettingsKeys.cs
| 1,707
|
C#
|
using Relo;
using SageBinaryData;
public static partial class Marshaler
{
public static unsafe void Marshal(Node node, FXListBehaviorEvent* objT, Tracker state)
{
if (node is null)
{
return;
}
Marshal(node.GetAttributeValue(nameof(FXListBehaviorEvent.Index), null), &objT->Index, state);
Marshal(node.GetAttributeValue(nameof(FXListBehaviorEvent.FX), null), &objT->FX, state);
Marshal(node.GetAttributeValue(nameof(FXListBehaviorEvent.MinThreshold), "0"), &objT->MinThreshold, state);
Marshal(node.GetAttributeValue(nameof(FXListBehaviorEvent.MaxThreshold), "0"), &objT->MaxThreshold, state);
Marshal(node.GetAttributeValue(nameof(FXListBehaviorEvent.OrientToObject), "true"), &objT->OrientToObject, state);
Marshal(node.GetAttributeValue(nameof(FXListBehaviorEvent.ForceUseDoFXObj), "false"), &objT->ForceUseDoFXObj, state);
Marshal(node.GetAttributeValue(nameof(FXListBehaviorEvent.Direction), "Default"), &objT->Direction, state);
}
public static unsafe void Marshal(Node node, FXListBehaviorModuleData* objT, Tracker state)
{
if (node is null)
{
return;
}
Marshal(node.GetChildNodes(nameof(FXListBehaviorModuleData.Event)), &objT->Event, state);
Marshal(node, (DieModuleData*)objT, state);
}
}
| 44.16129
| 125
| 0.693937
|
[
"MIT"
] |
Qibbi/BinaryAssetBuilder
|
source/BinaryAssetBuilder.XmlCompiler/Marshaler.ModulesFXListBehavior.cs
| 1,371
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.42000
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Reg.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.8.1.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;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("D:\\PetPictures")]
public string PetPictures {
get {
return ((string)(this["PetPictures"]));
}
set {
this["PetPictures"] = value;
}
}
}
}
| 40.384615
| 152
| 0.565714
|
[
"MIT"
] |
Mysa99/Advanced-GUI
|
Reg/Properties/Settings.Designer.cs
| 1,579
|
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.Globalization;
using System.Text;
using System.Xml;
namespace System.ServiceModel.Dispatcher
{
internal class EndpointAddressProcessor
{
// QName Attributes
internal static readonly string XsiNs = XmlUtil.XmlSerializerSchemaInstanceNamespace;
internal const string SerNs = "http://schemas.microsoft.com/2003/10/Serialization/";
internal const string TypeLN = "type";
internal const string ItemTypeLN = "ItemType";
internal const string FactoryTypeLN = "FactoryType";
internal static string GetComparableForm(StringBuilder builder, XmlReader reader)
{
List<Attr> attrSet = new List<Attr>();
int valueLength = -1;
while (!reader.EOF)
{
XmlNodeType type = reader.MoveToContent();
switch (type)
{
case XmlNodeType.Element:
CompleteValue(builder, valueLength);
valueLength = -1;
builder.Append("<");
AppendString(builder, reader.LocalName);
builder.Append(":");
AppendString(builder, reader.NamespaceURI);
builder.Append(" ");
// Scan attributes
attrSet.Clear();
if (reader.MoveToFirstAttribute())
{
do
{
// Ignore namespaces
if (reader.Prefix == "xmlns" || reader.Name == "xmlns")
{
continue;
}
if (reader.LocalName == AddressingStrings.IsReferenceParameter && reader.NamespaceURI == Addressing10Strings.Namespace)
{
continue; // ignore IsReferenceParameter
}
string val = reader.Value;
if ((reader.LocalName == TypeLN && reader.NamespaceURI == XsiNs) ||
(reader.NamespaceURI == SerNs && (reader.LocalName == ItemTypeLN || reader.LocalName == FactoryTypeLN)))
{
string local, ns;
XmlUtil.ParseQName(reader, val, out local, out ns);
val = local + "^" + local.Length.ToString(CultureInfo.InvariantCulture) + ":" + ns + "^" + ns.Length.ToString(CultureInfo.InvariantCulture);
}
else if (reader.LocalName == XD.UtilityDictionary.IdAttribute.Value && reader.NamespaceURI == XD.UtilityDictionary.Namespace.Value)
{
// ignore wsu:Id attributes added by security to sign the header
continue;
}
attrSet.Add(new Attr(reader.LocalName, reader.NamespaceURI, val));
} while (reader.MoveToNextAttribute());
}
reader.MoveToElement();
if (attrSet.Count > 0)
{
attrSet.Sort();
for (int i = 0; i < attrSet.Count; ++i)
{
Attr a = attrSet[i];
AppendString(builder, a.local);
builder.Append(":");
AppendString(builder, a.ns);
builder.Append("=\"");
AppendString(builder, a.val);
builder.Append("\" ");
}
}
if (reader.IsEmptyElement)
{
builder.Append("></>"); // Should be the same as an empty tag.
}
else
{
builder.Append(">");
}
break;
case XmlNodeType.EndElement:
CompleteValue(builder, valueLength);
valueLength = -1;
builder.Append("</>");
break;
// Need to escape CDATA values
case XmlNodeType.CDATA:
CompleteValue(builder, valueLength);
valueLength = -1;
builder.Append("<![CDATA[");
AppendString(builder, reader.Value);
builder.Append("]]>");
break;
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Text:
if (valueLength < 0)
{
valueLength = builder.Length;
}
builder.Append(reader.Value);
break;
default:
// Do nothing
break;
}
reader.Read();
}
return builder.ToString();
}
private static void AppendString(StringBuilder builder, string s)
{
builder.Append(s);
builder.Append("^");
builder.Append(s.Length.ToString(CultureInfo.InvariantCulture));
}
private static void CompleteValue(StringBuilder builder, int startLength)
{
if (startLength < 0)
{
return;
}
int len = builder.Length - startLength;
builder.Append("^");
builder.Append(len.ToString(CultureInfo.InvariantCulture));
}
internal class Attr : IComparable<Attr>
{
internal string local;
internal string ns;
internal string val;
private string _key;
internal Attr(string l, string ns, string v)
{
local = l;
this.ns = ns;
val = v;
_key = ns + ":" + l;
}
public int CompareTo(Attr a)
{
return string.Compare(_key, a._key, StringComparison.Ordinal);
}
}
}
}
| 39.022346
| 176
| 0.42219
|
[
"MIT"
] |
Bencargs/wcf
|
src/System.Private.ServiceModel/src/System/ServiceModel/Dispatcher/EndpointAddressProcessor.cs
| 6,985
|
C#
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace EmberKernel.Services.Configuration
{
public class OptionWriter<TOptions>
where TOptions : class, new()
{
private readonly PluginOptionsSetting Setting;
private readonly string Namespace;
public OptionWriter(PluginOptionsSetting setting, string @namespace)
{
this.Setting = setting;
this.Namespace = @namespace;
}
public async ValueTask SaveAsync(TOptions options, CancellationToken cancellationToken = default)
{
Dictionary<string, object> dict = default;
using (var readStream = File.OpenRead(Setting.PersistFilePath))
{
dict = await JsonSerializer.DeserializeAsync<Dictionary<string, object>>(readStream, cancellationToken: cancellationToken);
dict.Remove(Namespace);
dict.Add(Namespace, options);
}
if (dict == null)
{
throw new NullReferenceException("Read persisted configuration errored!");
}
var tempFile = Path.GetTempFileName();
using (var writeStream = File.OpenWrite(tempFile))
{
await JsonSerializer.SerializeAsync(writeStream, dict, cancellationToken: cancellationToken);
}
File.Copy(tempFile, Setting.PersistFilePath, overwrite: true);
}
}
}
| 35.906977
| 139
| 0.631477
|
[
"MIT"
] |
OsuSync/EmberTools
|
src/EmberKernel/Services/Configuration/OptionWriter.cs
| 1,546
|
C#
|
// This file is part of Silk.NET.
//
// You may modify and distribute Silk.NET under the terms
// of the MIT license. See the LICENSE file for details.
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Text;
using Silk.NET.Core;
using Silk.NET.Core.Native;
using Silk.NET.Core.Attributes;
using Silk.NET.Core.Contexts;
using Silk.NET.Core.Loader;
#pragma warning disable 1591
namespace Silk.NET.Direct3D11
{
[NativeName("Name", "D3D11_RASTERIZER_DESC1")]
public unsafe partial struct RasterizerDesc1
{
public RasterizerDesc1
(
FillMode? fillMode = null,
CullMode? cullMode = null,
int? frontCounterClockwise = null,
int? depthBias = null,
float? depthBiasClamp = null,
float? slopeScaledDepthBias = null,
int? depthClipEnable = null,
int? scissorEnable = null,
int? multisampleEnable = null,
int? antialiasedLineEnable = null,
uint? forcedSampleCount = null
) : this()
{
if (fillMode is not null)
{
FillMode = fillMode.Value;
}
if (cullMode is not null)
{
CullMode = cullMode.Value;
}
if (frontCounterClockwise is not null)
{
FrontCounterClockwise = frontCounterClockwise.Value;
}
if (depthBias is not null)
{
DepthBias = depthBias.Value;
}
if (depthBiasClamp is not null)
{
DepthBiasClamp = depthBiasClamp.Value;
}
if (slopeScaledDepthBias is not null)
{
SlopeScaledDepthBias = slopeScaledDepthBias.Value;
}
if (depthClipEnable is not null)
{
DepthClipEnable = depthClipEnable.Value;
}
if (scissorEnable is not null)
{
ScissorEnable = scissorEnable.Value;
}
if (multisampleEnable is not null)
{
MultisampleEnable = multisampleEnable.Value;
}
if (antialiasedLineEnable is not null)
{
AntialiasedLineEnable = antialiasedLineEnable.Value;
}
if (forcedSampleCount is not null)
{
ForcedSampleCount = forcedSampleCount.Value;
}
}
[NativeName("Type", "D3D11_FILL_MODE")]
[NativeName("Type.Name", "D3D11_FILL_MODE")]
[NativeName("Name", "FillMode")]
public FillMode FillMode;
[NativeName("Type", "D3D11_CULL_MODE")]
[NativeName("Type.Name", "D3D11_CULL_MODE")]
[NativeName("Name", "CullMode")]
public CullMode CullMode;
[NativeName("Type", "BOOL")]
[NativeName("Type.Name", "BOOL")]
[NativeName("Name", "FrontCounterClockwise")]
public int FrontCounterClockwise;
[NativeName("Type", "INT")]
[NativeName("Type.Name", "INT")]
[NativeName("Name", "DepthBias")]
public int DepthBias;
[NativeName("Type", "FLOAT")]
[NativeName("Type.Name", "FLOAT")]
[NativeName("Name", "DepthBiasClamp")]
public float DepthBiasClamp;
[NativeName("Type", "FLOAT")]
[NativeName("Type.Name", "FLOAT")]
[NativeName("Name", "SlopeScaledDepthBias")]
public float SlopeScaledDepthBias;
[NativeName("Type", "BOOL")]
[NativeName("Type.Name", "BOOL")]
[NativeName("Name", "DepthClipEnable")]
public int DepthClipEnable;
[NativeName("Type", "BOOL")]
[NativeName("Type.Name", "BOOL")]
[NativeName("Name", "ScissorEnable")]
public int ScissorEnable;
[NativeName("Type", "BOOL")]
[NativeName("Type.Name", "BOOL")]
[NativeName("Name", "MultisampleEnable")]
public int MultisampleEnable;
[NativeName("Type", "BOOL")]
[NativeName("Type.Name", "BOOL")]
[NativeName("Name", "AntialiasedLineEnable")]
public int AntialiasedLineEnable;
[NativeName("Type", "UINT")]
[NativeName("Type.Name", "UINT")]
[NativeName("Name", "ForcedSampleCount")]
public uint ForcedSampleCount;
}
}
| 29.078947
| 68
| 0.557466
|
[
"MIT"
] |
ThomasMiz/Silk.NET
|
src/Microsoft/Silk.NET.Direct3D11/Structs/RasterizerDesc1.gen.cs
| 4,420
|
C#
|
using Microsoft.EntityFrameworkCore;
using System.Reflection;
using System.Text;
namespace Com.Atomatus.Bootstarter.Context
{
/// <summary>
/// Context connection for postgres database.
/// </summary>
internal sealed class ContextConnectionPostgres : ContextConnection
{
private const int DEFAULT_PORT = 5432;
private const int DEFAULT_CONNECTION_TIMEOUT_IN_SEC = 120;
public ContextConnectionPostgres(Builder builder) : base(builder) { }
protected override string GetConnectionString()
{
return new StringBuilder()
.Append("Server=").AppendOrElse(host, "localhost").Append(';')
.Append("Port=").AppendOrElse(port, DEFAULT_PORT).Append(';')
.Append("Database=").AppendOrThrow(database, "database name not set!").Append(';')
.AppendIf(HasUsername(), "User Id=", user, ';')
.AppendIf(HasPassword(), "Password=", password, ';')
.AppendIf(HasNotUsernameAndPassword() || !DotnetRunningInContainer, "Integrated Security=True;")
.Append("Timeout=").AppendOrElse(timeout, DEFAULT_CONNECTION_TIMEOUT_IN_SEC).Append(";")
.Append("Command Timeout=").AppendOrElse(commandTimeout, DEFAULT_CONNECTION_TIMEOUT_IN_SEC).Append(";")
.AppendIf(MinPoolSize(), "Min Pool Size=", minPoolSize, ';')
.AppendIf(MaxPoolSize(), "Max Pool Size=", maxPoolSize, ";Pooling=true;")
.AppendIf(HasIdleLifetime(), "Connection Idle Lifetime=", idleLifetime, ';')
.Append("ApplicationName=").AppendOrElse(applicationName, Assembly.GetEntryAssembly().GetName().Name).Append(';')
.ToString();
}
protected internal override DbContextOptionsBuilder Attach(DbContextOptionsBuilder options)
{
return options
.UseNpgsql(o => o.SetPostgresVersion(9, 6))
.UseNpgsql(this);
}
}
}
| 46.465116
| 129
| 0.627127
|
[
"Apache-2.0"
] |
atomatus/dot-net-boot-starter
|
Atomatus.Bootstarter/Com.Atomatus.Bootstarter.Postgres/ContextConnectionPostgres.cs
| 2,000
|
C#
|
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging.AzureAppServices;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
namespace ExdTech.ImageServer
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
// public static IHostBuilder CreateHostBuilder(string[] args) =>
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
//.ConfigureLogging(logging => logging.AddAzureWebAppDiagnostics())
//.ConfigureServices(serviceCollection => serviceCollection
// .Configure<AzureFileLoggerOptions>(options =>
// {
// options.FileName = "azure-diagnostics-";
// options.FileSizeLimit = 50 * 1024;
// options.RetainedFileCountLimit = 5;
// })
// .Configure<AzureBlobLoggerOptions>(options =>
// {
// options.BlobName = "log.txt";
// }))
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 37.216216
| 83
| 0.557734
|
[
"MIT"
] |
peterdongan/ExdTech.ImageServer
|
ExdTech.ImageServer.Api/Program.cs
| 1,377
|
C#
|
namespace Manga.WebApi.UseCases.Register
{
using System.Threading.Tasks;
using Manga.Application.Boundaries.Register;
using Manga.Domain.ValueObjects;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[Route("api/register/[controller]")]
public class CustomersController : Controller
{
private readonly IUseCase _registerUseCase;
private readonly Presenter _presenter;
public CustomersController(
IUseCase registerUseCase,
Presenter presenter)
{
_registerUseCase = registerUseCase;
_presenter = presenter;
}
/// <summary>
/// Register a new Customer
/// </summary>
[HttpPost]
public async Task<IActionResult> Post([FromBody] RegisterRequest request)
{
await _registerUseCase.Execute(new Input(
new SSN(request.SSN),
new Name(request.Name),
new Password(request.Password),
new PositiveAmount(request.InitialAmount)));
return _presenter.ViewModel;
}
}
}
| 30.184211
| 81
| 0.618134
|
[
"Apache-2.0"
] |
darshitachavda/Clean-Architecture-manga-pro
|
source/Manga.WebApi/UseCases/Register/CustomersController.cs
| 1,147
|
C#
|
using Q42.HueApi.Models;
using Q42.HueApi.Models.Groups;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Q42.HueApi.Interfaces
{
/// <summary>
/// Hue Client for interaction with the bridge
/// </summary>
public interface IHueClient :
IHueClient_Capabilities,
IHueClient_Config,
IHueClient_Groups,
IHueClient_Lights,
IHueClient_ResourceLinks,
IHueClient_Rules,
IHueClient_Scenes,
IHueClient_Schedules,
IHueClient_Sensors
{
}
}
| 21.481481
| 49
| 0.712069
|
[
"MIT"
] |
AngusMcIntyre/Q42.HueApi
|
src/Q42.HueApi/Interfaces/IHueClient.cs
| 580
|
C#
|
using ReactiveUI.Fody.Helpers;
using Ui.Wpf.Common;
using Ui.Wpf.Common.ViewModels;
namespace Kanban.Desktop.Settings
{
public class SettingsViewModel : ViewModelBase, ISettingsViewModel
{
public void Initialize(ViewRequest viewRequest)
{
}
public bool UseDynamicDimensionts { get; set; }
}
}
| 23.133333
| 70
| 0.680115
|
[
"MIT"
] |
gabbacode/Kanban.Desktop
|
Kanban.Desktop/Kanban.Desktop/Settings/SettingsViewModel.cs
| 349
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Community.OData.Linq
{
using System;
using System.ComponentModel;
using Community.OData.Linq.Builder;
/// <summary>
/// Provides extension methods for the <see cref="ODataConventionModelBuilder"/> class.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class ODataConventionModelBuilderExtensions
{
/// <summary>
/// Enable lower camel case with default <see cref="NameResolverOptions"/>
/// NameResolverOptions.ProcessReflectedPropertyNames |
/// NameResolverOptions.ProcessDataMemberAttributePropertyNames |
/// NameResolverOptions.ProcessExplicitPropertyNames.
/// </summary>
/// <param name="builder">The <see cref="ODataConventionModelBuilder"/> to be enabled with lower camel case.</param>
/// <returns>Returns itself so that multiple calls can be chained.</returns>
public static ODataConventionModelBuilder EnableLowerCamelCase(this ODataConventionModelBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException("builder");
}
return builder.EnableLowerCamelCase(
NameResolverOptions.ProcessReflectedPropertyNames |
NameResolverOptions.ProcessDataMemberAttributePropertyNames |
NameResolverOptions.ProcessExplicitPropertyNames);
}
/// <summary>
/// Enable lower camel case with given <see cref="NameResolverOptions"/>.
/// </summary>
/// <param name="builder">The <see cref="ODataConventionModelBuilder"/> to be enabled with lower camel case.</param>
/// <param name="options">The <see cref="NameResolverOptions"/> for the lower camel case.</param>
/// <returns>Returns itself so that multiple calls can be chained.</returns>
public static ODataConventionModelBuilder EnableLowerCamelCase(
this ODataConventionModelBuilder builder,
NameResolverOptions options)
{
if (builder == null)
{
throw new ArgumentNullException("builder");
}
builder.OnModelCreating += new LowerCamelCaser(options).ApplyLowerCamelCase;
return builder;
}
}
}
| 42.758621
| 124
| 0.656855
|
[
"MIT"
] |
IharYakimush/comminity-data-odata-linq
|
Community.Data.OData.Linq/ODataConventionModelBuilderExtensions.cs
| 2,482
|
C#
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ProductOfArrayExceptSelf")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ProductOfArrayExceptSelf")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[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("735E6DFF-8826-4607-A1BB-2DA4A1A6B173")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.457143
| 84
| 0.74656
|
[
"MIT"
] |
thenitro/leet-code-problems
|
2021/ProductOfArrayExceptSelf/ProductOfArrayExceptSelf/Properties/AssemblyInfo.cs
| 1,384
|
C#
|
namespace AirConditionerTesterSystem.Core
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Contracts;
using Exceptions;
using Models;
using Models.Contracts;
using Repositories;
using Utilities;
public class Controller : IController
{
private readonly IAirConditionerTesterSystemData data;
public Controller(IAirConditionerTesterSystemData data)
{
this.data = data;
}
public string RegisterStationaryAirConditioner(string manufacturer, string model, char energyEfficiencyRating, int powerUsage)
{
var stationaryAc = new StationaryAirConditioner(manufacturer, model, energyEfficiencyRating, powerUsage);
this.CheckForDuplicateEntry(stationaryAc);
this.data
.AirConditioners
.Add(manufacturer + model, stationaryAc);
return string.Format(Constants.RegisterMessage, stationaryAc.Model, stationaryAc.Manufacturer);
}
public string RegisterCarAirConditioner(string manufacturer, string model, int volumeCoverage)
{
var carAirConditioner = new CarAirConditioner(manufacturer, model, volumeCoverage);
this.CheckForDuplicateEntry(carAirConditioner);
this.data
.AirConditioners
.Add(manufacturer + model, carAirConditioner);
return string.Format(Constants.RegisterMessage, carAirConditioner.Model, carAirConditioner.Manufacturer);
}
public string RegisterPlaneAirConditioner(string manufacturer, string model, int volumeCoverage, int electricityUsed)
{
var planeAirConditioner = new PlaneAirConditioner(manufacturer, model, volumeCoverage, electricityUsed);
this.CheckForDuplicateEntry(planeAirConditioner);
this.data
.AirConditioners
.Add(manufacturer + model, planeAirConditioner);
return string.Format(Constants.RegisterMessage, planeAirConditioner.Model, planeAirConditioner.Manufacturer);
}
public string TestAirConditioner(string manufacturer, string model)
{
if (this.data.AirConditioners.ContainsKey(manufacturer + model))
{
var airConditioner = this.data.GetAirConditioner(manufacturer, model);
var mark = airConditioner.Test();
var report = new Report(airConditioner.Manufacturer, airConditioner.Model, mark);
if (!this.data.Reports.ContainsKey(manufacturer))
{
this.data.Reports.Add(manufacturer, new List<IReport>());
this.data.Reports[manufacturer].Add(report);
}
else
{
if (this.data.Reports[manufacturer].Any(r => r.Model == model))
{
return Constants.Duplicate;
}
else
{
this.data.Reports[manufacturer].Add(report);
}
}
return string.Format(Constants.TestMessage, model, manufacturer);
}
return Constants.NonExistant;
}
public string FindAirConditioner(string manufacturer, string model)
{
var airConditioner = this.data.GetAirConditioner(manufacturer, model);
return airConditioner?.ToString() ?? Constants.NonExistant;
}
public string FindReport(string manufacturer, string model)
{
var report = this.data.GetReport(manufacturer, model);
return report?.ToString() ?? Constants.NonExistant;
}
public string FindAllReportsByManufacturer(string manufacturer)
{
var report = this.data.GetReportsByManufacturer(manufacturer);
if (report == null)
{
return Constants.NoReports;
}
report = report
.OrderBy(x => x.Model)
.ToList();
var sb = new StringBuilder();
sb.AppendLine($"Reports from {manufacturer}:")
.Append(string.Join(Environment.NewLine, report));
return sb.ToString().TrimEnd();
}
public string Status()
{
var reports = this.data.GetReportsCount();
var airConditioners = (double)this.data.GetAirConditionerCount();
var percent = reports / airConditioners;
if (double.IsNaN(percent))
{
percent = 0d;
}
percent = percent * 100;
return string.Format(Constants.Status, percent);
}
private void CheckForDuplicateEntry(IAirConditioner airConditioner)
{
if (this.data.AirConditioners.ContainsKey(airConditioner.Manufacturer + airConditioner.Model))
{
throw new DuplicateEntryException(Constants.Duplicate);
}
}
}
}
| 35.689189
| 135
| 0.579326
|
[
"MIT"
] |
stoyanov7/SoftwareUniversity
|
C#Development/HighQualityCode/AirConditionerTesterSystem/AirConditionerTesterSystem.Core/Controller.cs
| 5,284
|
C#
|
using NServiceBus.AcceptanceTesting.Support;
using System.Threading.Tasks;
namespace NServiceBus.IntegrationTesting
{
public interface IHandleTestCompletion
{
Task OnTestCompleted(RunSummary summary);
}
}
| 20.636364
| 49
| 0.770925
|
[
"Apache-2.0"
] |
Tobias-08/NServiceBus.IntegrationTesting
|
src/NServiceBus.IntegrationTesting/IHandleTestCompletion.cs
| 229
|
C#
|
/***************************************************************************\
*
* File: XamlParser.cs
*
* Purpose: Class for compiling Xaml.
*
* History:
* 6/06/01: rogerg Created
* 5/28/03: peterost Ported to wcp
* 10/6/03: peterost Reorganized to remove DP - clr distinction
*
* Copyright (C) 2003 by Microsoft Corporation. All rights reserved.
*
\***************************************************************************/
using System;
using System.Xml;
using System.IO;
using System.Text;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Globalization;
using System.Security.Permissions;
using MS.Utility;
using System.Runtime.InteropServices;
using MS.Internal;
// Disabling 1634 and 1691:
// In order to avoid generating warnings about unknown message numbers and
// unknown pragmas when compiling C# source code with the C# compiler,
// you need to disable warnings 1634 and 1691. (Presharp Documentation)
#pragma warning disable 1634, 1691
#if PBTCOMPILER
namespace MS.Internal.Markup
#else
using System.Windows;
namespace System.Windows.Markup
#endif
{
#region enums
/// <summary>
/// Parser modes. indicates if the Xaml should be parsed [....] or async.
/// currently public so test can set these values.
/// </summary>
internal enum XamlParseMode
{
/// <summary>
/// Not initialized
/// </summary>
Uninitialized,
/// <summary>
/// [....]
/// </summary>
Synchronous,
/// <summary>
/// Async
/// </summary>
Asynchronous,
}
#endregion enums
/// <summary>
/// XamlParser class. This class is used internally
/// </summary>
internal class XamlParser
{
#if PBTCOMPILER
#region Constructors
/// <summary>
/// Constructor that takes a stream and creates an XmlCompatibilityReader on it.
/// </summary>
public XamlParser(
ParserContext parserContext,
BamlRecordWriter bamlWriter,
Stream xamlStream,
bool multipleRoots) : this(parserContext, bamlWriter,
new XmlTextReader(xamlStream,
multipleRoots ? XmlNodeType.Element : XmlNodeType.Document,
(XmlParserContext)parserContext) )
{
}
protected XamlParser(
ParserContext parserContext,
BamlRecordWriter bamlWriter,
XmlTextReader textReader) : this(parserContext, bamlWriter)
{
// When the XML 1.0 specification was authored, security was not a top concern, and as a result DTDs have the
// unfortunate capability of severe Denial of Service (DoS) attacks, typically through the use of an internal
// entity expansion technique. In System.Xml V2.0, in order to provide protection against DTD DoS attacks there
// is the capability of turning off DTD parsing through the use of the ProhibitDtd property.
textReader.ProhibitDtd = true;
XmlCompatibilityReader xcr = new XmlCompatibilityReader(textReader,
new IsXmlNamespaceSupportedCallback(IsXmlNamespaceSupported),
_predefinedNamespaces );
TokenReader = new XamlReaderHelper(this,parserContext,xcr);
}
protected XamlParser(
ParserContext parserContext,
BamlRecordWriter bamlWriter)
{
_parserContext = parserContext;
_bamlWriter = bamlWriter;
}
// Default constructor to aid in subclassing
protected XamlParser()
{
}
#endregion Constructors
#region PublicMethods
/// <summary>
/// Main method to Parse the XAML.
/// When in synchronous mode the entire file is parsed before
/// this method returns.
/// In asynchronous mode at least the root tag is parsed. This
/// is necessary for the way binders currently work.
/// </summary>
public void Parse()
{
// if parseMode hasn't been set then set it now to synchronous.
if (XamlParseMode == XamlParseMode.Uninitialized)
{
XamlParseMode = XamlParseMode.Synchronous;
}
_Parse();
}
/// <summary>
/// Main function called by the XamlCompiler on a Compile.
/// If singleRecordMode is true the Read returns after each item read.
/// </summary>
/// <returns>True if more nodes to read</returns>
// !! Review - now that have separate out into XamlReaderHelper
// review if still need all the virtuals or the caller of the TokenReader
// can dispatch as they feel appropriate.
public bool ReadXaml(bool singleRecordMode)
{
XamlNode xamlNode = null;
bool cleanup = !singleRecordMode;
bool done = false;
try // What do we do with Exceptions we catch on this thread?.
{
while (TokenReader.Read(ref xamlNode))
{
SetParserAction(xamlNode);
if (ParserAction == ParserAction.Normal)
{
// If processing of the xaml node determines that we are done,
// then stop now. This can happen if ProcessXamlNode is
// overridden (such as when processing styles) and the parsed
// block is finished, but the overall file is not. In that
// case exit this parser, but leave everything intact.
ProcessXamlNode(xamlNode, ref cleanup, ref done);
if (done)
{
break;
}
// return here in single record mode since we don't want
// to set the parser loop to Done.
if (singleRecordMode)
{
return true;
}
}
}
}
catch (Exception e)
{
if (CriticalExceptions.IsCriticalException(e))
{
throw;
}
else
{
if (e is XamlParseException)
{
throw;
}
// If the exception was a XamlParse exception on the other
// side of a Reflection Invoke, then just pull up the Parse exception.
if (e is TargetInvocationException && e.InnerException is XamlParseException)
{
throw e.InnerException;
}
int lineNumber = 0;
int linePosition = 0;
string newMessage = null;
if (e is XmlException)
{
XmlException xmlEx = (XmlException)e;
lineNumber = xmlEx.LineNumber;
linePosition = xmlEx.LinePosition;
newMessage = xmlEx.Message;
}
else
{
// generic exception, If have a xamlNode then use the
// nodes values for the line Numbers.
if (null != xamlNode)
{
lineNumber = xamlNode.LineNumber;
linePosition = xamlNode.LinePosition;
}
newMessage = e.Message + " " + SR.Get(SRID.ParserLineAndOffset,
lineNumber.ToString(CultureInfo.CurrentCulture),
linePosition.ToString(CultureInfo.CurrentCulture));
}
XamlParseException parseException = new XamlParseException(newMessage, lineNumber, linePosition, e);
ParseError(parseException);
// Recurse on error
cleanup = true;
throw parseException;
}
}
finally
{
// Perform cleanup only if we encountered a non-recoverable error, or
// we're finished reading the stream (EndDocument reached in single
// record mode, or end of stream reached in multi-record mode)
if (cleanup)
{
// Close the reader, which will close the underlying stream.
TokenReader.Close();
}
}
return false;
}
/// <summary>
/// Big switch to handle all the records.
/// </summary>
/// <param name="xamlNode"> Node received from TokenReader to process</param>
/// <param name="cleanup"> True if end of stream reached and document is
/// totally finished and should be closed </param>
/// <param name="done"> True if done processing and want to exit. Doesn't
/// necessarily mean document is finished (see cleanup) </param>
internal virtual void ProcessXamlNode(
XamlNode xamlNode,
ref bool cleanup,
ref bool done)
{
switch(xamlNode.TokenType)
{
case XamlNodeType.DocumentStart:
XamlDocumentStartNode xamlDocumentStartNode =
(XamlDocumentStartNode) xamlNode;
WriteDocumentStart(xamlDocumentStartNode);
break;
case XamlNodeType.DocumentEnd:
XamlDocumentEndNode xamlEndDocumentNode =
(XamlDocumentEndNode) xamlNode;
cleanup = true;
done = true;
WriteDocumentEnd(xamlEndDocumentNode);
break;
case XamlNodeType.ElementStart:
XamlElementStartNode xamlElementNode =
(XamlElementStartNode) xamlNode;
WriteElementStart(xamlElementNode);
break;
case XamlNodeType.ElementEnd:
XamlElementEndNode xamlEndElementNode =
(XamlElementEndNode) xamlNode;
WriteElementEnd(xamlEndElementNode);
break;
case XamlNodeType.UnknownTagStart:
XamlUnknownTagStartNode xamlUnknownTagStartNode =
(XamlUnknownTagStartNode) xamlNode;
WriteUnknownTagStart(xamlUnknownTagStartNode);
break;
case XamlNodeType.UnknownTagEnd:
XamlUnknownTagEndNode xamlUnknownTagEndNode =
(XamlUnknownTagEndNode) xamlNode;
WriteUnknownTagEnd(xamlUnknownTagEndNode);
break;
case XamlNodeType.XmlnsProperty:
XamlXmlnsPropertyNode xamlXmlnsPropertyNode =
(XamlXmlnsPropertyNode) xamlNode;
WriteNamespacePrefix(xamlXmlnsPropertyNode);
break;
case XamlNodeType.Property:
XamlPropertyNode xamlPropertyNode =
(XamlPropertyNode) xamlNode;
if (xamlPropertyNode.AttributeUsage == BamlAttributeUsage.RuntimeName)
{
_parserContext.XamlTypeMapper.ValidateNames(
xamlPropertyNode.Value,
xamlPropertyNode.LineNumber,
xamlPropertyNode.LinePosition);
}
WriteProperty(xamlPropertyNode);
break;
case XamlNodeType.PropertyWithExtension:
XamlPropertyWithExtensionNode xamlPropertyWithExtensionNode =
(XamlPropertyWithExtensionNode)xamlNode;
WritePropertyWithExtension(xamlPropertyWithExtensionNode);
break;
case XamlNodeType.PropertyWithType:
XamlPropertyWithTypeNode xamlPropertyWithTypeNode =
(XamlPropertyWithTypeNode) xamlNode;
WritePropertyWithType(xamlPropertyWithTypeNode);
break;
case XamlNodeType.UnknownAttribute:
XamlUnknownAttributeNode xamlUnknownAttributeNode =
(XamlUnknownAttributeNode) xamlNode;
WriteUnknownAttribute(xamlUnknownAttributeNode);
break;
case XamlNodeType.PropertyComplexStart:
XamlPropertyComplexStartNode xamlPropertyComplexStartNode =
(XamlPropertyComplexStartNode) xamlNode;
WritePropertyComplexStart(xamlPropertyComplexStartNode);
break;
case XamlNodeType.PropertyComplexEnd:
XamlPropertyComplexEndNode xamlPropertyComplexEndNode =
(XamlPropertyComplexEndNode) xamlNode;
WritePropertyComplexEnd(xamlPropertyComplexEndNode);
break;
case XamlNodeType.LiteralContent:
XamlLiteralContentNode xamlLiteralContentNode =
(XamlLiteralContentNode) xamlNode;
WriteLiteralContent(xamlLiteralContentNode);
break;
case XamlNodeType.Text:
XamlTextNode xamlTextNode =
(XamlTextNode) xamlNode;
WriteText(xamlTextNode);
break;
case XamlNodeType.ClrEvent:
XamlClrEventNode xamlClrEventNode =
(XamlClrEventNode) xamlNode;
WriteClrEvent(xamlClrEventNode);
break;
case XamlNodeType.PropertyArrayStart:
XamlPropertyArrayStartNode xamlPropertyArrayStartNode =
(XamlPropertyArrayStartNode) xamlNode;
WritePropertyArrayStart(xamlPropertyArrayStartNode);
break;
case XamlNodeType.PropertyArrayEnd:
XamlPropertyArrayEndNode xamlPropertyArrayEndNode =
(XamlPropertyArrayEndNode) xamlNode;
WritePropertyArrayEnd(xamlPropertyArrayEndNode);
break;
case XamlNodeType.PropertyIListStart:
XamlPropertyIListStartNode xamlPropertyIListStartNode =
(XamlPropertyIListStartNode) xamlNode;
WritePropertyIListStart(xamlPropertyIListStartNode);
break;
case XamlNodeType.PropertyIListEnd:
XamlPropertyIListEndNode xamlPropertyIListEndNode =
(XamlPropertyIListEndNode) xamlNode;
WritePropertyIListEnd(xamlPropertyIListEndNode);
break;
case XamlNodeType.PropertyIDictionaryStart:
XamlPropertyIDictionaryStartNode xamlPropertyIDictionaryStartNode =
(XamlPropertyIDictionaryStartNode) xamlNode;
WritePropertyIDictionaryStart(xamlPropertyIDictionaryStartNode);
break;
case XamlNodeType.PropertyIDictionaryEnd:
XamlPropertyIDictionaryEndNode xamlPropertyIDictionaryEndNode =
(XamlPropertyIDictionaryEndNode) xamlNode;
WritePropertyIDictionaryEnd(xamlPropertyIDictionaryEndNode);
break;
case XamlNodeType.DefTag:
XamlDefTagNode xamlDefTagNode =
(XamlDefTagNode) xamlNode;
WriteDefTag(xamlDefTagNode);
break;
case XamlNodeType.DefKeyTypeAttribute:
XamlDefAttributeKeyTypeNode xamlDefAttributeKeyTypeNode =
(XamlDefAttributeKeyTypeNode) xamlNode;
WriteDefAttributeKeyType(xamlDefAttributeKeyTypeNode);
break;
case XamlNodeType.DefAttribute:
XamlDefAttributeNode xamlDefAttributeNode =
(XamlDefAttributeNode) xamlNode;
if (xamlDefAttributeNode.AttributeUsage == BamlAttributeUsage.RuntimeName)
{
_parserContext.XamlTypeMapper.ValidateNames(
xamlDefAttributeNode.Value,
xamlDefAttributeNode.LineNumber,
xamlDefAttributeNode.LinePosition);
}
WriteDefAttributeCore(xamlDefAttributeNode);
break;
case XamlNodeType.PresentationOptionsAttribute:
XamlPresentationOptionsAttributeNode xamlPresentationOptionsAttributeNode =
(XamlPresentationOptionsAttributeNode) xamlNode;
WritePresentationOptionsAttribute(xamlPresentationOptionsAttributeNode);
break;
case XamlNodeType.PIMapping:
XamlPIMappingNode xamlPIMappingNode =
(XamlPIMappingNode) xamlNode;
WritePIMapping(xamlPIMappingNode);
break;
// The following tokens that are used primarily by the markup compiler
case XamlNodeType.EndAttributes:
XamlEndAttributesNode xamlEndAttributesNode =
(XamlEndAttributesNode) xamlNode;
// if first tag and haven't alredy set the ParseMode
// set it to synchronous.
if (0 == xamlEndAttributesNode.Depth)
{
if (XamlParseMode == XamlParseMode.Uninitialized)
{
XamlParseMode = XamlParseMode.Synchronous;
}
}
WriteEndAttributes(xamlEndAttributesNode);
break;
case XamlNodeType.KeyElementStart:
XamlKeyElementStartNode xamlKeyElementStartNode =
(XamlKeyElementStartNode) xamlNode;
WriteKeyElementStart(xamlKeyElementStartNode);
break;
case XamlNodeType.KeyElementEnd:
XamlKeyElementEndNode xamlKeyElementEndNode =
(XamlKeyElementEndNode) xamlNode;
WriteKeyElementEnd(xamlKeyElementEndNode);
break;
case XamlNodeType.ConstructorParametersEnd:
XamlConstructorParametersEndNode xamlConstructorParametersEndNode =
(XamlConstructorParametersEndNode) xamlNode;
WriteConstructorParametersEnd(xamlConstructorParametersEndNode);
break;
case XamlNodeType.ConstructorParametersStart:
XamlConstructorParametersStartNode xamlConstructorParametersStartNode =
(XamlConstructorParametersStartNode) xamlNode;
WriteConstructorParametersStart(xamlConstructorParametersStartNode);
break;
case XamlNodeType.ContentProperty:
XamlContentPropertyNode xamlContentPropertyNode =
(XamlContentPropertyNode)xamlNode;
WriteContentProperty(xamlContentPropertyNode);
break;
case XamlNodeType.ConstructorParameterType:
XamlConstructorParameterTypeNode xamlConstructorParameterTypeNode =
(XamlConstructorParameterTypeNode)xamlNode;
WriteConstructorParameterType(xamlConstructorParameterTypeNode);
break;
default:
Debug.Assert(false,"Unknown Xaml Token.");
break;
}
}
#endregion // PublicMethods
#region Virtuals
/// <summary>
/// Called when parsing begins
/// </summary>
public virtual void WriteDocumentStart(XamlDocumentStartNode XamlDocumentStartNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteDocumentStart(XamlDocumentStartNode);
}
}
/// <summary>
/// Called when parsing ends
/// </summary>
public virtual void WriteDocumentEnd(XamlDocumentEndNode xamlEndDocumentNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteDocumentEnd(xamlEndDocumentNode);
}
}
/// <summary>
/// Write Start of an Element, which is a tag of the form /<Classname />
/// </summary>
public virtual void WriteElementStart(XamlElementStartNode xamlElementStartNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteElementStart(xamlElementStartNode);
}
}
/// <summary>
/// Write start of an unknown tag
/// </summary>
public virtual void WriteUnknownTagStart(XamlUnknownTagStartNode xamlUnknownTagStartNode)
{
// The default action for unknown tags is throw an exception.
ThrowException(SRID.ParserUnknownTag ,
xamlUnknownTagStartNode.Value,
xamlUnknownTagStartNode.XmlNamespace,
xamlUnknownTagStartNode.LineNumber,
xamlUnknownTagStartNode.LinePosition);
}
/// <summary>
/// Write end of an unknown tag
/// </summary>
public virtual void WriteUnknownTagEnd(XamlUnknownTagEndNode xamlUnknownTagEndNode)
{
// The default action for unknown tags is throw an exception. This should never
// get here unless there is a coding error, since it would first hit
// WriteUnknownTagStart
ThrowException(SRID.ParserUnknownTag ,
"???",
xamlUnknownTagEndNode.LineNumber,
xamlUnknownTagEndNode.LinePosition);
}
/// <summary>
/// Write End Element
/// </summary>
public virtual void WriteElementEnd(XamlElementEndNode xamlElementEndNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteElementEnd(xamlElementEndNode);
}
}
/// <summary>
/// Called when parsing hits literal content.
/// </summary>
public virtual void WriteLiteralContent(XamlLiteralContentNode xamlLiteralContentNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteLiteralContent(xamlLiteralContentNode);
}
}
/// <summary>
/// Write Start Complex Property, where the tag is of the
/// form /<Classname.PropertyName/>
/// </summary>
public virtual void WritePropertyComplexStart(
XamlPropertyComplexStartNode xamlPropertyComplexStartNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WritePropertyComplexStart(xamlPropertyComplexStartNode);
}
}
/// <summary>
/// Write End Complex Property
/// </summary>
public virtual void WritePropertyComplexEnd(
XamlPropertyComplexEndNode xamlPropertyComplexEndNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WritePropertyComplexEnd(xamlPropertyComplexEndNode);
}
}
/// <summary>
/// Write Start element for a dictionary key section.
/// </summary>
public virtual void WriteKeyElementStart(
XamlElementStartNode xamlKeyElementStartNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteKeyElementStart(xamlKeyElementStartNode);
}
}
/// <summary>
/// Write End element for a dictionary key section
/// </summary>
public virtual void WriteKeyElementEnd(
XamlElementEndNode xamlKeyElementEndNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteKeyElementEnd(xamlKeyElementEndNode);
}
}
/// <summary>
/// Write unknown attribute
/// </summary>
public virtual void WriteUnknownAttribute(XamlUnknownAttributeNode xamlUnknownAttributeNode)
{
// The default action for unknown attributes is throw an exception.
ThrowException(SRID.ParserUnknownAttribute ,
xamlUnknownAttributeNode.Name,
xamlUnknownAttributeNode.XmlNamespace,
xamlUnknownAttributeNode.LineNumber,
xamlUnknownAttributeNode.LinePosition);
}
/// <summary>
/// Write a Property, which has the form in markup of property="value".
/// </summary>
/// <remarks>
/// Note that for DependencyProperties, the assemblyName, TypeFullName, PropIdName
/// refer to DependencyProperty field
/// that the property was found on. This may be different from the ownerType
/// of the propId if the property was registered as an alias so if the
/// callback is persisting we want to persist the information that the propId
/// was found on in case the alias is a private or internal field.
/// </remarks>
public virtual void WriteProperty(XamlPropertyNode xamlPropertyNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteProperty(xamlPropertyNode);
}
}
internal void WriteBaseProperty(XamlPropertyNode xamlPropertyNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.BaseWriteProperty(xamlPropertyNode);
}
}
/// <summary>
/// Write a Property, which has the form in markup of property="value".
/// </summary>
/// <remarks>
/// Note that for DependencyProperties, the assemblyName, TypeFullName, PropIdName
/// refer to DependencyProperty field
/// that the property was found on. This may be different from the ownerType
/// of the propId if the property was registered as an alias so if the
/// callback is persisting we want to persist the information that the propId
/// was found on in case the alias is a private or internal field.
/// </remarks>
public virtual void WritePropertyWithType(XamlPropertyWithTypeNode xamlPropertyNode)
{
if (BamlRecordWriter != null)
{
if (xamlPropertyNode.ValueElementType == null)
{
ThrowException(SRID.ParserNoType,
xamlPropertyNode.ValueTypeFullName,
xamlPropertyNode.LineNumber,
xamlPropertyNode.LinePosition);
}
BamlRecordWriter.WritePropertyWithType(xamlPropertyNode);
}
}
public virtual void WritePropertyWithExtension(XamlPropertyWithExtensionNode xamlPropertyWithExtensionNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WritePropertyWithExtension(xamlPropertyWithExtensionNode);
}
}
/// <summary>
/// Write out Text, currently don't keep track if originally CData or Text
/// </summary>
public virtual void WriteText(XamlTextNode xamlTextNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteText(xamlTextNode);
}
}
/// <summary>
/// Write a new namespacePrefix to NamespaceURI map
/// </summary>
public virtual void WriteNamespacePrefix(XamlXmlnsPropertyNode xamlXmlnsPropertyNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteNamespacePrefix(xamlXmlnsPropertyNode);
}
}
/// <summary>
/// Xml - Clr namespace mapping
/// </summary>
public virtual void WritePIMapping(XamlPIMappingNode xamlPIMappingNode)
{
// The only case when the assembly name can be empty is when there is a local assembly
// specified in the Mapping PI, but the compiler extension should have resolved it by
// now. So if we are still seeing an empty string here that means we in the pure xaml
// parsing scenario and should throw.
if (xamlPIMappingNode.AssemblyName.Length == 0)
{
ThrowException(SRID.ParserMapPIMissingKey, xamlPIMappingNode.LineNumber, xamlPIMappingNode.LinePosition);
}
if (BamlRecordWriter != null)
{
BamlRecordWriter.WritePIMapping(xamlPIMappingNode);
}
}
/// <summary>
/// Write out the Clr event.
/// </summary>
public virtual void WriteClrEvent(XamlClrEventNode xamlClrEventNode)
{
// Parser currently doesn't support hooking up Events directly from
// XAML so throw an exception. In the compile case this method
// is overriden.
if (null == ParserHooks)
{
ThrowException(SRID.ParserNoEvents,
xamlClrEventNode.LineNumber,
xamlClrEventNode.LinePosition);
}
else if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteClrEvent(xamlClrEventNode);
}
}
/// <summary>
/// Write Property Array Start
/// </summary>
public virtual void WritePropertyArrayStart(XamlPropertyArrayStartNode xamlPropertyArrayStartNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WritePropertyArrayStart(xamlPropertyArrayStartNode);
}
}
/// <summary>
/// Write Property Array End
/// </summary>
public virtual void WritePropertyArrayEnd(XamlPropertyArrayEndNode xamlPropertyArrayEndNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WritePropertyArrayEnd(xamlPropertyArrayEndNode);
}
}
/// <summary>
/// Write Property IList Start
/// </summary>
public virtual void WritePropertyIListStart(XamlPropertyIListStartNode xamlPropertyIListStartNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WritePropertyIListStart(xamlPropertyIListStartNode);
}
}
/// <summary>
/// Write Property IList End
/// </summary>
public virtual void WritePropertyIListEnd(XamlPropertyIListEndNode xamlPropertyIListEndNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WritePropertyIListEnd(xamlPropertyIListEndNode);
}
}
/// <summary>
/// Write Property IDictionary Start
/// </summary>
public virtual void WritePropertyIDictionaryStart(XamlPropertyIDictionaryStartNode xamlPropertyIDictionaryStartNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WritePropertyIDictionaryStart(xamlPropertyIDictionaryStartNode);
}
}
/// <summary>
/// Write Property IDictionary End
/// </summary>
public virtual void WritePropertyIDictionaryEnd(XamlPropertyIDictionaryEndNode xamlPropertyIDictionaryEndNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WritePropertyIDictionaryEnd(xamlPropertyIDictionaryEndNode);
}
}
/// <summary>
/// WriteEndAttributes occurs after the last attribute (property, complex property or
/// def record) is written. Note that if there are none of the above, then WriteEndAttributes
/// is not called for a normal start tag.
/// </summary>
public virtual void WriteEndAttributes(XamlEndAttributesNode xamlEndAttributesNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteEndAttributes(xamlEndAttributesNode);
}
}
/// <summary>
/// WriteDefTag occurs when a x:Whatever tag is encountered.
/// Superclasses must interprete this since the base class doesn't understand
/// any of them.
/// </summary>
public virtual void WriteDefTag(XamlDefTagNode xamlDefTagNode)
{
ThrowException(SRID.ParserDefTag,
xamlDefTagNode.Value,
xamlDefTagNode.LineNumber,
xamlDefTagNode.LinePosition);
}
/// <summary>
/// Write out a key to a dictionary that has been resolved at compile or parse
/// time to a Type object.
/// </summary>
public virtual void WriteDefAttributeKeyType(XamlDefAttributeKeyTypeNode xamlDefNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteDefAttributeKeyType(xamlDefNode);
}
}
/// <summary>
/// WriteDefAttribute when attributes of the form x:Whatever are encountered
/// </summary>
public virtual void WriteDefAttribute(XamlDefAttributeNode xamlDefAttributeNode)
{
string attributeValue = xamlDefAttributeNode.Value;
// There are several known def attributes, and these are checked for
// correctness by running the known type converters.
switch(xamlDefAttributeNode.Name)
{
case XamlReaderHelper.DefinitionSynchronousMode:
if (BamlRecordWriter != null)
{
if (xamlDefAttributeNode.Value == "Async")
{
ThrowException(SRID.ParserNoBamlAsync, "Async",
xamlDefAttributeNode.LineNumber,
xamlDefAttributeNode.LinePosition);
}
}
break;
case XamlReaderHelper.DefinitionAsyncRecords:
// Update the AsyncRecords and don't store this as a def attribute
ThrowException(SRID.ParserNoBamlAsync, xamlDefAttributeNode.Name,
xamlDefAttributeNode.LineNumber,
xamlDefAttributeNode.LinePosition);
break;
case XamlReaderHelper.DefinitionShared:
Boolean.Parse(attributeValue); // For validation only.
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteDefAttribute(xamlDefAttributeNode);
}
break;
case XamlReaderHelper.DefinitionUid:
case XamlReaderHelper.DefinitionRuntimeName:
//Error if x:Uid or x:Name are markup extensions
if (MarkupExtensionParser.LooksLikeAMarkupExtension(attributeValue))
{
string message = SR.Get(SRID.ParserBadUidOrNameME, attributeValue);
message += " ";
message += SR.Get(SRID.ParserLineAndOffset,
xamlDefAttributeNode.LineNumber.ToString(CultureInfo.CurrentCulture),
xamlDefAttributeNode.LinePosition.ToString(CultureInfo.CurrentCulture));
XamlParseException parseException = new XamlParseException(message,
xamlDefAttributeNode.LineNumber, xamlDefAttributeNode.LinePosition);
throw parseException;
}
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteDefAttribute(xamlDefAttributeNode);
}
break;
case XamlReaderHelper.DefinitionName:
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteDefAttribute(xamlDefAttributeNode);
}
break;
default:
string errorID;
errorID = SRID.ParserUnknownDefAttribute;
ThrowException(errorID,
xamlDefAttributeNode.Name,
xamlDefAttributeNode.LineNumber,
xamlDefAttributeNode.LinePosition);
break;
}
}
/// <summary>
/// Write attributes of the form PresentationOptions:Whatever to Baml
/// </summary>
public virtual void WritePresentationOptionsAttribute(XamlPresentationOptionsAttributeNode xamlPresentationOptionsAttributeNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WritePresentationOptionsAttribute(xamlPresentationOptionsAttributeNode);
}
}
/// <summary>
/// Write the start of a constructor parameter section
/// </summary>
public virtual void WriteConstructorParametersStart(XamlConstructorParametersStartNode xamlConstructorParametersStartNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteConstructorParametersStart(xamlConstructorParametersStartNode);
}
}
public virtual void WriteContentProperty(XamlContentPropertyNode xamlContentPropertyNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteContentProperty(xamlContentPropertyNode);
}
}
/// <summary>
/// Write the constructor parameter record where the parameter is a compile time
/// resolved Type object.
/// </summary>
public virtual void WriteConstructorParameterType(
XamlConstructorParameterTypeNode xamlConstructorParameterTypeNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteConstructorParameterType(xamlConstructorParameterTypeNode);
}
}
/// <summary>
/// Write the end of a constructor parameter section
/// </summary>
public virtual void WriteConstructorParametersEnd(XamlConstructorParametersEndNode xamlConstructorParametersEndNode)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteConstructorParametersEnd(xamlConstructorParametersEndNode);
}
}
/// <summary>
/// Can be used by ac to return the type of the element if a class attribute is
/// present. If want to override default Type because of class= attribute can do so here.
/// Should leave the XmlReader positioned at the Element so if read attributes
/// to determine type need to call XmlReader.MoveToElement()
/// </summary>
public virtual bool GetElementType(
XmlReader reader,
string localName,
string namespaceUri,
ref string assemblyName,
ref string typeFullName,
ref Type baseType,
ref Type serializerType)
{
bool result = false;
assemblyName = string.Empty;
typeFullName = string.Empty;
serializerType = null;
baseType = null;
// if no namespaceURI or local name don't bother
if (null == namespaceUri || null == localName)
{
return false;
}
TypeAndSerializer typeAndSerializer =
XamlTypeMapper.GetTypeAndSerializer(namespaceUri, localName, null);
if (typeAndSerializer != null &&
typeAndSerializer.ObjectType != null)
{
serializerType = typeAndSerializer.SerializerType;
baseType = typeAndSerializer.ObjectType;
typeFullName = baseType.FullName;
assemblyName = baseType.Assembly.FullName;
result = true;
Debug.Assert(null != assemblyName, "assembly name returned from GetBaseElement is null");
Debug.Assert(null != typeFullName, "Type name returned from GetBaseElement is null");
}
return result;
}
#endregion Virtuals
/// <summary>
/// Write a Connector Id for compiler.
/// </summary>
protected internal void WriteConnectionId(Int32 connectionId)
{
if (BamlRecordWriter != null)
{
BamlRecordWriter.WriteConnectionId(connectionId);
}
}
/// <summary>
/// A def attribute was encountered. Perform synchonous mode checking
/// prior to calling the virtual that may be overridden.
/// </summary>
void WriteDefAttributeCore(XamlDefAttributeNode xamlDefAttributeNode)
{
string attributeValue = xamlDefAttributeNode.Value;
switch(xamlDefAttributeNode.Name)
{
case XamlReaderHelper.DefinitionSynchronousMode:
XamlParseMode documentParseMode = XamlParseMode.Synchronous;
if (attributeValue.Equals("Async"))
{
documentParseMode = XamlParseMode.Asynchronous;
}
else if (attributeValue.Equals("[....]"))
{
documentParseMode = XamlParseMode.Synchronous;
}
else
{
ThrowException(SRID.ParserBadSyncMode,
xamlDefAttributeNode.LineNumber,
xamlDefAttributeNode.LinePosition );
}
// if we haven't initialized the the parseMode yet set it
if (XamlParseMode == XamlParseMode.Uninitialized)
{
// todo: for now hardcode the string. when finalized
// should add a TypeConverter.
XamlParseMode = documentParseMode;
}
break;
default:
break;
}
WriteDefAttribute(xamlDefAttributeNode);
}
#region Methods
// virtuals to override the default implementation. used by the compiler
// for internal virtuals review why not public as the others?
// Used when an exception is thrown.The default action is to shutdown the parser
// and throw the exception.
internal virtual void ParseError(XamlParseException e)
{
}
/// <summary>
/// Called when the parse was cancelled by the user.
/// </summary>
internal virtual void ParseCancelled()
{
}
/// <summary>
/// called when the parse has been completed successfully.
/// </summary>
internal virtual void ParseCompleted()
{
}
/// <summary>
/// Default parsing is to synchronously read all the xaml nodes
/// until done.
/// </summary>
internal virtual void _Parse()
{
ReadXaml(false /* want to parse the entire thing */);
}
/// <summary>
/// If there are ParserHooks, call it with the current xamlNode and perform
/// as directed by the callback.
/// </summary>
private void SetParserAction(XamlNode xamlNode)
{
// if no ParserHooks then process as normal
if (null == ParserHooks)
{
ParserAction = ParserAction.Normal;
return;
}
// if ParserHooks want to skip the current node and its children,
// check for end of scope where it asked to be skipped.
if (ParserAction == ParserAction.Skip)
{
if (xamlNode.Depth <= SkipActionDepthCount &&
xamlNode.TokenType == SkipActionToken)
{
// We found the end token at the correct depth. Reset the depth count
// so that in the next call we won't skip calling the ParserHooks. Don't
// reset the ParserAction since we want to skip this end token.
SkipActionDepthCount = -1;
SkipActionToken = XamlNodeType.Unknown;
return;
}
else if (SkipActionDepthCount >= 0)
{
return;
}
}
// If we get to here, the ParserHooks want to be called.
ParserAction = ParserHooks.LoadNode(xamlNode);
// if the ParserHooks want to skip the current node and its children then
// set the callback depth so that we'll know when to start processing again.
if (ParserAction == ParserAction.Skip)
{
// For tokens with no scope (eg = attributes), don't set the depth so
// that we will only skip once
Debug.Assert(SkipActionDepthCount == -1);
int tokenIndex = ((IList)XamlNode.ScopeStartTokens).IndexOf(xamlNode.TokenType);
if (tokenIndex != -1)
{
SkipActionDepthCount = xamlNode.Depth;
SkipActionToken = XamlNode.ScopeEndTokens[tokenIndex];
}
}
}
// Return true if the passed namespace is known, meaning that it maps
// to a set of assemblies and clr namespaces
internal bool IsXmlNamespaceSupported(string xmlNamespace, out string newXmlNamespace)
{
newXmlNamespace = null;
if (xmlNamespace.StartsWith(XamlReaderHelper.MappingProtocol, StringComparison.Ordinal))
{
return true;
}
else if (xmlNamespace == XamlReaderHelper.PresentationOptionsNamespaceURI)
{
// PresentationOptions is expected to be marked as 'ignorable' in most Xaml
// so that other Xaml parsers don't have to interpret it, but this parser
// does handle it to support it's Freeze attribute.
return true;
}
else
{
return XamlTypeMapper.IsXmlNamespaceKnown(xmlNamespace, out newXmlNamespace) ||
TokenReader.IsXmlDataIsland();
}
}
#endregion Methods
#region Properties
/// <summary>
/// TokenReader that is being used.
/// </summary>
internal XamlReaderHelper TokenReader
{
get { return _xamlTokenReader; }
set { _xamlTokenReader = value; }
}
/// <summary>
/// ParserHooks implementation that any parse time callbacks
/// should be called on.
/// </summary>
internal ParserHooks ParserHooks
{
get { return _parserHooks; }
set { _parserHooks = value; }
}
// Set the depth count for how deep we are within
// a ParserAction.Skip reference.
int SkipActionDepthCount
{
get { return _skipActionDepthCount; }
set { _skipActionDepthCount = value; }
}
// Set and get the token to watch for when skipping a
// section of a xaml file
XamlNodeType SkipActionToken
{
get { return _skipActionToken; }
set { _skipActionToken = value; }
}
// set the operation mode of the parser as determined
// by attached ParserHooks
ParserAction ParserAction
{
get { return _parserAction; }
set { _parserAction = value; }
}
/// <summary>
/// Instance of the XamlTypeMapper
/// </summary>
internal XamlTypeMapper XamlTypeMapper
{
get { return _parserContext.XamlTypeMapper; }
}
/// <summary>
/// Instance of the BamlMapTable
/// </summary>
internal BamlMapTable MapTable
{
get { return _parserContext.MapTable; }
}
/// <summary>
/// BamlRecordWriter being used by the Parser
/// </summary>
public BamlRecordWriter BamlRecordWriter
{
get { return _bamlWriter; }
set
{
Debug.Assert(null == _bamlWriter || null == value, "XamlParser already had a bamlWriter");
_bamlWriter = value;
}
}
/// <summary>
/// ParseMode the Parser is in.
/// </summary>
internal XamlParseMode XamlParseMode
{
get { return _xamlParseMode; }
set { _xamlParseMode = value; }
}
/// <summary>
/// Parser context
/// </summary>
internal ParserContext ParserContext
{
get { return _parserContext; }
set { _parserContext = value; }
}
internal virtual bool CanResolveLocalAssemblies()
{
return false;
}
// Used to determine if strict or loose parsing rules should be enforced. The TokenReader
// does some validations that are difficult for the XamlParser to do and in strict parsing
// mode the TokenReader should throw exceptions of standard Xaml rules are violated.
internal virtual bool StrictParsing
{
get { return true; }
}
#endregion Properties
#region Data
// private Data
XamlReaderHelper _xamlTokenReader;
ParserContext _parserContext; // todo, need this for the XamlTypeMapper/resolver.
XamlParseMode _xamlParseMode;
BamlRecordWriter _bamlWriter;
// ParserHooks related
ParserHooks _parserHooks;
ParserAction _parserAction = ParserAction.Normal;
int _skipActionDepthCount = -1; // skip mode depth count.
XamlNodeType _skipActionToken = XamlNodeType.Unknown;
static private string [] _predefinedNamespaces = new string [3] {
XamlReaderHelper.DefinitionNamespaceURI,
XamlReaderHelper.DefaultNamespaceURI,
XamlReaderHelper.DefinitionMetroNamespaceURI
};
#endregion Data
#endif
// helper method called to throw an exception.
// todo: update exception with lineNumbers from Node.
internal static void ThrowException(string id, int lineNumber, int linePosition)
{
string message = SR.Get(id);
ThrowExceptionWithLine(message, lineNumber, linePosition);
}
// helper method called to throw an exception.
internal static void ThrowException(string id, string value, int lineNumber, int linePosition)
{
string message = SR.Get(id, value);
ThrowExceptionWithLine(message, lineNumber, linePosition);
}
// helper method called to throw an exception.
internal static void ThrowException(string id, string value1, string value2, int lineNumber, int linePosition)
{
string message = SR.Get(id, value1, value2);
ThrowExceptionWithLine(message, lineNumber, linePosition);
}
internal static void ThrowException(string id, string value1, string value2, string value3, int lineNumber, int linePosition)
{
string message = SR.Get(id, value1, value2, value3);
ThrowExceptionWithLine(message, lineNumber, linePosition);
}
internal static void ThrowException(string id, string value1, string value2, string value3, string value4, int lineNumber, int linePosition)
{
string message = SR.Get(id, value1, value2, value3, value4);
ThrowExceptionWithLine(message, lineNumber, linePosition);
}
private static void ThrowExceptionWithLine(string message, int lineNumber, int linePosition)
{
message += " ";
message += SR.Get(SRID.ParserLineAndOffset,
lineNumber.ToString(CultureInfo.CurrentCulture),
linePosition.ToString(CultureInfo.CurrentCulture));
XamlParseException parseException = new XamlParseException(message,
lineNumber, linePosition);
throw parseException;
}
}
}
| 37.356705
| 148
| 0.549483
|
[
"Apache-2.0"
] |
295007712/295007712.github.io
|
sourceCode/dotNet4.6/wpf/src/Framework/System/Windows/Markup/XamlParser.cs
| 54,877
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.Elastic.Models.Api20200701
{
using Microsoft.Azure.PowerShell.Cmdlets.Elastic.Runtime.PowerShell;
/// <summary>
/// A PowerShell PSTypeConverter to support converting to an instance of <see cref="OperationResult" />
/// </summary>
public partial class OperationResultTypeConverter : global::System.Management.Automation.PSTypeConverter
{
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>.
/// </returns>
public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue);
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="OperationResult"
/// /> type.</param>
/// <returns>
/// <c>true</c> if the instance could be converted to a <see cref="OperationResult" /> type, otherwise <c>false</c>
/// </returns>
public static bool CanConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return true;
}
global::System.Type type = sourceValue.GetType();
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
// we say yest to PSObjects
return true;
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
// we say yest to Hashtables/dictionaries
return true;
}
try
{
if (null != sourceValue.ToJsonString())
{
return true;
}
}
catch
{
// Not one of our objects
}
try
{
string text = sourceValue.ToString()?.Trim();
return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Elastic.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Elastic.Runtime.Json.JsonType.Object;
}
catch
{
// Doesn't look like it can be treated as JSON
}
return false;
}
/// <summary>
/// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>
/// </returns>
public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false;
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>
/// an instance of <see cref="OperationResult" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the value to convert into an instance of <see cref="OperationResult" />.</param>
/// <returns>
/// an instance of <see cref="OperationResult" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Elastic.Models.Api20200701.IOperationResult ConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return null;
}
global::System.Type type = sourceValue.GetType();
if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Elastic.Models.Api20200701.IOperationResult).IsAssignableFrom(type))
{
return sourceValue;
}
try
{
return OperationResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());;
}
catch
{
// Unable to use JSON pattern
}
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
return OperationResult.DeserializeFromPSObject(sourceValue);
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
return OperationResult.DeserializeFromDictionary(sourceValue);
}
return null;
}
/// <summary>NotImplemented -- this will return <c>null</c></summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>will always return <c>null</c>.</returns>
public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null;
}
}
| 51.591837
| 245
| 0.588476
|
[
"MIT"
] |
Agazoth/azure-powershell
|
src/Elastic/generated/api/Models/Api20200701/OperationResult.TypeConverter.cs
| 7,438
|
C#
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Threading.Tasks;
namespace Xamarin.Forms.Extended
{
public class InfiniteScrollCollection<T> : ObservableCollection<T>, IInfiniteScrollLoader, IInfiniteScrollLoading
{
private bool isLoadingMore;
public InfiniteScrollCollection()
{
}
public InfiniteScrollCollection(IEnumerable<T> collection)
: base(collection)
{
}
public Action OnBeforeLoadMore { get; set; }
public Action OnAfterLoadMore { get; set; }
public Action<Exception> OnError { get; set; }
public Func<bool> OnCanLoadMore { get; set; }
public Func<Task<IEnumerable<T>>> OnLoadMore { get; set; }
public virtual bool CanLoadMore => OnCanLoadMore?.Invoke() ?? true;
public bool IsLoadingMore
{
get => isLoadingMore;
private set
{
if (isLoadingMore != value)
{
isLoadingMore = value;
OnPropertyChanged(new PropertyChangedEventArgs(nameof(IsLoadingMore)));
LoadingMore?.Invoke(this, new LoadingMoreEventArgs(IsLoadingMore));
}
}
}
public event EventHandler<LoadingMoreEventArgs> LoadingMore;
public async Task LoadMoreAsync()
{
try
{
IsLoadingMore = true;
OnBeforeLoadMore?.Invoke();
var result = await OnLoadMore();
if (result != null)
{
AddRange(result);
}
}
catch (Exception ex) when (OnError != null)
{
OnError.Invoke(ex);
}
finally
{
IsLoadingMore = false;
OnAfterLoadMore?.Invoke();
}
}
public void AddRange(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
CheckReentrancy();
var startIndex = Count;
var changedItems = new List<T>(collection);
foreach (var i in changedItems)
Items.Add(i);
OnPropertyChanged(new PropertyChangedEventArgs("Count"));
OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, changedItems, startIndex));
}
}
}
| 22.197917
| 122
| 0.709057
|
[
"MIT"
] |
mattleibow/InfiniteScrolling
|
InfiniteScrolling/InfiniteScrollCollection.cs
| 2,133
|
C#
|
// Copyright (c) Dapplo and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Linq;
namespace Dapplo.Jira.Query
{
/// <summary>
/// A clause for simple values like container, macro and label
/// </summary>
public class SimpleValueClause : ISimpleValueClause
{
private readonly Clause _clause;
private bool _negate;
internal SimpleValueClause(Fields simpleField)
{
_clause = new Clause
{
Field = simpleField
};
}
/// <inheritDoc />
public ISimpleValueClause Not
{
get
{
_negate = !_negate;
return this;
}
}
/// <inheritDoc />
public IFinalClause Is(string value)
{
_clause.Operator = Operators.EqualTo;
_clause.Value = $"\"{value}\"";
if (_negate)
{
_clause.Negate();
}
return _clause;
}
/// <inheritDoc />
public IFinalClause In(params string[] values)
{
_clause.Operator = Operators.In;
_clause.Value = "(" + string.Join(", ", values.Select(value => $"\"{value}\"")) + ")";
if (_negate)
{
_clause.Negate();
}
return _clause;
}
}
}
| 19.610169
| 101
| 0.636992
|
[
"MIT"
] |
oldmansauls/Dapplo.Jira
|
src/Dapplo.Jira/Query/SimpleValueClause.cs
| 1,159
|
C#
|
using System;
using System.Threading.Tasks;
using Common.Log;
using Lykke.Snow.Mdm.Contracts.Models.Contracts;
using Lykke.Snow.Mdm.Contracts.Models.Events;
using MarginTrading.AssetService.Core.Caches;
using MarginTrading.AssetService.Core.Domain;
using MarginTrading.AssetService.Core.Handlers;
using MarginTrading.AssetService.Core.Services;
namespace MarginTrading.AssetService.Services.RabbitMq.Handlers
{
public class UnderlyingChangedHandler
{
private readonly IUnderlyingsCache _underlyingsCache;
private readonly ILegacyAssetsCacheUpdater _legacyAssetsCacheUpdater;
private readonly IProductsService _productsService;
private readonly IConvertService _convertService;
private readonly ILog _log;
public UnderlyingChangedHandler(
IUnderlyingsCache underlyingsCache,
ILegacyAssetsCacheUpdater legacyAssetsCacheUpdater,
IProductsService productsService,
IConvertService convertService,
ILog log)
{
_underlyingsCache = underlyingsCache;
_legacyAssetsCacheUpdater = legacyAssetsCacheUpdater;
_productsService = productsService;
_convertService = convertService;
_log = log;
}
public async Task Handle(UnderlyingChangedEvent e)
{
switch (e.ChangeType)
{
case ChangeType.Creation:
_underlyingsCache.AddOrUpdateByMdsCode(
_convertService.Convert<UnderlyingContract, UnderlyingsCacheModel>(e.NewValue));
break;
case ChangeType.Edition:
var model = _convertService.Convert<UnderlyingContract, UnderlyingsCacheModel>(e.NewValue);
await UpdateUnderlyingsCache(e, model);
await HandleMdsCodeChanged(e);
await _legacyAssetsCacheUpdater.HandleUnderlyingUpdated(e.OldValue.MdsCode, model, e.Timestamp);
break;
case ChangeType.Deletion:
_underlyingsCache.Remove(
_convertService.Convert<UnderlyingContract, UnderlyingsCacheModel>(e.OldValue));
break;
default:
throw new ArgumentOutOfRangeException();
}
}
private async Task UpdateUnderlyingsCache(UnderlyingChangedEvent e, UnderlyingsCacheModel model)
{
if (e.OldValue.MdsCode != e.NewValue.MdsCode)
{
_underlyingsCache.AddOrUpdateByChangedMdsCode(e.OldValue.MdsCode, model);
}
else
{
_underlyingsCache.AddOrUpdateByMdsCode(model);
}
}
private async Task HandleMdsCodeChanged(UnderlyingChangedEvent e)
{
if (e.OldValue.MdsCode != e.NewValue.MdsCode)
{
try
{
await _productsService.ChangeUnderlyingMdsCodeAsync(e.OldValue.MdsCode,
e.NewValue.MdsCode,
e.Username,
e.CorrelationId);
}
catch (Exception exception)
{
throw new Exception(
$"Cannot update products with underlying mds code {e.OldValue.MdsCode}: {exception.Message}",
exception);
}
}
}
}
}
| 37.752688
| 117
| 0.598405
|
[
"MIT-0"
] |
lykkecloud/MarginTrading.AssetService
|
src/MarginTrading.AssetService.Services/RabbitMq/Handlers/UnderlyingChangedHandler.cs
| 3,513
|
C#
|
/**
* (C) Copyright IBM Corp. 2020.
*
* 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 Newtonsoft.Json;
namespace IBM.Watson.VisualRecognition.v4.Model
{
/// <summary>
/// Basic information about an object.
/// </summary>
public class ObjectMetadata
{
/// <summary>
/// The name of the object.
/// </summary>
[JsonProperty("object", NullValueHandling = NullValueHandling.Ignore)]
public string _Object { get; set; }
/// <summary>
/// Number of bounding boxes with this object name in the collection.
/// </summary>
[JsonProperty("count", NullValueHandling = NullValueHandling.Ignore)]
public virtual long? Count { get; private set; }
}
}
| 31.3
| 78
| 0.671725
|
[
"Apache-2.0"
] |
AndreiLuis/dotnet-standard-sdk
|
src/IBM.Watson.VisualRecognition.v4/Model/ObjectMetadata.cs
| 1,252
|
C#
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace Splatoon.Cheats
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 18.277778
| 42
| 0.705167
|
[
"MIT"
] |
ivydrinkscoffee/Splatoon.Cheats
|
App.xaml.cs
| 331
|
C#
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Text.Analyzers;
namespace Text.CSharp.Analyzers
{
/// <summary>
/// CA1704: Identifiers should be spelled correctly
/// </summary>
[ExportCodeFixProvider(LanguageNames.CSharp), Shared]
public sealed class CSharpIdentifiersShouldBeSpelledCorrectlyFixer : IdentifiersShouldBeSpelledCorrectlyFixer
{
}
}
| 34.882353
| 160
| 0.770658
|
[
"Apache-2.0"
] |
AndrewZu1337/roslyn-analyzers
|
src/Text.Analyzers/CSharp/CSharpIdentifiersShouldBeSpelledCorrectly.Fixer.cs
| 593
|
C#
|
using BEDA.CMB.Contracts.Responses;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace BEDA.CMB.Contracts.Requests
{
/// <summary>
/// 17.28.查询公司卡关联付款方信息请求主体
/// </summary>
[XmlRoot("CMBSDKPGK")]
public class RQ17_28 : CMBBase<RQINFO>, IRequest<RS17_28>
{
/// <summary>
/// NTDMDRQD
/// </summary>
/// <returns></returns>
public override string GetFUNNAM() => "NTDMDRQD";
/// <summary>
/// 17.28.查询公司卡关联付款方信息请求内容
/// </summary>
public NTDMDRQDX1 NTDMDRQDX1 { get; set; }
}
/// <summary>
/// 17.28.查询公司卡关联付款方信息请求内容
/// </summary>
public class NTDMDRQDX1
{
/// <summary>
/// 分行号 C(2)
/// </summary>
public string BBKNBR { get; set; }
/// <summary>
/// 账号 C(35)
/// </summary>
public string ACCNBR { get; set; }
/// <summary>
/// 虚拟户 C(20) 首次查询空,续传查询传上次查询返回续传键值 (虚拟户、公司卡号、关联付方账号必须同时为空或同时有值)
/// </summary>
public string DMANBR { get; set; }
/// <summary>
/// 公司卡号 C(20) 首次查询空,续传查询传上次查询返回续传键值 (虚拟户、公司卡号、关联付方账号必须同时为空或同时有值)
/// </summary>
public string CDSNBR { get; set; }
/// <summary>
/// 关联付款方账号 C(35) 首次查询空,续传查询传上次查询返回续传键值 (虚拟户、公司卡号、关联付方账号必须同时为空或同时有值)
/// </summary>
public string DBTACC { get; set; }
}
}
| 27.872727
| 78
| 0.557078
|
[
"MIT"
] |
fdstar/BankEnterpriseDirectAttach
|
src/BEDA.CMB/Contracts/Requests/17/RQ17_28.cs
| 1,963
|
C#
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using System.Xml.Serialization;
using Cats.Models;
using Cats.Services.Administration;
using Cats.Services.Common;
using Cats.Models.ViewModels;
using Newtonsoft.Json;
using System.Net;
//using Cats.Services.EarlyWarning.IFDPService;
namespace Cats.Controllers
{
public class SMSGatewayController : Controller
{
//
// GET: /CatsSmsGateway/
//private readonly IFDPService _fdpService;
private readonly ISMSGatewayService _smsService;
//private readonly IContactService _contactService;
public SMSGatewayController(ISMSGatewayService smsGatewayService)
{
_smsService = smsGatewayService;
}
public JsonResult Index2()
{
////var request = (WebRequest)Request.Url.AbsoluteUri;
////HttpContext.Response.AddHeader("Content-Type", "application/json");
////Response.AddHeader("Content-Type: application/json");
////Request.Headers.Add("Content-Type", "application/json");
////HttpContext.Response.AddHeader("Content-Type","application/json");
////Response.AddHeader();
////Response.AddHeader("Content-Type", "application/json");
//HttpContext.Response.AddHeader("Content-Type", "text/xml");
//var messages = new List<SmsOutgoingMessage>();
//var sendevents = new List<SmsEventSend>();
//var pack = new List<List<SmsEventSend>>();-
//var messageOne = new SmsOutgoingMessage()
// {
// id = "4f7c9cea5e11b",
// message = "Hello Nati Man! You are selected to be man of the day! CATS",
// to = "0911474539",
// };
////var contacts = _contactService.FindBy(t => t.FDP.Name == );
//messages.Add(messageOne);
//var ev = new SmsEventSend()
// {
// @event = "send",
// messages = messages
// };
//sendevents.Add(ev);
//var result = new { events = sendevents };
////return Json(sendevents, "EV", JsonRequestBehavior.AllowGet);
//return Json(result, JsonRequestBehavior.AllowGet);
////return "HI";
///*dynamic collectionWrapper = new
//{
// events = sendevents
//};
//var output = JsonConvert.SerializeObject(collectionWrapper);
//var o = JsonConvert.SerializeObject(collectionWrapper, Newtonsoft.Json.Formatting.Indented);
//string result = o.ToString();
//return o;
//*/
///*
//string xml;
//using (MemoryStream ms = new MemoryStream())
//{
// var sw = new StreamWriter(ms);
// var settings = new XmlWriterSettings();
// settings.Encoding = Encoding.UTF8;
// settings.Indent = true;
// //var s = new StringBuilder();
// //var setting = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true };
// XmlWriter writer = XmlWriter.Create(sw, settings);
// using (writer)
// {
// writer.WriteStartDocument();
// writer.WriteStartElement("response");
// foreach (var eve in sendevents)
// {
// writer.WriteStartElement("messages");
// foreach (var sms in eve.messages)
// {
// writer.WriteStartElement("sms");
// //id="52d7924725bf0" to="251911663223">Hello Yareda CATS wishs you a great lunch!! ENVAYASMS is working now!
// // writer.WriteAttributeString("id", sms.id);
// writer.WriteAttributeString("to", sms.to);
// writer.WriteRaw(sms.message);
// writer.WriteEndElement();
// }
// writer.WriteEndElement();
// }
// writer.WriteEndElement();
// writer.WriteEndDocument();
// }
// using (StreamReader sr = new StreamReader(ms))
// {
// ms.Position = 0;
// xml = sr.ReadToEnd();
// sr.Close();
// }
//}
//return xml;
//*/
////string re = "<?xml version='1.0' encoding='UTF-8'?><response><messages><sms id="52d7924725bf0" to="251911663223
////">Hello Yareda CATS wishs you a great lunch!! ENVAYASMS is working now!</sms></messages></response>";
return Json(new HRD(), JsonRequestBehavior.AllowGet);
}
public bool Send()
{
//var messageOne = new SmsOutgoingMessage()
//{
// //id = "4f7c9cea8e17b",
// message = "Hello this is the first ever message from the original CATS",
// to = "251911474539",
//};
//var result = _smsService.SendSMS(messageOne);
//return result;
return true;
}
}
}
| 35.461538
| 138
| 0.509761
|
[
"Apache-2.0"
] |
IYoni/cats
|
Web/Controllers/SMSGatewayController.cs
| 5,534
|
C#
|
using System.Collections.Generic;
using FluentAssertions.Common;
namespace FluentAssertions.Equivalency.Ordering
{
/// <summary>
/// Ordering rule that ensures that byte arrays are always compared in strict ordering since it would cause a
/// severe performance impact otherwise.
/// </summary>
internal class ByteArrayOrderingRule : IOrderingRule
{
public bool AppliesTo(ISubjectInfo subjectInfo)
{
return subjectInfo.CompileTimeType.Implements<IEnumerable<byte>>();
}
public override string ToString()
{
return "Be strict about the order of items in byte arrays";
}
}
}
| 30.636364
| 114
| 0.673591
|
[
"Apache-2.0"
] |
Pyroka/FuentAssertions.Unity
|
FluentAssertions.Unity/Equivalency/Ordering/ByteArrayOrderingRule.cs
| 674
|
C#
|
using System.Threading;
using System.Threading.Tasks;
using BC7.Infrastructure.CustomExceptions;
using BC7.Repository;
using MediatR;
namespace BC7.Business.Implementation.Users.Commands.ChangeAvatar
{
public class ChangeAvatarCommandHandler : IRequestHandler<ChangeAvatarCommand>
{
private readonly IUserAccountDataRepository _userAccountDataRepository;
public ChangeAvatarCommandHandler(IUserAccountDataRepository userAccountDataRepository)
{
_userAccountDataRepository = userAccountDataRepository;
}
public async Task<Unit> Handle(ChangeAvatarCommand request, CancellationToken cancellationToken = default(CancellationToken))
{
var user = await _userAccountDataRepository.GetAsync(request.UserAccountDataId);
if (user is null)
{
throw new AccountNotFoundException($"User with given ID cannot be found - {request.UserAccountDataId}");
}
user.ChangeAvatar(request.AvatarPath);
await _userAccountDataRepository.UpdateAsync(user);
return Unit.Value;
}
}
}
| 34.575758
| 133
| 0.712533
|
[
"MIT"
] |
XardasLord/BitClub7
|
BC7.Business.Implementation/Users/Commands/ChangeAvatar/ChangeAvatarCommandHandler.cs
| 1,143
|
C#
|
/*
using System.Runtime.CompilerServices;
using IPA.Config.Stores;
[assembly: InternalsVisibleTo(GeneratedStore.AssemblyVisibilityTarget)]
namespace BeatSaberDiscordPresence.Configuration
{
internal class PluginConfig
{
public static PluginConfig Instance { get; set; }
public virtual int IntValue { get; set; } = 42; // Must be 'virtual' if you want BSIPA to detect a value change and save the config automatically.
/// <summary>
/// This is called whenever BSIPA reads the config from disk (including when file changes are detected).
/// </summary>
public virtual void OnReload()
{
// Do stuff after config is read from disk.
}
/// <summary>
/// Call this to force BSIPA to update the config file. This is also called by BSIPA if it detects the file was modified.
/// </summary>
public virtual void Changed()
{
// Do stuff when the config is changed.
}
/// <summary>
/// Call this to have BSIPA copy the values from <paramref name="other"/> into this config.
/// </summary>
public virtual void CopyFrom(PluginConfig other)
{
// This instance's members populated from other
}
}
}
*/
| 32.45
| 154
| 0.623267
|
[
"MIT"
] |
braddevans/BeatSaberDiscordPresence
|
BeatSaberDiscordPresence/Configuration/PluginConfig.cs
| 1,300
|
C#
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using OnlineTraining.Entities.Db;
using OnlineTraining.Entities.Entities;
using OnlineTraining.Helper.Config;
using OnlineTraining.Repositories.Interfaces;
namespace OnlineTraining.Repositories.Repositories
{
public class BookmarkRepository : IBookmarkRepository
{
private readonly IMongoCollection<Bookmark> _bookmarkRepository;
private readonly IMongoCollection<Course> _courseRepository;
public BookmarkRepository(IOptions<OtaConfig> config)
{
var mongoConnect = new MongoContext(config);
_bookmarkRepository = mongoConnect.GetConnection().GetCollection<Bookmark>("Bookmarks");
_courseRepository = mongoConnect.GetConnection().GetCollection<Course>("Courses");
}
public async Task<List<Bookmark>> GetBookMarkByUserId(string userId)
{
var bookmarkList = await
_bookmarkRepository.Find(bm => bm.UserId == userId).ToListAsync();
return bookmarkList;
}
public async Task<List<Course>> GetCourseBookMarkByUserId(string userId)
{
var listCourses = new List<Course>();
var bookmarkList = await
_bookmarkRepository.Find(bm => bm.UserId == userId).ToListAsync();
foreach (var bookmark in bookmarkList)
{
var courseId = bookmark.CourseId;
var course = await _courseRepository.Find(c => c.Id == courseId).SingleAsync();
listCourses.Add(course);
}
return listCourses;
}
public async Task<bool> BookmarkCourse(string courseId, string userId)
{
var bookmarkExist =
_bookmarkRepository.Find(bm => bm.CourseId == courseId && bm.UserId == userId);
if (bookmarkExist.Count() > 0) {
return false;
}
var bookmark = new Bookmark
{
CourseId = courseId,
UserId = userId,
CreatedDate = DateTime.Now,
ModifieddDate = DateTime.Now
};
await _bookmarkRepository.InsertOneAsync(bookmark);
return true;
}
public async Task<bool> UnBookmarkCourse(string courseId, string userId)
{
await _bookmarkRepository.FindOneAndDeleteAsync(bm => bm.CourseId == courseId && bm.UserId == userId);
return true;
}
}
}
| 34.605263
| 114
| 0.61673
|
[
"Unlicense"
] |
anandgithub27/online-training
|
OnlineTraining/OnlineTraining.Repositories/Repositories/BookmarkRepository.cs
| 2,632
|
C#
|
#region Licence
/* The MIT License (MIT)
Copyright © 2014 Ian Cooper <ian_hammond_cooper@yahoo.co.uk>
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.Transactions;
using paramore.brighter.restms.core.Model;
using paramore.brighter.restms.core.Ports.Common;
using paramore.brighter.restms.server.Adapters.Configuration;
using paramore.brighter.restms.server.Adapters.Security;
using Thinktecture.IdentityModel.Hawk.Core;
using Thinktecture.IdentityModel.Hawk.Core.Helpers;
namespace paramore.brighter.restms.server.Adapters.Service
{
// In the general decoupled messaging model, the cat reads from a private queue which subscribes to the named address, and the master
// publishes messages to this named address. In a coupled model, the cat reads from a named queue and the master publishes into this queue directly.
// The RestMS 3/Defaults profile implements both coupled Housecat (using the default feed and default join) and decoupled Housecat
// (using a dynamic feed and arbitrary joins).
/// </summary>
internal class RestMSServerBuilder : IConfigureRestMSServers, IBuildARestMSService, IUseRepositories, IUseCredentials
{
private IAmARepository<Domain> _domainRepository;
private IAmARepository<Feed> _feedRepository;
private RestMSServerConfiguration _configuration;
public IUseRepositories With()
{
_configuration = RestMSServerConfiguration.GetConfiguration();
return this;
}
public void Do()
{
var domain = new Domain(
name: new Name("default"),
title: new Title("title"),
profile: new Profile(
name: new Name(@"3/Defaults"),
href: new Uri(@"href://www.restms.org/spec:3/Defaults")
),
version: new AggregateVersion(0)
);
var feed = new Feed(
feedType: FeedType.Default,
name: new Name("default"),
title: new Title("Default feed")
);
domain.AddFeed(feed.Id);
using (var scope = new TransactionScope())
{
_domainRepository.Add(domain);
_feedRepository.Add(feed);
scope.Complete();
}
}
public IUseCredentials Repositories(IAmARepository<Domain> domainRepository, IAmARepository<Feed> feedRepository)
{
_domainRepository = domainRepository;
_feedRepository = feedRepository;
return this;
}
/// <summary>
/// Securities the specified credentials storage.
/// </summary>
/// <param name="credentialsStorage">The credentials storage.</param>
/// <returns>IBuildARestMSService.</returns>
public IBuildARestMSService Security(IAmACredentialStore credentialsStorage)
{
credentialsStorage.Add(new Credential()
{
Id = _configuration.Admin.Id,
Algorithm = SupportedAlgorithms.SHA256,
User = _configuration.Admin.User,
Key = Convert.FromBase64String(_configuration.Admin.Key)
});
return this;
}
}
internal interface IConfigureRestMSServers
{
/// <summary>
/// Withes this instance.
/// </summary>
/// <returns>IUseRepositories.</returns>
IUseRepositories With();
}
internal interface IUseRepositories
{
/// <summary>
/// Repositorieses the specified domain repository.
/// </summary>
/// <param name="domainRepository">The domain repository.</param>
/// <param name="feedRepository">The feed repository.</param>
/// <returns>IBuildARestMSService.</returns>
IUseCredentials Repositories(IAmARepository<Domain> domainRepository, IAmARepository<Feed> feedRepository);
}
internal interface IUseCredentials
{
IBuildARestMSService Security(IAmACredentialStore credentialsStorage);
}
internal interface IBuildARestMSService
{
void Do();
}
}
| 37.553957
| 153
| 0.662452
|
[
"MIT"
] |
BrighterCommand/Contrib
|
Renegade/src/Paramore.Restms.Server/Adapters/Service/RestMSServerBuilder.cs
| 5,231
|
C#
|
using System;
using System.Collections.Generic;
using System.Text;
using DotNet.Basics.Diagnostics;
namespace DotNet.Basics.Cli
{
public interface ICliHost : ICliConfiguration
{
ILogger Log { get; }
}
}
| 18.230769
| 50
| 0.675105
|
[
"MIT"
] |
rzmoz/DotNet.Basics
|
DotNet.Basics.Cli/ICliHost.cs
| 239
|
C#
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the meteringmarketplace-2016-01-14.normal.json service model.
*/
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Net;
using Amazon.AWSMarketplaceMetering.Model;
using Amazon.AWSMarketplaceMetering.Model.Internal.MarshallTransformations;
using Amazon.AWSMarketplaceMetering.Internal;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.AWSMarketplaceMetering
{
/// <summary>
/// Implementation for accessing AWSMarketplaceMetering
///
/// AWS Marketplace Metering Service
/// <para>
/// This reference provides descriptions of the low-level AWS Marketplace Metering Service
/// API.
/// </para>
///
/// <para>
/// AWS Marketplace sellers can use this API to submit usage data for custom usage dimensions.
/// </para>
///
/// <para>
/// For information on the permissions you need to use this API, see <a href="https://docs.aws.amazon.com/marketplace/latest/userguide/iam-user-policy-for-aws-marketplace-actions.html">AWS
/// Marketplace metering and entitlement API permissions</a> in the <i>AWS Marketplace
/// Seller Guide.</i>
/// </para>
///
/// <para>
/// <b>Submitting Metering Records</b>
/// </para>
/// <ul> <li>
/// <para>
/// <i>MeterUsage</i> - Submits the metering record for an AWS Marketplace product. <code>MeterUsage</code>
/// is called from an EC2 instance or a container running on EKS or ECS.
/// </para>
/// </li> <li>
/// <para>
/// <i>BatchMeterUsage</i> - Submits the metering record for a set of customers. <code>BatchMeterUsage</code>
/// is called from a software-as-a-service (SaaS) application.
/// </para>
/// </li> </ul>
/// <para>
/// <b>Accepting New Customers</b>
/// </para>
/// <ul> <li>
/// <para>
/// <i>ResolveCustomer</i> - Called by a SaaS application during the registration process.
/// When a buyer visits your website during the registration process, the buyer submits
/// a Registration Token through the browser. The Registration Token is resolved through
/// this API to obtain a <code>CustomerIdentifier</code> along with the <code>CustomerAWSAccountId</code>
/// and <code>ProductCode</code>.
/// </para>
/// </li> </ul>
/// <para>
/// <b>Entitlement and Metering for Paid Container Products</b>
/// </para>
/// <ul> <li>
/// <para>
/// Paid container software products sold through AWS Marketplace must integrate with
/// the AWS Marketplace Metering Service and call the <code>RegisterUsage</code> operation
/// for software entitlement and metering. Free and BYOL products for Amazon ECS or Amazon
/// EKS aren't required to call <code>RegisterUsage</code>, but you can do so if you want
/// to receive usage data in your seller reports. For more information on using the <code>RegisterUsage</code>
/// operation, see <a href="https://docs.aws.amazon.com/marketplace/latest/userguide/container-based-products.html">Container-Based
/// Products</a>.
/// </para>
/// </li> </ul>
/// <para>
/// <code>BatchMeterUsage</code> API calls are captured by AWS CloudTrail. You can use
/// Cloudtrail to verify that the SaaS metering records that you sent are accurate by
/// searching for records with the <code>eventName</code> of <code>BatchMeterUsage</code>.
/// You can also use CloudTrail to audit records over time. For more information, see
/// the <i> <a href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-concepts.html">AWS
/// CloudTrail User Guide</a>.</i>
/// </para>
/// </summary>
public partial class AmazonAWSMarketplaceMeteringClient : AmazonServiceClient, IAmazonAWSMarketplaceMetering
{
private static IServiceMetadata serviceMetadata = new AmazonAWSMarketplaceMeteringMetadata();
#region Constructors
/// <summary>
/// Constructs AmazonAWSMarketplaceMeteringClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonAWSMarketplaceMeteringClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonAWSMarketplaceMeteringConfig()) { }
/// <summary>
/// Constructs AmazonAWSMarketplaceMeteringClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonAWSMarketplaceMeteringClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonAWSMarketplaceMeteringConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonAWSMarketplaceMeteringClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonAWSMarketplaceMeteringClient Configuration Object</param>
public AmazonAWSMarketplaceMeteringClient(AmazonAWSMarketplaceMeteringConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonAWSMarketplaceMeteringClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonAWSMarketplaceMeteringClient(AWSCredentials credentials)
: this(credentials, new AmazonAWSMarketplaceMeteringConfig())
{
}
/// <summary>
/// Constructs AmazonAWSMarketplaceMeteringClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonAWSMarketplaceMeteringClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonAWSMarketplaceMeteringConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonAWSMarketplaceMeteringClient with AWS Credentials and an
/// AmazonAWSMarketplaceMeteringClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonAWSMarketplaceMeteringClient Configuration Object</param>
public AmazonAWSMarketplaceMeteringClient(AWSCredentials credentials, AmazonAWSMarketplaceMeteringConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonAWSMarketplaceMeteringClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonAWSMarketplaceMeteringClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonAWSMarketplaceMeteringConfig())
{
}
/// <summary>
/// Constructs AmazonAWSMarketplaceMeteringClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonAWSMarketplaceMeteringClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonAWSMarketplaceMeteringConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonAWSMarketplaceMeteringClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonAWSMarketplaceMeteringClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonAWSMarketplaceMeteringClient Configuration Object</param>
public AmazonAWSMarketplaceMeteringClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonAWSMarketplaceMeteringConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonAWSMarketplaceMeteringClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonAWSMarketplaceMeteringClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonAWSMarketplaceMeteringConfig())
{
}
/// <summary>
/// Constructs AmazonAWSMarketplaceMeteringClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonAWSMarketplaceMeteringClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonAWSMarketplaceMeteringConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonAWSMarketplaceMeteringClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonAWSMarketplaceMeteringClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonAWSMarketplaceMeteringClient Configuration Object</param>
public AmazonAWSMarketplaceMeteringClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonAWSMarketplaceMeteringConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
/// <summary>
/// Capture metadata for the service.
/// </summary>
protected override IServiceMetadata ServiceMetadata
{
get
{
return serviceMetadata;
}
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region BatchMeterUsage
/// <summary>
/// <code>BatchMeterUsage</code> is called from a SaaS application listed on AWS Marketplace
/// to post metering records for a set of customers.
///
///
/// <para>
/// For identical requests, the API is idempotent; requests can be retried with the same
/// records or a subset of the input records.
/// </para>
///
/// <para>
/// Every request to <code>BatchMeterUsage</code> is for one product. If you need to meter
/// usage for multiple products, you must make multiple calls to <code>BatchMeterUsage</code>.
/// </para>
///
/// <para>
/// Usage records are expected to be submitted as quickly as possible after the event
/// that is being recorded, and are not accepted more than 6 hours after the event.
/// </para>
///
/// <para>
/// <code>BatchMeterUsage</code> can process up to 25 <code>UsageRecords</code> at a
/// time.
/// </para>
///
/// <para>
/// A <code>UsageRecord</code> can optionally include multiple usage allocations, to provide
/// customers with usage data split into buckets by tags that you define (or allow the
/// customer to define).
/// </para>
///
/// <para>
/// <code>BatchMeterUsage</code> returns a list of <code>UsageRecordResult</code> objects,
/// showing the result for each <code>UsageRecord</code>, as well as a list of <code>UnprocessedRecords</code>,
/// indicating errors in the service side that you should retry.
/// </para>
///
/// <para>
/// <code>BatchMeterUsage</code> requests must be less than 1MB in size.
/// </para>
/// <note>
/// <para>
/// For an example of using <code>BatchMeterUsage</code>, see <a href="https://docs.aws.amazon.com/marketplace/latest/userguide/saas-code-examples.html#saas-batchmeterusage-example">
/// BatchMeterUsage code example</a> in the <i>AWS Marketplace Seller Guide</i>.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the BatchMeterUsage service method.</param>
///
/// <returns>The response from the BatchMeterUsage service method, as returned by AWSMarketplaceMetering.</returns>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.DisabledApiException">
/// The API is disabled in the Region.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InternalServiceErrorException">
/// An internal error has occurred. Retry your request. If the problem persists, post
/// a message with details on the AWS forums.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidCustomerIdentifierException">
/// You have metered usage for a <code>CustomerIdentifier</code> that does not exist.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidProductCodeException">
/// The product code passed does not match the product code used for publishing the product.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidTagException">
/// The tag is invalid, or the number of tags is greater than 5.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidUsageAllocationsException">
/// The usage allocation objects are invalid, or the number of allocations is greater
/// than 500 for a single usage record.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidUsageDimensionException">
/// The usage dimension does not match one of the <code>UsageDimensions</code> associated
/// with products.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.ThrottlingException">
/// The calls to the API are throttled.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.TimestampOutOfBoundsException">
/// The <code>timestamp</code> value passed in the <code>UsageRecord</code> is out of
/// allowed range.
///
///
/// <para>
/// For <code>BatchMeterUsage</code>, if any of the records are outside of the allowed
/// range, the entire batch is not processed. You must remove invalid records and try
/// again.
/// </para>
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/meteringmarketplace-2016-01-14/BatchMeterUsage">REST API Reference for BatchMeterUsage Operation</seealso>
public virtual BatchMeterUsageResponse BatchMeterUsage(BatchMeterUsageRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = BatchMeterUsageRequestMarshaller.Instance;
options.ResponseUnmarshaller = BatchMeterUsageResponseUnmarshaller.Instance;
return Invoke<BatchMeterUsageResponse>(request, options);
}
/// <summary>
/// <code>BatchMeterUsage</code> is called from a SaaS application listed on AWS Marketplace
/// to post metering records for a set of customers.
///
///
/// <para>
/// For identical requests, the API is idempotent; requests can be retried with the same
/// records or a subset of the input records.
/// </para>
///
/// <para>
/// Every request to <code>BatchMeterUsage</code> is for one product. If you need to meter
/// usage for multiple products, you must make multiple calls to <code>BatchMeterUsage</code>.
/// </para>
///
/// <para>
/// Usage records are expected to be submitted as quickly as possible after the event
/// that is being recorded, and are not accepted more than 6 hours after the event.
/// </para>
///
/// <para>
/// <code>BatchMeterUsage</code> can process up to 25 <code>UsageRecords</code> at a
/// time.
/// </para>
///
/// <para>
/// A <code>UsageRecord</code> can optionally include multiple usage allocations, to provide
/// customers with usage data split into buckets by tags that you define (or allow the
/// customer to define).
/// </para>
///
/// <para>
/// <code>BatchMeterUsage</code> returns a list of <code>UsageRecordResult</code> objects,
/// showing the result for each <code>UsageRecord</code>, as well as a list of <code>UnprocessedRecords</code>,
/// indicating errors in the service side that you should retry.
/// </para>
///
/// <para>
/// <code>BatchMeterUsage</code> requests must be less than 1MB in size.
/// </para>
/// <note>
/// <para>
/// For an example of using <code>BatchMeterUsage</code>, see <a href="https://docs.aws.amazon.com/marketplace/latest/userguide/saas-code-examples.html#saas-batchmeterusage-example">
/// BatchMeterUsage code example</a> in the <i>AWS Marketplace Seller Guide</i>.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the BatchMeterUsage service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the BatchMeterUsage service method, as returned by AWSMarketplaceMetering.</returns>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.DisabledApiException">
/// The API is disabled in the Region.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InternalServiceErrorException">
/// An internal error has occurred. Retry your request. If the problem persists, post
/// a message with details on the AWS forums.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidCustomerIdentifierException">
/// You have metered usage for a <code>CustomerIdentifier</code> that does not exist.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidProductCodeException">
/// The product code passed does not match the product code used for publishing the product.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidTagException">
/// The tag is invalid, or the number of tags is greater than 5.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidUsageAllocationsException">
/// The usage allocation objects are invalid, or the number of allocations is greater
/// than 500 for a single usage record.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidUsageDimensionException">
/// The usage dimension does not match one of the <code>UsageDimensions</code> associated
/// with products.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.ThrottlingException">
/// The calls to the API are throttled.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.TimestampOutOfBoundsException">
/// The <code>timestamp</code> value passed in the <code>UsageRecord</code> is out of
/// allowed range.
///
///
/// <para>
/// For <code>BatchMeterUsage</code>, if any of the records are outside of the allowed
/// range, the entire batch is not processed. You must remove invalid records and try
/// again.
/// </para>
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/meteringmarketplace-2016-01-14/BatchMeterUsage">REST API Reference for BatchMeterUsage Operation</seealso>
public virtual Task<BatchMeterUsageResponse> BatchMeterUsageAsync(BatchMeterUsageRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = BatchMeterUsageRequestMarshaller.Instance;
options.ResponseUnmarshaller = BatchMeterUsageResponseUnmarshaller.Instance;
return InvokeAsync<BatchMeterUsageResponse>(request, options, cancellationToken);
}
#endregion
#region MeterUsage
/// <summary>
/// API to emit metering records. For identical requests, the API is idempotent. It simply
/// returns the metering record ID.
///
///
/// <para>
/// <code>MeterUsage</code> is authenticated on the buyer's AWS account using credentials
/// from the EC2 instance, ECS task, or EKS pod.
/// </para>
///
/// <para>
/// <code>MeterUsage</code> can optionally include multiple usage allocations, to provide
/// customers with usage data split into buckets by tags that you define (or allow the
/// customer to define).
/// </para>
///
/// <para>
/// Usage records are expected to be submitted as quickly as possible after the event
/// that is being recorded, and are not accepted more than 6 hours after the event.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the MeterUsage service method.</param>
///
/// <returns>The response from the MeterUsage service method, as returned by AWSMarketplaceMetering.</returns>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.CustomerNotEntitledException">
/// Exception thrown when the customer does not have a valid subscription for the product.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.DuplicateRequestException">
/// A metering record has already been emitted by the same EC2 instance, ECS task, or
/// EKS pod for the given {<code>usageDimension</code>, <code>timestamp</code>} with a
/// different <code>usageQuantity</code>.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InternalServiceErrorException">
/// An internal error has occurred. Retry your request. If the problem persists, post
/// a message with details on the AWS forums.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidEndpointRegionException">
/// The endpoint being called is in a AWS Region different from your EC2 instance, ECS
/// task, or EKS pod. The Region of the Metering Service endpoint and the AWS Region of
/// the resource must match.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidProductCodeException">
/// The product code passed does not match the product code used for publishing the product.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidTagException">
/// The tag is invalid, or the number of tags is greater than 5.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidUsageAllocationsException">
/// The usage allocation objects are invalid, or the number of allocations is greater
/// than 500 for a single usage record.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidUsageDimensionException">
/// The usage dimension does not match one of the <code>UsageDimensions</code> associated
/// with products.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.ThrottlingException">
/// The calls to the API are throttled.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.TimestampOutOfBoundsException">
/// The <code>timestamp</code> value passed in the <code>UsageRecord</code> is out of
/// allowed range.
///
///
/// <para>
/// For <code>BatchMeterUsage</code>, if any of the records are outside of the allowed
/// range, the entire batch is not processed. You must remove invalid records and try
/// again.
/// </para>
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/meteringmarketplace-2016-01-14/MeterUsage">REST API Reference for MeterUsage Operation</seealso>
public virtual MeterUsageResponse MeterUsage(MeterUsageRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = MeterUsageRequestMarshaller.Instance;
options.ResponseUnmarshaller = MeterUsageResponseUnmarshaller.Instance;
return Invoke<MeterUsageResponse>(request, options);
}
/// <summary>
/// API to emit metering records. For identical requests, the API is idempotent. It simply
/// returns the metering record ID.
///
///
/// <para>
/// <code>MeterUsage</code> is authenticated on the buyer's AWS account using credentials
/// from the EC2 instance, ECS task, or EKS pod.
/// </para>
///
/// <para>
/// <code>MeterUsage</code> can optionally include multiple usage allocations, to provide
/// customers with usage data split into buckets by tags that you define (or allow the
/// customer to define).
/// </para>
///
/// <para>
/// Usage records are expected to be submitted as quickly as possible after the event
/// that is being recorded, and are not accepted more than 6 hours after the event.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the MeterUsage service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the MeterUsage service method, as returned by AWSMarketplaceMetering.</returns>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.CustomerNotEntitledException">
/// Exception thrown when the customer does not have a valid subscription for the product.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.DuplicateRequestException">
/// A metering record has already been emitted by the same EC2 instance, ECS task, or
/// EKS pod for the given {<code>usageDimension</code>, <code>timestamp</code>} with a
/// different <code>usageQuantity</code>.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InternalServiceErrorException">
/// An internal error has occurred. Retry your request. If the problem persists, post
/// a message with details on the AWS forums.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidEndpointRegionException">
/// The endpoint being called is in a AWS Region different from your EC2 instance, ECS
/// task, or EKS pod. The Region of the Metering Service endpoint and the AWS Region of
/// the resource must match.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidProductCodeException">
/// The product code passed does not match the product code used for publishing the product.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidTagException">
/// The tag is invalid, or the number of tags is greater than 5.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidUsageAllocationsException">
/// The usage allocation objects are invalid, or the number of allocations is greater
/// than 500 for a single usage record.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidUsageDimensionException">
/// The usage dimension does not match one of the <code>UsageDimensions</code> associated
/// with products.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.ThrottlingException">
/// The calls to the API are throttled.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.TimestampOutOfBoundsException">
/// The <code>timestamp</code> value passed in the <code>UsageRecord</code> is out of
/// allowed range.
///
///
/// <para>
/// For <code>BatchMeterUsage</code>, if any of the records are outside of the allowed
/// range, the entire batch is not processed. You must remove invalid records and try
/// again.
/// </para>
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/meteringmarketplace-2016-01-14/MeterUsage">REST API Reference for MeterUsage Operation</seealso>
public virtual Task<MeterUsageResponse> MeterUsageAsync(MeterUsageRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = MeterUsageRequestMarshaller.Instance;
options.ResponseUnmarshaller = MeterUsageResponseUnmarshaller.Instance;
return InvokeAsync<MeterUsageResponse>(request, options, cancellationToken);
}
#endregion
#region RegisterUsage
/// <summary>
/// Paid container software products sold through AWS Marketplace must integrate with
/// the AWS Marketplace Metering Service and call the <code>RegisterUsage</code> operation
/// for software entitlement and metering. Free and BYOL products for Amazon ECS or Amazon
/// EKS aren't required to call <code>RegisterUsage</code>, but you may choose to do so
/// if you would like to receive usage data in your seller reports. The sections below
/// explain the behavior of <code>RegisterUsage</code>. <code>RegisterUsage</code> performs
/// two primary functions: metering and entitlement.
///
/// <ul> <li>
/// <para>
/// <i>Entitlement</i>: <code>RegisterUsage</code> allows you to verify that the customer
/// running your paid software is subscribed to your product on AWS Marketplace, enabling
/// you to guard against unauthorized use. Your container image that integrates with <code>RegisterUsage</code>
/// is only required to guard against unauthorized use at container startup, as such a
/// <code>CustomerNotSubscribedException</code> or <code>PlatformNotSupportedException</code>
/// will only be thrown on the initial call to <code>RegisterUsage</code>. Subsequent
/// calls from the same Amazon ECS task instance (e.g. task-id) or Amazon EKS pod will
/// not throw a <code>CustomerNotSubscribedException</code>, even if the customer unsubscribes
/// while the Amazon ECS task or Amazon EKS pod is still running.
/// </para>
/// </li> <li>
/// <para>
/// <i>Metering</i>: <code>RegisterUsage</code> meters software use per ECS task, per
/// hour, or per pod for Amazon EKS with usage prorated to the second. A minimum of 1
/// minute of usage applies to tasks that are short lived. For example, if a customer
/// has a 10 node Amazon ECS or Amazon EKS cluster and a service configured as a Daemon
/// Set, then Amazon ECS or Amazon EKS will launch a task on all 10 cluster nodes and
/// the customer will be charged: (10 * hourly_rate). Metering for software use is automatically
/// handled by the AWS Marketplace Metering Control Plane -- your software is not required
/// to perform any metering specific actions, other than call <code>RegisterUsage</code>
/// once for metering of software use to commence. The AWS Marketplace Metering Control
/// Plane will also continue to bill customers for running ECS tasks and Amazon EKS pods,
/// regardless of the customers subscription state, removing the need for your software
/// to perform entitlement checks at runtime.
/// </para>
/// </li> </ul>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RegisterUsage service method.</param>
///
/// <returns>The response from the RegisterUsage service method, as returned by AWSMarketplaceMetering.</returns>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.CustomerNotEntitledException">
/// Exception thrown when the customer does not have a valid subscription for the product.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.DisabledApiException">
/// The API is disabled in the Region.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InternalServiceErrorException">
/// An internal error has occurred. Retry your request. If the problem persists, post
/// a message with details on the AWS forums.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidProductCodeException">
/// The product code passed does not match the product code used for publishing the product.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidPublicKeyVersionException">
/// Public Key version is invalid.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidRegionException">
/// <code>RegisterUsage</code> must be called in the same AWS Region the ECS task was
/// launched in. This prevents a container from hardcoding a Region (e.g. withRegion(“us-east-1”)
/// when calling <code>RegisterUsage</code>.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.PlatformNotSupportedException">
/// AWS Marketplace does not support metering usage from the underlying platform. Currently,
/// Amazon ECS, Amazon EKS, and AWS Fargate are supported.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.ThrottlingException">
/// The calls to the API are throttled.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/meteringmarketplace-2016-01-14/RegisterUsage">REST API Reference for RegisterUsage Operation</seealso>
public virtual RegisterUsageResponse RegisterUsage(RegisterUsageRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = RegisterUsageRequestMarshaller.Instance;
options.ResponseUnmarshaller = RegisterUsageResponseUnmarshaller.Instance;
return Invoke<RegisterUsageResponse>(request, options);
}
/// <summary>
/// Paid container software products sold through AWS Marketplace must integrate with
/// the AWS Marketplace Metering Service and call the <code>RegisterUsage</code> operation
/// for software entitlement and metering. Free and BYOL products for Amazon ECS or Amazon
/// EKS aren't required to call <code>RegisterUsage</code>, but you may choose to do so
/// if you would like to receive usage data in your seller reports. The sections below
/// explain the behavior of <code>RegisterUsage</code>. <code>RegisterUsage</code> performs
/// two primary functions: metering and entitlement.
///
/// <ul> <li>
/// <para>
/// <i>Entitlement</i>: <code>RegisterUsage</code> allows you to verify that the customer
/// running your paid software is subscribed to your product on AWS Marketplace, enabling
/// you to guard against unauthorized use. Your container image that integrates with <code>RegisterUsage</code>
/// is only required to guard against unauthorized use at container startup, as such a
/// <code>CustomerNotSubscribedException</code> or <code>PlatformNotSupportedException</code>
/// will only be thrown on the initial call to <code>RegisterUsage</code>. Subsequent
/// calls from the same Amazon ECS task instance (e.g. task-id) or Amazon EKS pod will
/// not throw a <code>CustomerNotSubscribedException</code>, even if the customer unsubscribes
/// while the Amazon ECS task or Amazon EKS pod is still running.
/// </para>
/// </li> <li>
/// <para>
/// <i>Metering</i>: <code>RegisterUsage</code> meters software use per ECS task, per
/// hour, or per pod for Amazon EKS with usage prorated to the second. A minimum of 1
/// minute of usage applies to tasks that are short lived. For example, if a customer
/// has a 10 node Amazon ECS or Amazon EKS cluster and a service configured as a Daemon
/// Set, then Amazon ECS or Amazon EKS will launch a task on all 10 cluster nodes and
/// the customer will be charged: (10 * hourly_rate). Metering for software use is automatically
/// handled by the AWS Marketplace Metering Control Plane -- your software is not required
/// to perform any metering specific actions, other than call <code>RegisterUsage</code>
/// once for metering of software use to commence. The AWS Marketplace Metering Control
/// Plane will also continue to bill customers for running ECS tasks and Amazon EKS pods,
/// regardless of the customers subscription state, removing the need for your software
/// to perform entitlement checks at runtime.
/// </para>
/// </li> </ul>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the RegisterUsage service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the RegisterUsage service method, as returned by AWSMarketplaceMetering.</returns>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.CustomerNotEntitledException">
/// Exception thrown when the customer does not have a valid subscription for the product.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.DisabledApiException">
/// The API is disabled in the Region.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InternalServiceErrorException">
/// An internal error has occurred. Retry your request. If the problem persists, post
/// a message with details on the AWS forums.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidProductCodeException">
/// The product code passed does not match the product code used for publishing the product.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidPublicKeyVersionException">
/// Public Key version is invalid.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidRegionException">
/// <code>RegisterUsage</code> must be called in the same AWS Region the ECS task was
/// launched in. This prevents a container from hardcoding a Region (e.g. withRegion(“us-east-1”)
/// when calling <code>RegisterUsage</code>.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.PlatformNotSupportedException">
/// AWS Marketplace does not support metering usage from the underlying platform. Currently,
/// Amazon ECS, Amazon EKS, and AWS Fargate are supported.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.ThrottlingException">
/// The calls to the API are throttled.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/meteringmarketplace-2016-01-14/RegisterUsage">REST API Reference for RegisterUsage Operation</seealso>
public virtual Task<RegisterUsageResponse> RegisterUsageAsync(RegisterUsageRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = RegisterUsageRequestMarshaller.Instance;
options.ResponseUnmarshaller = RegisterUsageResponseUnmarshaller.Instance;
return InvokeAsync<RegisterUsageResponse>(request, options, cancellationToken);
}
#endregion
#region ResolveCustomer
/// <summary>
/// <code>ResolveCustomer</code> is called by a SaaS application during the registration
/// process. When a buyer visits your website during the registration process, the buyer
/// submits a registration token through their browser. The registration token is resolved
/// through this API to obtain a <code>CustomerIdentifier</code> along with the <code>CustomerAWSAccountId</code>
/// and <code>ProductCode</code>.
///
/// <note>
/// <para>
/// The API needs to called from the seller account id used to publish the SaaS application
/// to successfully resolve the token.
/// </para>
///
/// <para>
/// For an example of using <code>ResolveCustomer</code>, see <a href="https://docs.aws.amazon.com/marketplace/latest/userguide/saas-code-examples.html#saas-resolvecustomer-example">
/// ResolveCustomer code example</a> in the <i>AWS Marketplace Seller Guide</i>.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ResolveCustomer service method.</param>
///
/// <returns>The response from the ResolveCustomer service method, as returned by AWSMarketplaceMetering.</returns>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.DisabledApiException">
/// The API is disabled in the Region.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.ExpiredTokenException">
/// The submitted registration token has expired. This can happen if the buyer's browser
/// takes too long to redirect to your page, the buyer has resubmitted the registration
/// token, or your application has held on to the registration token for too long. Your
/// SaaS registration website should redeem this token as soon as it is submitted by the
/// buyer's browser.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InternalServiceErrorException">
/// An internal error has occurred. Retry your request. If the problem persists, post
/// a message with details on the AWS forums.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidTokenException">
/// Registration token is invalid.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.ThrottlingException">
/// The calls to the API are throttled.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/meteringmarketplace-2016-01-14/ResolveCustomer">REST API Reference for ResolveCustomer Operation</seealso>
public virtual ResolveCustomerResponse ResolveCustomer(ResolveCustomerRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ResolveCustomerRequestMarshaller.Instance;
options.ResponseUnmarshaller = ResolveCustomerResponseUnmarshaller.Instance;
return Invoke<ResolveCustomerResponse>(request, options);
}
/// <summary>
/// <code>ResolveCustomer</code> is called by a SaaS application during the registration
/// process. When a buyer visits your website during the registration process, the buyer
/// submits a registration token through their browser. The registration token is resolved
/// through this API to obtain a <code>CustomerIdentifier</code> along with the <code>CustomerAWSAccountId</code>
/// and <code>ProductCode</code>.
///
/// <note>
/// <para>
/// The API needs to called from the seller account id used to publish the SaaS application
/// to successfully resolve the token.
/// </para>
///
/// <para>
/// For an example of using <code>ResolveCustomer</code>, see <a href="https://docs.aws.amazon.com/marketplace/latest/userguide/saas-code-examples.html#saas-resolvecustomer-example">
/// ResolveCustomer code example</a> in the <i>AWS Marketplace Seller Guide</i>.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ResolveCustomer service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ResolveCustomer service method, as returned by AWSMarketplaceMetering.</returns>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.DisabledApiException">
/// The API is disabled in the Region.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.ExpiredTokenException">
/// The submitted registration token has expired. This can happen if the buyer's browser
/// takes too long to redirect to your page, the buyer has resubmitted the registration
/// token, or your application has held on to the registration token for too long. Your
/// SaaS registration website should redeem this token as soon as it is submitted by the
/// buyer's browser.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InternalServiceErrorException">
/// An internal error has occurred. Retry your request. If the problem persists, post
/// a message with details on the AWS forums.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.InvalidTokenException">
/// Registration token is invalid.
/// </exception>
/// <exception cref="Amazon.AWSMarketplaceMetering.Model.ThrottlingException">
/// The calls to the API are throttled.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/meteringmarketplace-2016-01-14/ResolveCustomer">REST API Reference for ResolveCustomer Operation</seealso>
public virtual Task<ResolveCustomerResponse> ResolveCustomerAsync(ResolveCustomerRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ResolveCustomerRequestMarshaller.Instance;
options.ResponseUnmarshaller = ResolveCustomerResponseUnmarshaller.Instance;
return InvokeAsync<ResolveCustomerResponse>(request, options, cancellationToken);
}
#endregion
}
}
| 54.54023
| 192
| 0.65466
|
[
"Apache-2.0"
] |
Hazy87/aws-sdk-net
|
sdk/src/Services/AWSMarketplaceMetering/Generated/_bcl45/AmazonAWSMarketplaceMeteringClient.cs
| 52,203
|
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("6.Drawing-with-Loops-Exercises")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("6.Drawing-with-Loops-Exercises")]
[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("fa727616-8888-47b8-8e7d-af593122e11f")]
// 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.72973
| 84
| 0.745987
|
[
"MIT"
] |
GerganaRibarova/Programming-Basics
|
6.Drawing-with-Loops-Exercises/6.Drawing-with-Loops-Exercises/Properties/AssemblyInfo.cs
| 1,436
|
C#
|
namespace BBT.StructureTools.Convert.Strategy
{
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using BBT.StructureTools.Convert;
/// <summary>
/// Strategy to convert entities with a <c>ToMany</c> relationship.
/// See <see cref="IConvertOperation{TSource,TTarget}"/>.
/// </summary>
/// <typeparam name="TSource">See link above.</typeparam>
/// <typeparam name="TTarget">See link above.</typeparam>
/// <typeparam name="TSourceValue">See link above.</typeparam>
/// <typeparam name="TTargetValue">See link above.</typeparam>
/// <typeparam name="TReverseRelation">See link above.</typeparam>
/// <typeparam name="TConvertIntention">See link above.</typeparam>
public interface IOperationCreateToManyWithReverseRelation<TSource, TTarget, TSourceValue, TTargetValue, TReverseRelation, TConvertIntention>
: IConvertOperation<TSource, TTarget>
where TSource : class
where TTarget : class
where TSourceValue : class
where TTargetValue : class
where TReverseRelation : class
where TConvertIntention : IBaseConvertIntention
{
/// <summary>
/// Initializes the <see cref="IConvertOperation{TSource,TTarget}"/>.
/// </summary>
/// <param name="sourceFunc">Declares the source values.</param>
/// <param name="targetExpression">Declares the collection property on target.</param>
/// <param name="createConvertHelper">Used to create the collection entries on target.</param>
void Initialize(
Func<TSource, IEnumerable<TSourceValue>> sourceFunc,
Expression<Func<TTarget, ICollection<TTargetValue>>> targetExpression,
ICreateConvertHelper<TSourceValue, TTargetValue, TReverseRelation, TConvertIntention> createConvertHelper);
}
}
| 49.157895
| 145
| 0.689507
|
[
"MIT"
] |
bbtsoftware/BBT.StructureTools
|
src/BBT.StructureTools/Convert/Strategy/IOperationCreateToManyWithReverseRelation.cs
| 1,870
|
C#
|
// Copyright © 2018, Meta Company. All rights reserved.
//
// Redistribution and use of this software (the "Software") in binary form, without modification, is
// permitted provided that the following conditions are met:
//
// 1. Redistributions of the unmodified Software 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.
// 2. The name of Meta Company (“Metaâ€) may not be used to endorse or promote products derived
// from this Software without specific prior written permission from Meta.
// 3. LIMITATION TO META PLATFORM: Use of the Software is limited to use on or in connection
// with Meta-branded devices or Meta-branded software development kits. For example, a bona
// fide recipient of the Software may incorporate an unmodified binary version of the
// Software into an application limited to use on or in connection with a Meta-branded
// device, while he or she may not incorporate an unmodified binary version of the Software
// into an application designed or offered for use on a non-Meta-branded device.
//
// For the sake of clarity, the Software may not be redistributed under any circumstances in source
// code form, or in the form of modified binary code – and nothing in this License shall be construed
// to permit such redistribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "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 META COMPANY BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using Meta.Extensions;
using UnityEngine;
using UnityEngine.EventSystems;
namespace Meta.Mouse
{
/// <summary>
/// Handles scaling of an object using the mouse scrollwheel.
/// </summary>
public class DragScale : MonoBehaviour, IDragHandler
{
/// <summary>
/// Transform to scale
/// </summary>
[SerializeField]
private Transform _scaleTransform;
[SerializeField]
private float _scaleMultiplier = .05f;
[SerializeField]
private float _maxScale = 5;
[SerializeField]
private float _minScale = .2f;
/// <summary>
/// Input Button that activates the interaction
/// </summary>
[SerializeField]
private PointerEventData.InputButton _button = PointerEventData.InputButton.Middle;
/// <summary>
/// Input Button that activates the interaction when a modifier key is used
/// </summary>
[SerializeField]
private PointerEventData.InputButton _altButton = PointerEventData.InputButton.Left;
/// <summary>
/// Keys that activate the interaction
/// </summary>
[SerializeField]
private KeySet _keyCodes;
private void Awake()
{
if (_scaleTransform == null)
{
_scaleTransform = transform;
}
if (_keyCodes == null)
{
Debug.LogWarningFormat("No KeySet specified on {0}! This is fine if you don't want the Alt Button to require a modifier key.", name);
}
}
public void OnDrag(PointerEventData eventData)
{
if (eventData.button == _button || (eventData.button == _altButton && (_keyCodes == null || _keyCodes.IsPressed())))
{
float scaleValue = eventData.delta.y * _scaleMultiplier;
Vector3 newScale = _scaleTransform.localScale.Add(scaleValue);
if (newScale.LargestComponent() < _maxScale && newScale.SmallestComponent() > _minScale)
{
_scaleTransform.localScale = newScale;
}
}
}
}
}
| 45
| 149
| 0.660606
|
[
"MIT"
] |
JDZ-3/MXRManipulation
|
Assets/MetaSDK/Meta/Mouse/Scripts/DragScale.cs
| 4,472
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.Storage.Models;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Compute.Tests
{
public class OSProfileTests : VMTestBase
{
private static readonly string CustomData = Convert.ToBase64String(Encoding.UTF8.GetBytes("echo 'Hello World'"));
private const PassNames OOBESystem = PassNames.OobeSystem;
private const ComponentNames MicrosoftWindowsShellSetup = ComponentNames.MicrosoftWindowsShellSetup;
private const SettingNames AutoLogon = SettingNames.AutoLogon;
private const string PacificStandardTime = "Pacific Standard Time";
private const string WinRMCertificateResourceName = "WinRMCertificateResource";
private const string DefaultSshPublicKey =
"MIIDszCCApugAwIBAgIJALBV9YJCF/tAMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV" +
"BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX" +
"aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzIyMjI1NDQ5WhcNMTYwMzIxMjI1NDQ5WjBF" +
"MQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50" +
"ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIDANBgkqhkiG9w0BAQEFAAOCAQ0AMIIB" +
"CAKCAQEAxDC+OfmB+tQ+P1MLmuuW2hJLdcK8m4DLgAk5l8bQDNBcVezt+bt/ZFMs" +
"CHBhfTZG9O9yqMn8IRUh7/7jfQm6DmXCgtxj/uFiwT+F3out5uWvMV9SjFYvu9kJ" +
"NXiDC2u3l4lHV8eHde6SbKiZB9Jji9FYQV4YiWrBa91j9I3hZzbTL0UCiJ+1PPoL" +
"Rx/T1s9KT5Wn8m/z2EDrHWpetYu45OA7nzyIFOyQup5oWadWNnpk6HkCGutl9t9b" +
"cLdjXjXPm9wcy1yxIB3Dj/Y8Hnulr80GJlUtUboDm8TExGc4YaPJxdn0u5igo5gZ" +
"c6qnqH/BMd1nsyICx6AZnKBXBycoSQIBI6OBpzCBpDAdBgNVHQ4EFgQUzWhrCCDs" +
"ClANCGlKZ64rHp2BDn0wdQYDVR0jBG4wbIAUzWhrCCDsClANCGlKZ64rHp2BDn2h" +
"SaRHMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQK" +
"ExhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGSCCQCwVfWCQhf7QDAMBgNVHRMEBTAD" +
"AQH/MA0GCSqGSIb3DQEBBQUAA4IBAQCUaJnX0aBzwBkbJrBS5YvkZnNKLdc4oHgC" +
"/Nsr/9pwXzFYYXkdqpTw2nygH0C0WuPVVrG3Y3EGx/UIGDtLbwMvZJhQN9mZH3oX" +
"+c3HGqBnXGuDRrtsfsK1ywAofx9amZfKNk/04/Rt3POdbyD1/AOADw2zMokbIapX" +
"+nMDUtD/Tew9+0qU9+dcFMrFE1N4utlrFHlrLFbiCA/eSegP6gOeu9mqZv7UHIz2" +
"oe6IQTw7zJF7xuBIzTYwjOCM197GKW7xc4GU4JZIN+faZ7njl/fxfUNdlqvgZUUn" +
"kfdrzU3PZPl0w9NuncgEje/PZ+YtZvIsnH7MLSPeIGNQwW6V2kc8";
private void EnableWinRMCustomDataAndUnattendContent(string rgName, string keyVaultName, string winRMCertificateUrl, string autoLogonContent, VirtualMachine inputVM)
{
var osProfile = inputVM.OsProfile;
osProfile.CustomData = CustomData;
osProfile.WindowsConfiguration = new WindowsConfiguration
{
ProvisionVMAgent = true,
EnableAutomaticUpdates = false,
TimeZone = PacificStandardTime,
AdditionalUnattendContent = new List<AdditionalUnattendContent>
{
new AdditionalUnattendContent
{
PassName = OOBESystem,
ComponentName = MicrosoftWindowsShellSetup,
SettingName = AutoLogon,
Content = autoLogonContent
}
},
WinRM = new WinRMConfiguration
{
Listeners = new List<WinRMListener>
{
new WinRMListener
{
Protocol = ProtocolTypes.Http,
CertificateUrl = null,
},
new WinRMListener
{
Protocol = ProtocolTypes.Https,
CertificateUrl = winRMCertificateUrl,
}
}
}
};
osProfile.Secrets = new List<VaultSecretGroup>
{
new VaultSecretGroup
{
SourceVault = SecretVaultHelper.GetVaultId(m_subId, rgName, keyVaultName).Result,
VaultCertificates = new List<VaultCertificate>
{
new VaultCertificate
{
CertificateStore = "My",
CertificateUrl = winRMCertificateUrl
}
}
}
};
}
private void ValidateWinRMCustomDataAndUnattendContent(string winRMCertificateUrl, string autoLogonContent, VirtualMachine outputVM)
{
var osProfile = outputVM.OsProfile;
// CustomData:
Assert.Equal(osProfile.CustomData, CustomData);
Assert.Null(osProfile.LinuxConfiguration);
Assert.NotNull(osProfile.WindowsConfiguration);
Assert.True(osProfile.WindowsConfiguration.ProvisionVMAgent != null && osProfile.WindowsConfiguration.ProvisionVMAgent.Value);
Assert.True(osProfile.WindowsConfiguration.EnableAutomaticUpdates != null && !osProfile.WindowsConfiguration.EnableAutomaticUpdates.Value);
// TimeZone
Assert.Equal(PacificStandardTime, osProfile.WindowsConfiguration.TimeZone);
// WinRM
Assert.NotNull(osProfile.WindowsConfiguration.WinRM);
var listeners = osProfile.WindowsConfiguration.WinRM.Listeners;
Assert.NotNull(listeners);
Assert.Equal(2, listeners.Count);
if (listeners[0].Protocol == ProtocolTypes.Http)
{
Assert.Null(listeners[0].CertificateUrl);
Assert.True(listeners[1].Protocol == ProtocolTypes.Https);
#if NET46
Assert.True(listeners[1].CertificateUrl.Equals(winRMCertificateUrl, StringComparison.OrdinalIgnoreCase));
#else
Assert.Equal(listeners[1].CertificateUrl, winRMCertificateUrl, ignoreCase: true);
#endif
}
else if (listeners[0].Protocol == ProtocolTypes.Https)
{
#if NET46
Assert.True(listeners[0].CertificateUrl.Equals(winRMCertificateUrl, StringComparison.OrdinalIgnoreCase));
#else
Assert.Equal(listeners[0].CertificateUrl, winRMCertificateUrl, ignoreCase: true);
#endif
Assert.True(listeners[1].Protocol == ProtocolTypes.Http);
Assert.Null(listeners[1].CertificateUrl);
}
else
{
// Unexpected value for winRM Listener protocol
Assert.True(false);
}
// AdditionalUnattendContent
var additionalContents = osProfile.WindowsConfiguration.AdditionalUnattendContent;
Assert.NotNull(additionalContents);
Assert.Equal(1, additionalContents.Count);
Assert.Equal(OOBESystem, additionalContents[0].PassName);
Assert.Equal(MicrosoftWindowsShellSetup, additionalContents[0].ComponentName);
Assert.Equal(AutoLogon, additionalContents[0].SettingName);
Assert.Equal(autoLogonContent, additionalContents[0].Content);
}
// See recording instructions in HyakSpec\ReadMe.txt. The key vault URLs produced by the script are plugged
// into SecretVaultHelper, below.
[Fact(Skip = "Secret Vault")]
public void TestVMWithWindowsOSProfile()
{
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
EnsureClientsInitialized(context);
string rgName = ComputeManagementTestUtilities.GenerateName(TestPrefix);
string keyVaultName = ComputeManagementTestUtilities.GenerateName(TestPrefix);
string winRMCertificateBase64 = Convert.ToBase64String(
Encoding.UTF8.GetBytes(
ReadFromEmbeddedResource(typeof(OSProfileTests), WinRMCertificateResourceName)));
// The following variables are defined here to allow validation
string autoLogonContent = null;
string winRMCertificateUrl = SecretVaultHelper.AddSecret(m_subId, rgName, keyVaultName, winRMCertificateBase64).Result;
Action<VirtualMachine> enableWinRMCustomDataAndUnattendContent = inputVM =>
{
autoLogonContent = GetAutoLogonContent(5, inputVM.OsProfile.AdminUsername, inputVM.OsProfile.AdminPassword);
EnableWinRMCustomDataAndUnattendContent(rgName, keyVaultName, winRMCertificateUrl, autoLogonContent, inputVM);
};
Action<VirtualMachine> validateWinRMCustomDataAndUnattendContent =
outputVM => ValidateWinRMCustomDataAndUnattendContent(winRMCertificateUrl, autoLogonContent, outputVM);
SecretVaultHelper.CreateKeyVault(m_subId, rgName, keyVaultName).Wait();
TestVMWithOSProfile(
rgName: rgName,
useWindowsProfile: true,
vmCustomizer: enableWinRMCustomDataAndUnattendContent,
vmValidator: validateWinRMCustomDataAndUnattendContent);
SecretVaultHelper.DeleteKeyVault(m_subId, rgName, keyVaultName).Wait();
}
}
[Fact(Skip = "ReRecord due to CR change")]
[Trait("Failure", "Unable Match Http")]
public void TestVMWithLinuxOSProfile()
{
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
EnsureClientsInitialized(context);
string rgName = ComputeManagementTestUtilities.GenerateName(TestPrefix);
string sshPath = null;
Action<VirtualMachine> enableSSHAndCustomData = customizedVM =>
{
var osProfile = customizedVM.OsProfile;
sshPath = "/home/" + osProfile.AdminUsername + "/.ssh/authorized_keys";
osProfile.CustomData = CustomData;
osProfile.LinuxConfiguration = new LinuxConfiguration
{
DisablePasswordAuthentication = false,
Ssh = new SshConfiguration
{
PublicKeys = new List<SshPublicKey>
{
new SshPublicKey
{
Path = sshPath,
KeyData = DefaultSshPublicKey,
}
}
}
};
};
Action<VirtualMachine> validateWinRMCustomDataAndUnattendContent = outputVM =>
{
var osProfile = outputVM.OsProfile;
Assert.Null(osProfile.WindowsConfiguration);
Assert.NotNull(osProfile.LinuxConfiguration);
Assert.NotNull(osProfile.LinuxConfiguration.Ssh);
var publicKeys = osProfile.LinuxConfiguration.Ssh.PublicKeys;
Assert.NotNull(osProfile.LinuxConfiguration.Ssh.PublicKeys);
Assert.True(osProfile.LinuxConfiguration.DisablePasswordAuthentication != null && !osProfile.LinuxConfiguration.DisablePasswordAuthentication.Value);
Assert.Equal(1, publicKeys.Count);
Assert.Equal(sshPath, publicKeys[0].Path);
Assert.Equal(DefaultSshPublicKey, publicKeys[0].KeyData);
};
TestVMWithOSProfile(
rgName: rgName,
useWindowsProfile: false,
vmCustomizer: enableSSHAndCustomData,
vmValidator: validateWinRMCustomDataAndUnattendContent);
}
}
private void TestVMWithOSProfile(
string rgName,
bool useWindowsProfile,
Action<VirtualMachine> vmCustomizer = null,
Action<VirtualMachine> vmValidator = null)
{
string storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix);
string asName = ComputeManagementTestUtilities.GenerateName("as");
ImageReference imageRef = GetPlatformVMImage(useWindowsProfile);
VirtualMachine inputVM;
try
{
StorageAccount storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);
VirtualMachine vm = CreateVM(rgName, asName, storageAccountOutput, imageRef, out inputVM, vmCustomizer);
var getVMWithInstanceViewResponse = m_CrpClient.VirtualMachines.Get(rgName, inputVM.Name, InstanceViewTypes.InstanceView);
ValidateVMInstanceView(inputVM, getVMWithInstanceViewResponse);
var lroResponse = m_CrpClient.VirtualMachines.CreateOrUpdate(rgName, vm.Name, vm);
Assert.True(lroResponse.ProvisioningState == "Succeeded");
if (vmValidator != null)
{
vmValidator(vm);
}
m_CrpClient.VirtualMachines.BeginDelete(rgName, vm.Name);
}
finally
{
if (m_ResourcesClient != null)
{
m_ResourcesClient.ResourceGroups.Delete(rgName);
}
}
}
//Not used
public static string ReadFromEmbeddedResource(Type type, string resourceName)
{
throw new NotSupportedException("\'type.Assembly\' is not supported for cross platform");
}
private static string GetAutoLogonContent(uint logonCount, string userName, string password)
{
return string.Format(
"<AutoLogon>" +
"<Enabled>true</Enabled>" +
"<LogonCount>{0}</LogonCount>" +
"<Username>{1}</Username>" +
"<Password><Value>{2}</Value><PlainText>true</PlainText></Password>" +
"</AutoLogon>", logonCount, userName, password);
}
}
public static class SecretVaultHelper
{
// TODO: Please remove once KeyVault ARM client is ready and replace by actual calls to the service.
// Currently, for new recroding of TestVMWithWindowsOSProfile supporting WinRM with Https listeners, we need to
// have a certifcate in KeyVault. To do that, we:
// 1. Execute the script CreateKeyVaultAndCertificateScript.ps1 -SubscriptionName: <subscriptionName>
// using appropriate SubscriptionName (you can change Region, ResourceGroupName, and KeyVaultName too)
// 2. Update static values below (e.g. VaultId and CertifcateUrl) with values returned when running the script
// 3. Complete the recording.
// 4. After recording completes, please delete key vault you created by deleting the whole resource group.
public static string KeyVaultId = "/subscriptions/ccfebd33-45cd-4e22-9389-98982441aa5d/resourceGroups/pslibtestosprofile/providers/Microsoft.KeyVault/vaults/pslibtestkeyvault";
public static Uri CertificateUrl = new Uri("https://pslibtestkeyvault.vault.azure.net:443/secrets/WinRM/24c727e7449b47cb9d2f385113f59a63");
#pragma warning disable 1998
public static async Task CreateKeyVault(string subId, string rgName, string keyVaultName)
{
}
public static async Task DeleteKeyVault(string subId, string rgName, string keyVaultName)
{
}
public static async Task<Microsoft.Azure.Management.Compute.Models.SubResource> GetVaultId(string subId, string rgName, string keyVaultName)
{
return new Microsoft.Azure.Management.Compute.Models.SubResource { Id = KeyVaultId };
}
public static async Task<string> AddSecret(string subId, string rgName, string keyVaultName, string secret)
{
return CertificateUrl.AbsoluteUri;
}
public static async Task DeleteSecret(string subId, string rgName, string keyVaultName, string secret)
{
}
#pragma warning restore 1998
}
}
| 46.98338
| 184
| 0.613702
|
[
"MIT"
] |
MarzWorldLit/azure-sdk-for-net
|
src/SDKs/Compute/Compute.Tests/ScenarioTests/OSProfileTests.cs
| 16,963
|
C#
|
namespace Microsoft.Azure.Cosmos.SDK.EmulatorTests
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.Spatial;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
[TestClass]
public class CosmosSpatialTests
{
private ContainerInternal Container = null;
private DocumentClient documentClient;
private readonly string spatialName = "SpatialName";
protected CancellationTokenSource cancellationTokenSource = null;
protected CancellationToken cancellationToken;
protected CosmosClient cosmosClient = null;
protected Database database = null;
[TestInitialize]
public async Task TestInitialize()
{
this.cancellationTokenSource = new CancellationTokenSource();
this.cancellationToken = this.cancellationTokenSource.Token;
this.cosmosClient = TestCommon.CreateCosmosClient();
this.database = await this.cosmosClient.CreateDatabaseAsync(Guid.NewGuid().ToString(),
cancellationToken: this.cancellationToken);
this.documentClient = TestCommon.CreateClient(true, defaultConsistencyLevel: Documents.ConsistencyLevel.Session);
string PartitionKey = "/partitionKey";
ContainerResponse response = await this.database.CreateContainerAsync(
new ContainerProperties(id: Guid.NewGuid().ToString(), partitionKeyPath: PartitionKey),
cancellationToken: this.cancellationToken);
Assert.IsNotNull(response);
Assert.IsNotNull(response.Container);
Assert.IsNotNull(response.Resource);
this.Container = (ContainerInlineCore)response;
}
[TestCleanup]
public async Task Cleanup()
{
if (this.documentClient != null)
{
this.documentClient.Dispose();
}
if (this.cosmosClient == null)
{
return;
}
if (this.database != null)
{
await this.database.DeleteStreamAsync(
requestOptions: null,
cancellationToken: this.cancellationToken);
}
this.cancellationTokenSource?.Cancel();
this.cosmosClient.Dispose();
}
[TestMethod]
public async Task CreateDropMultiPolygonTest()
{
SpatialItem spatialItem = new SpatialItem
{
Name = spatialName,
partitionKey = Guid.NewGuid().ToString(),
id = Guid.NewGuid().ToString(),
multiPolygon = this.GetMultiPoygon(),
};
ItemResponse<SpatialItem> createResponse = await this.Container.CreateItemAsync<SpatialItem>(item: spatialItem);
Assert.IsNotNull(createResponse);
Assert.AreEqual(HttpStatusCode.Created, createResponse.StatusCode);
ItemResponse<SpatialItem> readResponse = await this.Container.ReadItemAsync<SpatialItem>(partitionKey: new Cosmos.PartitionKey(spatialItem.partitionKey), id: spatialItem.id);
Assert.IsNotNull(readResponse);
Assert.AreEqual(HttpStatusCode.OK, readResponse.StatusCode);
Assert.IsNotNull(readResponse.Resource.multiPolygon);
IOrderedQueryable<SpatialItem> multipolygonQuery =
this.documentClient.CreateDocumentQuery<SpatialItem>(this.Container.LinkUri.OriginalString, new FeedOptions() { EnableScanInQuery = true, EnableCrossPartitionQuery = true });
SpatialItem[] withinQuery = multipolygonQuery
.Where(f => f.multiPolygon.Within(this.GetMultiPoygon()) && f.multiPolygon.IsValid())
.ToArray();
Assert.IsTrue(withinQuery.Length == 1);
foreach (SpatialItem item in withinQuery)
{
Assert.IsTrue(item.multiPolygon.Equals(this.GetMultiPoygon()));
}
ItemResponse<SpatialItem> deleteResponse = await this.Container.DeleteItemAsync<SpatialItem>(partitionKey: new Cosmos.PartitionKey(spatialItem.partitionKey), id: spatialItem.id);
Assert.IsNotNull(deleteResponse);
Assert.AreEqual(HttpStatusCode.NoContent, deleteResponse.StatusCode);
}
[TestMethod]
public async Task CreateDropPolygonTest()
{
SpatialItem spatialItem = new SpatialItem
{
Name = spatialName,
partitionKey = Guid.NewGuid().ToString(),
id = Guid.NewGuid().ToString(),
polygon = this.GetPolygon(),
};
ItemResponse<SpatialItem> createResponse = await this.Container.CreateItemAsync<SpatialItem>(item: spatialItem);
Assert.IsNotNull(createResponse);
Assert.AreEqual(HttpStatusCode.Created, createResponse.StatusCode);
ItemResponse<SpatialItem> readResponse = await this.Container.ReadItemAsync<SpatialItem>(partitionKey: new Cosmos.PartitionKey(spatialItem.partitionKey), id: spatialItem.id);
Assert.IsNotNull(readResponse);
Assert.AreEqual(HttpStatusCode.OK, readResponse.StatusCode);
Assert.IsNotNull(readResponse.Resource.polygon);
ItemResponse<SpatialItem> deleteResponse = await this.Container.DeleteItemAsync<SpatialItem>(partitionKey: new Cosmos.PartitionKey(spatialItem.partitionKey), id: spatialItem.id);
Assert.IsNotNull(deleteResponse);
Assert.AreEqual(HttpStatusCode.NoContent, deleteResponse.StatusCode);
}
[TestMethod]
public async Task CreateDropLineStringTest()
{
SpatialItem spatialItem = new SpatialItem
{
Name = spatialName,
partitionKey = Guid.NewGuid().ToString(),
id = Guid.NewGuid().ToString(),
lineString = this.GetLineString(),
};
ItemResponse<SpatialItem> createResponse = await this.Container.CreateItemAsync<SpatialItem>(item: spatialItem);
Assert.IsNotNull(createResponse);
Assert.AreEqual(HttpStatusCode.Created, createResponse.StatusCode);
ItemResponse<SpatialItem> readResponse = await this.Container.ReadItemAsync<SpatialItem>(partitionKey: new Cosmos.PartitionKey(spatialItem.partitionKey), id: spatialItem.id);
Assert.IsNotNull(readResponse);
Assert.AreEqual(HttpStatusCode.OK, readResponse.StatusCode);
Assert.IsNotNull(readResponse.Resource.lineString);
ItemResponse<SpatialItem> deleteResponse = await this.Container.DeleteItemAsync<SpatialItem>(partitionKey: new Cosmos.PartitionKey(spatialItem.partitionKey), id: spatialItem.id);
Assert.IsNotNull(deleteResponse);
Assert.AreEqual(HttpStatusCode.NoContent, deleteResponse.StatusCode);
}
[TestMethod]
public async Task CreateDropPointTest()
{
SpatialItem spatialItem = new SpatialItem
{
Name = spatialName,
partitionKey = Guid.NewGuid().ToString(),
id = Guid.NewGuid().ToString(),
point = this.GetPoint(),
};
ItemResponse<SpatialItem> createResponse = await this.Container.CreateItemAsync<SpatialItem>(item: spatialItem);
Assert.IsNotNull(createResponse);
Assert.AreEqual(HttpStatusCode.Created, createResponse.StatusCode);
ItemResponse<SpatialItem> readResponse = await this.Container.ReadItemAsync<SpatialItem>(partitionKey: new Cosmos.PartitionKey(spatialItem.partitionKey), id: spatialItem.id);
Assert.IsNotNull(readResponse);
Assert.AreEqual(HttpStatusCode.OK, readResponse.StatusCode);
Assert.IsNotNull(readResponse.Resource.point);
ItemResponse<SpatialItem> deleteResponse = await this.Container.DeleteItemAsync<SpatialItem>(partitionKey: new Cosmos.PartitionKey(spatialItem.partitionKey), id: spatialItem.id);
Assert.IsNotNull(deleteResponse);
Assert.AreEqual(HttpStatusCode.NoContent, deleteResponse.StatusCode);
}
internal class SpatialItem
{
[JsonProperty("name")]
public string Name { get; set; }
public string id { get; set; }
[JsonProperty("point")]
public Point point { get; set; }
[JsonProperty("polygon")]
public Polygon polygon { get; set; }
[JsonProperty("lineString")]
public LineString lineString { get; set; }
[JsonProperty("partitionKey")]
public string partitionKey { get; set; }
[JsonProperty("MultiPointLocation")]
public MultiPolygon multiPolygon { get; set; }
}
private MultiPolygon GetMultiPoygon()
{
MultiPolygon multiPolygon =
new MultiPolygon(
new[]
{
new PolygonCoordinates(
new[]
{
new LinearRing(
new[]
{
new Position(20, 20), new Position(20, 21), new Position(21, 21),
new Position(21, 20), new Position(20, 20)
})
})
});
return multiPolygon;
}
private Polygon GetPolygon()
{
Polygon polygon = new Polygon(
new[]
{
new LinearRing(
new[]
{
new Position(20, 20),
new Position(20, 21),
new Position(21, 21),
new Position(21, 20),
new Position(22, 20)
})
},
new GeometryParams
{
AdditionalProperties = new Dictionary<string, object> { { "b", "c" } },
BoundingBox = new BoundingBox(new Position(0, 0), new Position(40, 40)),
Crs = Crs.Named("SomeCrs")
});
return polygon;
}
private LineString GetLineString()
{
LineString lineString = new LineString(
new[] {
new Position(20, 30), new Position(30, 40) },
new GeometryParams
{
AdditionalProperties = new Dictionary<string, object> { { "a", "b" } },
BoundingBox = new BoundingBox(new Position(0, 0), new Position(40, 40)),
Crs = Crs.Named("SomeCrs")
});
return lineString;
}
private Point GetPoint()
{
Point point = new Point(
new Position(20, 30),
new GeometryParams
{
AdditionalProperties = new Dictionary<string, object> { { "a", "b" } },
BoundingBox = new BoundingBox(new Position(0, 0), new Position(40, 40)),
Crs = Crs.Named("SomeCrs")
});
return point;
}
}
}
| 42.860215
| 190
| 0.565563
|
[
"MIT"
] |
Camios/azure-cosmos-dotnet-v3
|
Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.EmulatorTests/CosmosSpatialTests.cs
| 11,960
|
C#
|
using System;
namespace Rafi
{
internal class Names
{
public static string[] Csr { get; } = new string[0x1000];
public static string[] IntReg { get; } = new string[32];
static Names()
{
Csr[0x000] = "ustatus";
Csr[0x001] = "fflags";
Csr[0x002] = "frm";
Csr[0x003] = "fcsr";
Csr[0x004] = "uie";
Csr[0x005] = "utvec";
Csr[0x040] = "uscratch";
Csr[0x041] = "uepc";
Csr[0x042] = "ucause";
Csr[0x043] = "utval";
Csr[0x044] = "uip";
Csr[0x100] = "sstatus";
Csr[0x102] = "sedeleg";
Csr[0x103] = "sideleg";
Csr[0x104] = "sie";
Csr[0x105] = "stvec";
Csr[0x106] = "scounteren";
Csr[0x140] = "sscratch";
Csr[0x141] = "sepc";
Csr[0x142] = "scause";
Csr[0x143] = "stval";
Csr[0x144] = "sip";
Csr[0x180] = "satp";
Csr[0x300] = "mstatus";
Csr[0x301] = "misa";
Csr[0x302] = "medeleg";
Csr[0x303] = "mideleg";
Csr[0x304] = "mie";
Csr[0x305] = "mtvec";
Csr[0x306] = "mcounteren";
for (int i = 3; i < 32; i++)
{
Csr[0x320 + i] = $"mhpmevent{i}";
}
Csr[0x340] = "mscratch";
Csr[0x341] = "mepc";
Csr[0x342] = "mcause";
Csr[0x343] = "mtval";
Csr[0x344] = "mip";
for (int i = 0; i < 4; i++)
{
Csr[0x3a0 + i] = $"pmpcfg{i}";
}
for (int i = 3; i < 16; i++)
{
Csr[0x3b0 + i] = $"pmpaddr{i}";
}
Csr[0x7a0] = "tselect";
Csr[0x7a1] = "tdata1";
Csr[0x7a2] = "tdata2";
Csr[0x7a3] = "tdata3";
Csr[0x7b0] = "dcsr";
Csr[0x7b1] = "dpc";
Csr[0x7b2] = "dscratch";
Csr[0xb00] = "mcycle";
Csr[0xb01] = "mtime";
Csr[0xb02] = "minstret";
for (int i = 3; i < 32; i++)
{
Csr[0xb00 + i] = $"mhpmcounter{i}";
}
Csr[0xb80] = "mcycleh";
Csr[0xb81] = "mtimeh";
Csr[0xb82] = "minstreth";
for (int i = 3; i < 32; i++)
{
Csr[0xb80 + i] = $"mhpmcounter{i}h";
}
Csr[0xc00] = "cycle";
Csr[0xc01] = "time";
Csr[0xc02] = "instret";
for (int i = 3; i < 32; i++)
{
Csr[0xc00 + i] = $"hpmcounter{i}";
}
Csr[0xc80] = "cycleh";
Csr[0xc81] = "timeh";
Csr[0xc82] = "instreth";
for (int i = 3; i < 32; i++)
{
Csr[0xc80 + i] = $"hpmcounter{i}h";
}
Csr[0xf11] = "mvendorid";
Csr[0xf12] = "marchid";
Csr[0xf13] = "mimpid";
Csr[0xf14] = "mhartid";
IntReg[0] = "zero";
IntReg[1] = "ra";
IntReg[2] = "sp";
IntReg[3] = "gp";
IntReg[4] = "tp";
IntReg[5] = "t0";
IntReg[6] = "t1";
IntReg[7] = "t2";
IntReg[8] = "s0";
IntReg[9] = "s1";
IntReg[10] = "a0";
IntReg[11] = "a1";
IntReg[12] = "a2";
IntReg[13] = "a3";
IntReg[14] = "a4";
IntReg[15] = "a5";
IntReg[16] = "a6";
IntReg[17] = "a7";
IntReg[18] = "s2";
IntReg[19] = "s3";
IntReg[20] = "s4";
IntReg[21] = "s5";
IntReg[22] = "s6";
IntReg[23] = "s7";
IntReg[24] = "s8";
IntReg[25] = "s9";
IntReg[26] = "s10";
IntReg[27] = "s11";
IntReg[28] = "t3";
IntReg[29] = "t4";
IntReg[30] = "t5";
IntReg[31] = "t6";
}
}
}
| 29.042553
| 65
| 0.357509
|
[
"Apache-2.0"
] |
fjt7tdmi/rafi-emu-csharp
|
Rafi/Def/Names.cs
| 4,097
|
C#
|
using FlowScriptEngine;
namespace FlowScriptEngineBasic.FlowSourceObjects.Array
{
[ToolTipText("Array_BinarySearch_Summary")]
public partial class BinarySearchFlowSourceObject : ArrayFlowSourceObjectBase
{
[ToolTipText("Array_BinarySearch_Compare")]
public event FlowEventHandler Compare;
public override string Name
{
get { return "Array.BinarySearch"; }
}
[ToolTipText("Array_BinarySearch_Value")]
public object Value
{
private get;
set;
}
[ToolTipText("Array_BinarySearch_X")]
public object X
{
get;
private set;
}
[ToolTipText("Array_BinarySearch_Y")]
public object Y
{
get;
private set;
}
[ToolTipText("Array_BinarySearch_Result")]
public int Result
{
private get;
set;
}
[ToolTipText("Array_BinarySearch_FoundIndex")]
public int FoundIndex
{
get;
private set;
}
public override void In(FlowScriptEngine.FlowEventArgs e)
{
SetArray();
if (Array != null)
{
SetValue(nameof(Value));
var comparer = new CallbackComparer((x, y) =>
{
X = x;
Y = y;
FireEvent(Compare, true);
ProcessChildEvent();
SetValue(nameof(Result));
return Result;
});
FoundIndex = System.Array.BinarySearch(Array, Value, comparer);
OnSuccess();
}
else
{
OnFailed();
}
}
}
}
| 24.25
| 81
| 0.478568
|
[
"Apache-2.0"
] |
KHCmaster/PPD
|
Win/FlowScriptEngineBasic/FlowSourceObjects/Array/BinarySearchFlowSourceObject.cs
| 1,845
|
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.AzureNative.DataMigration.V20180715Preview.Outputs
{
[OutputType]
public sealed class GetUserTablesPostgreSqlTaskPropertiesResponse
{
/// <summary>
/// Key value pairs of client data to attach meta data information to task
/// </summary>
public readonly ImmutableDictionary<string, string>? ClientData;
/// <summary>
/// Array of command properties.
/// </summary>
public readonly ImmutableArray<Union<Outputs.MigrateMISyncCompleteCommandPropertiesResponse, Outputs.MigrateSyncCompleteCommandPropertiesResponse>> Commands;
/// <summary>
/// Array of errors. This is ignored if submitted.
/// </summary>
public readonly ImmutableArray<Outputs.ODataErrorResponse> Errors;
/// <summary>
/// Task input
/// </summary>
public readonly Outputs.GetUserTablesPostgreSqlTaskInputResponse? Input;
/// <summary>
/// Task output. This is ignored if submitted.
/// </summary>
public readonly ImmutableArray<Outputs.GetUserTablesPostgreSqlTaskOutputResponse> Output;
/// <summary>
/// The state of the task. This is ignored if submitted.
/// </summary>
public readonly string State;
/// <summary>
/// Task type.
/// Expected value is 'GetUserTablesPostgreSql'.
/// </summary>
public readonly string TaskType;
[OutputConstructor]
private GetUserTablesPostgreSqlTaskPropertiesResponse(
ImmutableDictionary<string, string>? clientData,
ImmutableArray<Union<Outputs.MigrateMISyncCompleteCommandPropertiesResponse, Outputs.MigrateSyncCompleteCommandPropertiesResponse>> commands,
ImmutableArray<Outputs.ODataErrorResponse> errors,
Outputs.GetUserTablesPostgreSqlTaskInputResponse? input,
ImmutableArray<Outputs.GetUserTablesPostgreSqlTaskOutputResponse> output,
string state,
string taskType)
{
ClientData = clientData;
Commands = commands;
Errors = errors;
Input = input;
Output = output;
State = state;
TaskType = taskType;
}
}
}
| 35.902778
| 165
| 0.654932
|
[
"Apache-2.0"
] |
pulumi-bot/pulumi-azure-native
|
sdk/dotnet/DataMigration/V20180715Preview/Outputs/GetUserTablesPostgreSqlTaskPropertiesResponse.cs
| 2,585
|
C#
|
namespace genny.Interfaces.Repositories;
public interface IRepositoryFactory
{
IConnectionDescriptionRepository ConnectionDescriptionRepository { get; }
IDatabaseObjectRepository DatabaseObjectRepository { get; }
}
| 31.857143
| 77
| 0.838565
|
[
"MIT"
] |
stho32/M001-WebApp-X-CSharp-001
|
Source/genny/genny.Interfaces/Repositories/IRepositoryFactory.cs
| 223
|
C#
|
//-----------------------------------------------------------------------
// <copyright file="IRetryPolicyAction.cs">
// Copyright (c) 2015 Adam Craven. All rights reserved.
// </copyright>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//-----------------------------------------------------------------------
namespace ChannelAdam.TransientFaultHandling
{
using System;
/// <summary>
/// Interface for a retry policy.
/// </summary>
public interface IRetryPolicyAction
{
/// <summary>
/// Repetitively executes the specified action while it satisfies the current retry policy.
/// </summary>
/// <param name="action">A delegate that represents the executable action that doesn't return any results.</param>
void Execute(Action action);
}
}
| 40.090909
| 122
| 0.622071
|
[
"Apache-2.0"
] |
channeladam/ChannelAdam.Core
|
src/ChannelAdam.Core/TransientFaultHandling/IRetryPolicyAction.cs
| 1,325
|
C#
|
using System;
using System.Net;
using System.Net.Http;
namespace NSW.StarCitizen.Tools.Repository
{
public static class HttpNetClient
{
private static readonly HttpClientHandler _clientHandler;
public static HttpClient Client { get; }
static HttpNetClient()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
_clientHandler = new HttpClientHandler();
_clientHandler.UseProxy = Program.Settings.UseHttpProxy;
Client = new HttpClient(_clientHandler);
Client.DefaultRequestHeaders.UserAgent.ParseAdd($"{Program.Name}/{Program.Version.ToString(3)}");
Client.Timeout = TimeSpan.FromMinutes(1);
}
}
}
| 37.363636
| 162
| 0.695864
|
[
"MIT"
] |
defterai/SCTools
|
SCTools/SCTools/Repository/HttpNetClient.cs
| 822
|
C#
|
using System;
using System.Runtime.Serialization;
namespace Application.Common
{
[Serializable]
public class AppException : ApplicationException
{
#region "Property"
protected string _TranslationCode;
public string TranslationCode
{
get { return _TranslationCode;}
set { _TranslationCode = value; }
}
#endregion
#region "Constructor"
public AppException()
{
_TranslationCode = "";
}
public AppException(string theMessage)
{
}
#endregion
public static AppException Create(string MsgCode)
{
return Create(MsgCode,"");
}
public static AppException Create(string MsgCode, MsgBuilder builder)
{
RawMessage themsg = MsgRepository.GetMessage(MsgCode);
builder.MsgRepository[MsgCode] = themsg.ToString();
string thedynamicmsg = builder.BuildMessage(MsgCode);
return Create(MsgCode, thedynamicmsg);
}
public static AppException Create(string MsgCode, string theMsg)
{
string theException = MsgCode;
return new AppException(string.Format("AppException/{0}",theException));
}
}
}
| 26.34
| 84
| 0.585421
|
[
"MIT"
] |
uon-coehm/IQCare
|
SourceBase/DataAccess/Application.Common/AppException.cs
| 1,317
|
C#
|
using CommunityToolkit.Mvvm.ComponentModel;
using Windows.Gaming.Input;
namespace UnoGamepad
{
public class GamepadViewModel : ObservableObject
{
private static int _id = 0;
public GamepadViewModel(Gamepad gamepad)
{
Id = ++_id;
Gamepad = gamepad;
}
public Gamepad Gamepad { get; }
public int Id { get; }
public void Update()
{
var reading = Gamepad.GetCurrentReading();
Buttons = reading.Buttons.ToString("g");
RightThumbstickX = reading.RightThumbstickX.ToString("0.00");
RightThumbstickY = reading.RightThumbstickY.ToString("0.00");
LeftThumbstickX = reading.LeftThumbstickX.ToString("0.00");
LeftThumbstickY = reading.LeftThumbstickY.ToString("0.00");
LeftTrigger = reading.LeftTrigger.ToString("0.00");
RightTrigger = reading.RightTrigger.ToString("0.00");
OnPropertyChanged("");
}
public string Buttons { get; private set; }
public string RightThumbstickX { get; private set; }
public string RightThumbstickY { get; private set; }
public string LeftThumbstickX { get; private set; }
public string LeftThumbstickY { get; private set; }
public string LeftTrigger { get; private set; }
public string RightTrigger { get; private set; }
}
}
| 29.469388
| 73
| 0.608033
|
[
"MIT"
] |
MartinZikmund/blog-2022
|
UnoGamepad/UnoGamepad.Shared/GamepadViewModel.cs
| 1,446
|
C#
|
using System;
using System.Collections.Generic;
using Android.Content;
using Com.Adjust.Test;
namespace TestApp
{
public class CommandListener : Java.Lang.Object, ICommandListener
{
private readonly AdjustCommandExecutor _adjustCommandExecutor;
public CommandListener(Context context)
{
_adjustCommandExecutor = new AdjustCommandExecutor(context);
}
public void SetTestLibrary(TestLibrary testLibrary)
{
_adjustCommandExecutor?.SetTestLibrary(testLibrary);
}
public void ExecuteCommand(string className, string methodName, IDictionary<string, IList<string>> parameters)
{
Command command = new Command(className, methodName, parameters);
switch (className.ToLower())
{
case "adjust":
_adjustCommandExecutor.ExecuteCommand(command);
break;
default:
Console.WriteLine("Could not find {0} class to execute", className);
break;
}
}
}
}
| 30.675676
| 118
| 0.597357
|
[
"MIT"
] |
hungrydk/xamarin_sdk
|
android/Test/TestApp/CommandListener.cs
| 1,137
|
C#
|
using System.ServiceModel.Channels;
namespace WcfCoreMtomEncoder
{
public class MtomMessageEncoderFactory : MessageEncoderFactory
{
private readonly MessageEncoderFactory _innerMessageEncoderFactory;
public MtomMessageEncoderFactory(MessageEncoderFactory innerMessageEncoderFactory)
{
_innerMessageEncoderFactory = innerMessageEncoderFactory;
}
public override MessageEncoder CreateSessionEncoder()
{
return new MtomMessageEncoder(_innerMessageEncoderFactory.CreateSessionEncoder());
}
public override MessageEncoder Encoder => new MtomMessageEncoder(_innerMessageEncoderFactory.Encoder);
public override MessageVersion MessageVersion => _innerMessageEncoderFactory.MessageVersion;
}
}
| 34.73913
| 110
| 0.755945
|
[
"MIT"
] |
LokiMidgard/WcfCoreMtomEncoder
|
src/WcfCoreMtomEncoder/MtomMessageEncoderFactory.cs
| 801
|
C#
|
using System;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace UnityPoc.Areas.HelpPage.ModelDescriptions
{
internal static class ModelNameHelper
{
// Modify this to provide custom model name mapping.
public static string GetModelName(Type type)
{
ModelNameAttribute modelNameAttribute = type.GetCustomAttribute<ModelNameAttribute>();
if (modelNameAttribute != null && !String.IsNullOrEmpty(modelNameAttribute.Name))
{
return modelNameAttribute.Name;
}
string modelName = type.Name;
if (type.IsGenericType)
{
// Format the generic type name to something like: GenericOfAgurment1AndArgument2
Type genericType = type.GetGenericTypeDefinition();
Type[] genericArguments = type.GetGenericArguments();
string genericTypeName = genericType.Name;
// Trim the generic parameter counts from the name
genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`'));
string[] argumentTypeNames = genericArguments.Select(t => GetModelName(t)).ToArray();
modelName = String.Format(CultureInfo.InvariantCulture, "{0}Of{1}", genericTypeName, String.Join("And", argumentTypeNames));
}
return modelName;
}
}
}
| 39.916667
| 140
| 0.635351
|
[
"MIT"
] |
tonysneed/Demo.UnityPocWithNLog
|
UnityPoc/Areas/HelpPage/ModelDescriptions/ModelNameHelper.cs
| 1,437
|
C#
|
using System.Runtime.Serialization;
namespace LogicMonitor.Api.Alerts
{
/// <summary>
/// A column specification
/// </summary>
[DataContract]
public class ColumnSpecification
{
/// <summary>
/// Whether visible
/// </summary>
[DataMember(Name = "visible")]
public bool IsVisible { get; set; }
/// <summary>
/// The label
/// </summary>
[DataMember(Name = "columnLabel")]
public string Label { get; set; }
/// <summary>
/// The key
/// </summary>
[DataMember(Name = "columnKey")]
public string Key { get; set; }
}
}
| 19.137931
| 37
| 0.621622
|
[
"MIT"
] |
tdicks/LogicMonitor.Api
|
LogicMonitor.Api/Alerts/ColumnSpecification.cs
| 555
|
C#
|
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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 ICSharpCode.Reports.Expressions.ReportingLanguage;
using NUnit.Framework;
using SimpleExpressionEvaluator;
using SimpleExpressionEvaluator.Evaluation;
using SimpleExpressionEvaluator.Utilities;
namespace ICSharpCode.Reports.Core.Test.ReportingLanguage.LanguageTests
{
[TestFixture]
[SetCulture("de-DE")]
public class PropertyEvaluator
{
[Test]
public void Can_Compile_Uknown_Variable()
{
const string expression = "varName";
var compiler = new ReportingLanguageCompiler();
IExpression compiled = compiler.CompileExpression<string>(expression);
var context = new ExpressionContext(null);
context.ResolveUnknownVariable += (sender, args) =>
{
Assert.That(args.VariableName, Is.EqualTo("varName"));
args.VariableValue = 123.456;
};
Assert.That(compiled.Evaluate(context), Is.EqualTo("123,456"));
}
[Test]
public void PropertyPathWillEvaluateFieldsAndProperties()
{
var data = TestHelper.CreateSinglePage();
PropertyPath path = data.ParsePropertyPath("PageNumber");
Assert.That(path.Evaluate(data), Is.EqualTo(15));
}
}
}
| 42.033333
| 108
| 0.679223
|
[
"MIT"
] |
galich/SharpDevelop
|
src/AddIns/Misc/Reports/ICSharpCode.Reports.Core/Test/ICSharpCode.Reports.Core.Test/ReportingLanguage/LanguageTests/PropertyEvaluator.cs
| 2,524
|
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>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("09_ForceBook")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("09_ForceBook")]
[assembly: System.Reflection.AssemblyTitleAttribute("09_ForceBook")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 41.083333
| 80
| 0.649087
|
[
"MIT"
] |
NeSh74/Fundamental-CSharp-January-2021
|
14_Associative Arrays - Exercise And More Exercise/09_ForceBook/obj/Debug/netcoreapp3.1/09_ForceBook.AssemblyInfo.cs
| 986
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using Repository;
namespace IDTO.Entity.Models
{
public class Mode : EntityBase
{
//Primary Key
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
}
| 18.142857
| 44
| 0.674541
|
[
"Apache-2.0"
] |
OSADP/IDTO
|
IDTO Azure Hosted Systems/IDTO.Entity/Models/Mode.cs
| 383
|
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Reflection;
using System;
using System.Linq;
namespace VSX.UniversalVehicleCombat.Radar
{
[CustomPropertyDrawer(typeof(LinkableVariable))]
public class TrackableVarPropertyDrawer : PropertyDrawer
{
private float itemHeight = 16;
private int spacing = 2;
private int numItemsStatic = 5;
private int numItemsDynamic = 7;
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
SerializedProperty numArgsProperty = property.FindPropertyRelative("numArgs");
int numArgs = numArgsProperty.intValue;
bool isDynamic = property.FindPropertyRelative("isLinkedVariable").boolValue;
int numItems = isDynamic ? numItemsDynamic + numArgs : numItemsStatic;
return itemHeight * numItems + spacing * 2 + spacing * (numItems - 1);
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
// Draw box background
GUI.Box(position, GUIContent.none);
// Keep a running reference to the next GUI height position, because checkboxes on/off will change the position of things
Rect runningPosition = position;
runningPosition.height = itemHeight;
runningPosition.y += spacing;
// Keep a reference to the suffix position for items preceeded by a label.
Rect suffixPosition;
// Draw property - list index
SerializedProperty listIndexProperty = property.FindPropertyRelative("listIndex");
EditorGUI.PropertyField(runningPosition, listIndexProperty);
runningPosition.y += itemHeight + spacing;
// Draw property - key
SerializedProperty keyProperty = property.FindPropertyRelative("key");
EditorGUI.PropertyField(runningPosition, keyProperty);
runningPosition.y += itemHeight + spacing;
// Draw property - variable type
SerializedProperty variableTypeProperty = property.FindPropertyRelative("variableType");
EditorGUI.PropertyField(runningPosition, variableTypeProperty);
// Get reference to the variable type and assembly qualified name
LinkableVariableType trackableVariableType = (LinkableVariableType)variableTypeProperty.enumValueIndex;
string typeName = "";
switch (trackableVariableType)
{
case LinkableVariableType.Object:
typeName = typeof(UnityEngine.Object).AssemblyQualifiedName;
break;
case LinkableVariableType.Bool:
typeName = typeof(bool).AssemblyQualifiedName;
break;
case LinkableVariableType.Int:
typeName = typeof(int).AssemblyQualifiedName;
break;
case LinkableVariableType.Float:
typeName = typeof(float).AssemblyQualifiedName;
break;
case LinkableVariableType.String:
typeName = typeof(string).AssemblyQualifiedName;
break;
case LinkableVariableType.Vector3:
typeName = typeof(Vector3).AssemblyQualifiedName;
break;
}
runningPosition.y += itemHeight + spacing;
// Draw property - is dynamic (checkbox)
SerializedProperty isDynamicVariableProperty = property.FindPropertyRelative("isLinkedVariable");
EditorGUI.PropertyField(runningPosition, isDynamicVariableProperty);
// Dynamic variable stuff
if (isDynamicVariableProperty.boolValue)
{
// Get property - target component
SerializedProperty targetComponentProperty = property.FindPropertyRelative("targetComponent");
runningPosition.y += itemHeight + spacing;
// Draw property - target object
SerializedProperty targetObjectProperty = property.FindPropertyRelative("targetObject");
EditorGUI.BeginChangeCheck();
EditorGUI.PropertyField(runningPosition, targetObjectProperty);
bool targetObjectChanged = EditorGUI.EndChangeCheck();
// Draw the components options menu for the target object
if (targetObjectProperty.objectReferenceValue != null)
{
GameObject targetGameObject = targetObjectProperty.objectReferenceValue as GameObject;
Component targetObjectComponent = targetObjectProperty.objectReferenceValue as Component;
if (targetGameObject == null)
{
if (targetObjectComponent != null)
{
targetGameObject = targetObjectComponent.gameObject;
}
}
List<Component> components = new List<Component>(targetGameObject.GetComponents<Component>());
List<string> componentNames = new List<string>();
for (int i = 0; i < components.Count; ++i)
{
if (components[i] == null) continue;
string componentTypeName = components[i].GetType().Name;
if (componentNames.Contains(componentTypeName))
{
componentNames.Add(componentTypeName + "(" + i + ")"); // Unity 2017 won't allow duplicate names in generic menu
}
else
{
componentNames.Add(componentTypeName);
}
}
int selectedComponentIndex = -1;
selectedComponentIndex = components.IndexOf((Component)targetComponentProperty.objectReferenceValue);
string buttonLabel;
if (selectedComponentIndex == -1 || targetObjectChanged)
{
if (targetObjectComponent != null && components.IndexOf(targetObjectComponent) != -1)
{
buttonLabel = targetObjectComponent.GetType().Name;
targetComponentProperty.objectReferenceValue = targetObjectComponent;
}
else
{
buttonLabel = "No Component Selected";
targetComponentProperty.objectReferenceValue = null;
}
}
else
{
buttonLabel = components[selectedComponentIndex].GetType().Name;
}
runningPosition.y += itemHeight + spacing;
// Draw component options menu button
suffixPosition = EditorGUI.PrefixLabel(runningPosition, new GUIContent("Component"));
suffixPosition = runningPosition;
suffixPosition.x = EditorGUIUtility.labelWidth;
suffixPosition.width = runningPosition.width - EditorGUIUtility.labelWidth;
if (GUI.Button(suffixPosition, new GUIContent(buttonLabel)))
{
GenericMenu componentMenu = new GenericMenu();
componentMenu.AddItem(new GUIContent("None"), false, () =>
{
property.serializedObject.Update();
targetComponentProperty.objectReferenceValue = null;
property.serializedObject.ApplyModifiedProperties();
});
foreach (Component component in components)
{
string menuLabel = component.GetType().Name;
componentMenu.AddItem(new GUIContent(component.GetType().Name), false, () =>
{
property.serializedObject.Update();
targetComponentProperty.objectReferenceValue = component;
property.serializedObject.ApplyModifiedProperties();
});
}
componentMenu.ShowAsContext();
}
}
// Get the target component as an object
UnityEngine.Object targetObject = targetComponentProperty.objectReferenceValue;
// Get all methods
MethodInfo[] methodInfos = new MethodInfo[] { };
if (targetObject != null)
{
methodInfos = targetObject.GetType().GetMethods();
}
// Get all the compatible methods
List<MethodInfo> compatibleMethodInfos = GetMethodInfos(methodInfos, typeName);
// Get the number of arguments of the currently selected method on the object
SerializedProperty numArgsProperty = property.FindPropertyRelative("numArgs");
if (targetObject == null)
{
numArgsProperty.intValue = 0;
}
// Get information about the currently selected method
SerializedProperty methodInfoNameProp = property.FindPropertyRelative("methodInfoName");
SerializedProperty arg0ObjectProperty = property.FindPropertyRelative("arg0ObjectValue");
SerializedProperty argo0TypeProperty = property.FindPropertyRelative("arg0Type");
// Get index of currently selected method
int selectedMethodIndex = -1;
// Get index of currently selected method
if (targetObject != null)
{
MethodInfo selectedMethodInfo = null;
// Get the currently selected method
if (numArgsProperty.intValue == 1)
{
selectedMethodInfo = targetObject.GetType().GetMethod(methodInfoNameProp.stringValue, new Type[] { Type.GetType(argo0TypeProperty.stringValue) });
}
else
{
selectedMethodInfo = targetObject.GetType().GetMethod(methodInfoNameProp.stringValue, new Type[] { });
}
// Update the selected index
if (selectedMethodInfo != null)
{
selectedMethodIndex = compatibleMethodInfos.IndexOf(selectedMethodInfo);
}
}
if (selectedMethodIndex == -1 && compatibleMethodInfos.Count > 0) selectedMethodIndex = 0;
// Get the display info for each of the compatible methods on the currently selected object
List<string> methodDisplayNames = new List<string>();
for (int i = 0; i < compatibleMethodInfos.Count; ++i)
{
string s = compatibleMethodInfos[i].Name;
if (s.StartsWith("get_"))
{
s = s.Substring("get_".Length);
s += " (get)";
}
if (compatibleMethodInfos[i].GetParameters().Length > 0)
{
s += "(";
s += compatibleMethodInfos[i].GetParameters()[0].ParameterType.Name.ToString();
s += ")";
}
methodDisplayNames.Add(s);
}
// Display the methods on the selected object
runningPosition.y += itemHeight + spacing;
suffixPosition = EditorGUI.PrefixLabel(runningPosition, new GUIContent("Function"));
suffixPosition = runningPosition;
suffixPosition.x = EditorGUIUtility.labelWidth;
suffixPosition.width = runningPosition.width - EditorGUIUtility.labelWidth;
selectedMethodIndex = EditorGUI.Popup(suffixPosition, selectedMethodIndex, methodDisplayNames.ToArray());
// Update the argument type for the method
if (selectedMethodIndex != -1)
{
methodInfoNameProp.stringValue = compatibleMethodInfos[selectedMethodIndex].Name;
numArgsProperty.intValue = compatibleMethodInfos[selectedMethodIndex].GetParameters().Length;
if (compatibleMethodInfos[selectedMethodIndex].GetParameters().Length > 0)
{
property.FindPropertyRelative("arg0Type").stringValue = compatibleMethodInfos[selectedMethodIndex].GetParameters()[0].ParameterType.AssemblyQualifiedName;
}
}
else
{
numArgsProperty.intValue = 0;
}
// Display the input for the argument to the selected method.
System.Type argType = Type.GetType(property.FindPropertyRelative("arg0Type").stringValue);
if (numArgsProperty.intValue != 0 && argType != null)
{
runningPosition.y += itemHeight + spacing;
if (argType == typeof(bool))
{
SerializedProperty arg0BoolProperty = property.FindPropertyRelative("arg0BoolValue");
EditorGUI.PropertyField(runningPosition, arg0BoolProperty, new GUIContent("Argument"));
}
else if (argType == typeof(int))
{
SerializedProperty arg0IntProperty = property.FindPropertyRelative("arg0IntValue");
EditorGUI.PropertyField(runningPosition, arg0IntProperty, new GUIContent("Argument"));
}
else if (argType.IsEnum)
{
string[] enumNames = System.Enum.GetNames(argType);
SerializedProperty arg0IntProperty = property.FindPropertyRelative("arg0IntValue");
suffixPosition = EditorGUI.PrefixLabel(runningPosition, new GUIContent("Argument"));
suffixPosition = runningPosition;
suffixPosition.x = EditorGUIUtility.labelWidth;
arg0IntProperty.intValue = EditorGUI.Popup(suffixPosition, arg0IntProperty.intValue, enumNames);
}
else if (argType == typeof(float))
{
SerializedProperty arg0FloatProperty = property.FindPropertyRelative("arg0FloatValue");
EditorGUI.PropertyField(runningPosition, arg0FloatProperty, new GUIContent("Argument"));
}
else if (argType == typeof(string))
{
SerializedProperty arg0StringProperty = property.FindPropertyRelative("arg0StringValue");
EditorGUI.PropertyField(runningPosition, arg0StringProperty, new GUIContent("Argument"));
}
else
{
EditorGUI.PropertyField(runningPosition, arg0ObjectProperty, new GUIContent("Argument"));
}
}
}
else
{
runningPosition.y += itemHeight + spacing;
LinkableVariableType type = (LinkableVariableType)variableTypeProperty.enumValueIndex;
switch (type)
{
case LinkableVariableType.Object:
SerializedProperty objectValueProperty = property.FindPropertyRelative("objectValue");
EditorGUI.PropertyField(runningPosition, objectValueProperty);
break;
case LinkableVariableType.Bool:
SerializedProperty boolValueProperty = property.FindPropertyRelative("boolValue");
EditorGUI.PropertyField(runningPosition, boolValueProperty);
break;
case LinkableVariableType.Int:
SerializedProperty intValueProperty = property.FindPropertyRelative("intValue");
EditorGUI.PropertyField(runningPosition, intValueProperty);
break;
case LinkableVariableType.Float:
SerializedProperty floatValueProperty = property.FindPropertyRelative("floatValue");
EditorGUI.PropertyField(runningPosition, floatValueProperty);
break;
case LinkableVariableType.String:
SerializedProperty stringValueProperty = property.FindPropertyRelative("stringValue");
EditorGUI.PropertyField(runningPosition, stringValueProperty);
break;
case LinkableVariableType.Vector3:
SerializedProperty vector3ValueProperty = property.FindPropertyRelative("vector3Value");
EditorGUI.PropertyField(runningPosition, vector3ValueProperty);
break;
}
}
/*
object obj = fieldInfo.GetValue(property.serializedObject.targetObject);
LinkableVariable variable = obj as LinkableVariable;
IEnumerable enumerable = obj as IEnumerable;
if (enumerable != null)
{
int index = Convert.ToInt32(new string(property.propertyPath.Where(c => char.IsDigit(c)).ToArray()));
List<LinkableVariable> variablesList = (List<LinkableVariable>)obj;
if (variablesList != null && index >= 0 && variablesList.Count > index) variable = ((List<LinkableVariable>)obj)[index];
}
if (variable != null)
{
MethodInfo initializeMethod = variable.GetType().GetMethod("InitializeLinkDelegate", BindingFlags.NonPublic | BindingFlags.Instance);
if (initializeMethod == null)
{
Debug.LogError("Unable to find InitializeLinkDelegate method on LinkableVariable component");
}
else
{
initializeMethod.Invoke(variable, null);
}
}
*/
}
private List<MethodInfo> GetMethodInfos(MethodInfo[] methodInfos, string returnType)
{
Type[] allowedArgumentTypes = new Type[] { typeof(bool), typeof(string), typeof(int), typeof(float), typeof(Enum), typeof(UnityEngine.Object), typeof(Vector3) };
// Get the methods with the return type specified
System.Type type = System.Type.GetType(returnType);
List<MethodInfo> compatMethodInfos = new List<MethodInfo>();
for (int i = 0; i < methodInfos.Length; ++i)
{
if (methodInfos[i].ReturnType != type) continue;
// Add the method if it has no arguments
if (methodInfos[i].GetParameters().Length == 0)
{
compatMethodInfos.Add(methodInfos[i]);
}
else if (methodInfos[i].GetParameters().Length == 1)
{
// If the argument type is an enum, add the method.
if (methodInfos[i].GetParameters()[0].ParameterType.IsEnum)
{
compatMethodInfos.Add(methodInfos[i]);
}
else
{
// If the argument type is a Unity object, add the method.
if (typeof(UnityEngine.Object).IsAssignableFrom(methodInfos[i].GetParameters()[0].ParameterType))
{
compatMethodInfos.Add(methodInfos[i]);
}
else
{
// If the argument type is one of the allowed types, add the method.
for (int j = 0; j < allowedArgumentTypes.Length; ++j)
{
//Debug.Log(methodInfos[i].GetParameters()[0].ParameterType.BaseType + " " + allowedArgumentTypes[j]);
if (allowedArgumentTypes[j] == methodInfos[i].GetParameters()[0].ParameterType)
{
compatMethodInfos.Add(methodInfos[i]);
break;
}
}
}
}
}
}
return compatMethodInfos;
}
}
}
| 48.064444
| 178
| 0.531971
|
[
"MIT"
] |
RisulKarimWG/GameX
|
Assets/SpaceCombatKit/Scripts/AllVehicles/Radar/LinkableVariables/Editor/LinkableVariableDrawer.cs
| 21,631
|
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 dax-2017-04-19.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.DAX.Model
{
/// <summary>
/// Describes an individual setting that controls some aspect of DAX behavior.
/// </summary>
public partial class Parameter
{
private string _allowedValues;
private ChangeType _changeType;
private string _dataType;
private string _description;
private IsModifiable _isModifiable;
private List<NodeTypeSpecificValue> _nodeTypeSpecificValues = new List<NodeTypeSpecificValue>();
private string _parameterName;
private ParameterType _parameterType;
private string _parameterValue;
private string _source;
/// <summary>
/// Gets and sets the property AllowedValues.
/// <para>
/// A range of values within which the parameter can be set.
/// </para>
/// </summary>
public string AllowedValues
{
get { return this._allowedValues; }
set { this._allowedValues = value; }
}
// Check to see if AllowedValues property is set
internal bool IsSetAllowedValues()
{
return this._allowedValues != null;
}
/// <summary>
/// Gets and sets the property ChangeType.
/// <para>
/// The conditions under which changes to this parameter can be applied. For example,
/// <code>requires-reboot</code> indicates that a new value for this parameter will only
/// take effect if a node is rebooted.
/// </para>
/// </summary>
public ChangeType ChangeType
{
get { return this._changeType; }
set { this._changeType = value; }
}
// Check to see if ChangeType property is set
internal bool IsSetChangeType()
{
return this._changeType != null;
}
/// <summary>
/// Gets and sets the property DataType.
/// <para>
/// The data type of the parameter. For example, <code>integer</code>:
/// </para>
/// </summary>
public string DataType
{
get { return this._dataType; }
set { this._dataType = value; }
}
// Check to see if DataType property is set
internal bool IsSetDataType()
{
return this._dataType != null;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// A description of the parameter
/// </para>
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property IsModifiable.
/// <para>
/// Whether the customer is allowed to modify the parameter.
/// </para>
/// </summary>
public IsModifiable IsModifiable
{
get { return this._isModifiable; }
set { this._isModifiable = value; }
}
// Check to see if IsModifiable property is set
internal bool IsSetIsModifiable()
{
return this._isModifiable != null;
}
/// <summary>
/// Gets and sets the property NodeTypeSpecificValues.
/// <para>
/// A list of node types, and specific parameter values for each node.
/// </para>
/// </summary>
public List<NodeTypeSpecificValue> NodeTypeSpecificValues
{
get { return this._nodeTypeSpecificValues; }
set { this._nodeTypeSpecificValues = value; }
}
// Check to see if NodeTypeSpecificValues property is set
internal bool IsSetNodeTypeSpecificValues()
{
return this._nodeTypeSpecificValues != null && this._nodeTypeSpecificValues.Count > 0;
}
/// <summary>
/// Gets and sets the property ParameterName.
/// <para>
/// The name of the parameter.
/// </para>
/// </summary>
public string ParameterName
{
get { return this._parameterName; }
set { this._parameterName = value; }
}
// Check to see if ParameterName property is set
internal bool IsSetParameterName()
{
return this._parameterName != null;
}
/// <summary>
/// Gets and sets the property ParameterType.
/// <para>
/// Determines whether the parameter can be applied to any nodes, or only nodes of a particular
/// type.
/// </para>
/// </summary>
public ParameterType ParameterType
{
get { return this._parameterType; }
set { this._parameterType = value; }
}
// Check to see if ParameterType property is set
internal bool IsSetParameterType()
{
return this._parameterType != null;
}
/// <summary>
/// Gets and sets the property ParameterValue.
/// <para>
/// The value for the parameter.
/// </para>
/// </summary>
public string ParameterValue
{
get { return this._parameterValue; }
set { this._parameterValue = value; }
}
// Check to see if ParameterValue property is set
internal bool IsSetParameterValue()
{
return this._parameterValue != null;
}
/// <summary>
/// Gets and sets the property Source.
/// <para>
/// How the parameter is defined. For example, <code>system</code> denotes a system-defined
/// parameter.
/// </para>
/// </summary>
public string Source
{
get { return this._source; }
set { this._source = value; }
}
// Check to see if Source property is set
internal bool IsSetSource()
{
return this._source != null;
}
}
}
| 30.606061
| 104
| 0.56662
|
[
"Apache-2.0"
] |
Bio2hazard/aws-sdk-net
|
sdk/src/Services/DAX/Generated/Model/Parameter.cs
| 7,070
|
C#
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Analyzer.Utilities.FlowAnalysis.Analysis.TaintedDataAnalysis;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.NetCore.Analyzers.Security.Helpers;
namespace Microsoft.NetCore.Analyzers.Security
{
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public class ReviewCodeForOpenRedirectVulnerabilities : SourceTriggeredTaintedDataAnalyzerBase
{
internal static readonly DiagnosticDescriptor Rule = SecurityHelpers.CreateDiagnosticDescriptor(
"CA3007",
nameof(MicrosoftNetCoreAnalyzersResources.ReviewCodeForOpenRedirectVulnerabilitiesTitle),
nameof(MicrosoftNetCoreAnalyzersResources.ReviewCodeForOpenRedirectVulnerabilitiesMessage),
RuleLevel.Disabled,
isPortedFxCopRule: false,
isDataflowRule: true,
isReportedAtCompilationEnd: false);
protected override SinkKind SinkKind => SinkKind.Redirect;
protected override DiagnosticDescriptor TaintedDataEnteringSinkDescriptor => Rule;
}
}
| 45.777778
| 160
| 0.777508
|
[
"Apache-2.0"
] |
AndrewZu1337/roslyn-analyzers
|
src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/ReviewCodeForOpenRedirectVulnerabilities.cs
| 1,236
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace VendingMachineNew.Controllers
{
public class PayPalController : Controller
{
// GET: PayPal
public ActionResult Index()
{
return View();
}
}
}
| 19.588235
| 47
| 0.606607
|
[
"MIT"
] |
jaredburks/VendingMachineFinal
|
Controllers/PayPalController.cs
| 335
|
C#
|
// ***********************************************************************
// Assembly : HZH_Controls
// Created : 08-08-2019
//
// ***********************************************************************
// <copyright file="UCBtnExt.Designer.cs">
// Copyright by Huang Zhenghui(黄正辉) All, QQ group:568015492 QQ:623128629 Email:623128629@qq.com
// </copyright>
//
// Blog: https://www.cnblogs.com/bfyx
// GitHub:https://github.com/kwwwvagaa/NetWinformControl
// gitee:https://gitee.com/kwwwvagaa/net_winform_custom_control.git
//
// If you use this code, please keep this note.
// ***********************************************************************
namespace HZH_Controls.Controls
{
/// <summary>
/// Class UCBtnExt.
/// Implements the <see cref="HZH_Controls.Controls.UCControlBase" />
/// </summary>
/// <seealso cref="HZH_Controls.Controls.UCControlBase" />
public partial class UCBtnExt
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region 组件设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.lbl = new System.Windows.Forms.Label();
this.lblTips = new System.Windows.Forms.Label();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.SuspendLayout();
//
// lbl
//
this.lbl.BackColor = System.Drawing.Color.Transparent;
this.lbl.Dock = System.Windows.Forms.DockStyle.Fill;
this.lbl.Font = new System.Drawing.Font("微软雅黑", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.lbl.ForeColor = System.Drawing.Color.White;
this.lbl.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.lbl.Location = new System.Drawing.Point(0, 0);
this.lbl.Name = "lbl";
this.lbl.Size = new System.Drawing.Size(184, 60);
this.lbl.TabIndex = 0;
this.lbl.Text = "自定义按钮";
this.lbl.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.lbl.MouseDown += new System.Windows.Forms.MouseEventHandler(this.lbl_MouseDown);
this.lbl.MouseHover += new System.EventHandler(this.lbl_MouseHover);
//
// lblTips
//
this.lblTips.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.lblTips.BackColor = System.Drawing.Color.Transparent;
this.lblTips.Font = new System.Drawing.Font("Arial Unicode MS", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.lblTips.ForeColor = System.Drawing.Color.White;
this.lblTips.ImageIndex = 0;
this.lblTips.Location = new System.Drawing.Point(158, 0);
this.lblTips.Name = "lblTips";
this.lblTips.Size = new System.Drawing.Size(24, 24);
this.lblTips.TabIndex = 1;
this.lblTips.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.lblTips.Visible = false;
//
// UCBtnExt
//
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
this.BackColor = System.Drawing.Color.Transparent;
this.ConerRadius = 5;
this.Controls.Add(this.lblTips);
this.Controls.Add(this.lbl);
this.Cursor = System.Windows.Forms.Cursors.Hand;
this.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(77)))), ((int)(((byte)(59)))));
this.IsRadius = true;
this.IsShowRect = true;
this.Margin = new System.Windows.Forms.Padding(0);
this.Name = "UCBtnExt";
this.RectColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(77)))), ((int)(((byte)(58)))));
this.Size = new System.Drawing.Size(184, 60);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The label
/// </summary>
public System.Windows.Forms.Label lbl;
/// <summary>
/// The label tips
/// </summary>
private System.Windows.Forms.Label lblTips;
private System.Windows.Forms.ToolTip toolTip1;
}
}
| 43.243697
| 166
| 0.547221
|
[
"Apache-2.0"
] |
JakobWang/NetWinformControl
|
HZH_Controls/HZH_Controls/Controls/Btn/UCBtnExt.Designer.cs
| 5,326
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.