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
sequence | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
// *** 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.Resources
{
public static class GetDeploymentAtScope
{
/// <summary>
/// Deployment information.
/// API Version: 2020-10-01.
/// </summary>
public static Task<GetDeploymentAtScopeResult> InvokeAsync(GetDeploymentAtScopeArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetDeploymentAtScopeResult>("azure-native:resources:getDeploymentAtScope", args ?? new GetDeploymentAtScopeArgs(), options.WithVersion());
}
public sealed class GetDeploymentAtScopeArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The name of the deployment.
/// </summary>
[Input("deploymentName", required: true)]
public string DeploymentName { get; set; } = null!;
/// <summary>
/// The resource scope.
/// </summary>
[Input("scope", required: true)]
public string Scope { get; set; } = null!;
public GetDeploymentAtScopeArgs()
{
}
}
[OutputType]
public sealed class GetDeploymentAtScopeResult
{
/// <summary>
/// The ID of the deployment.
/// </summary>
public readonly string Id;
/// <summary>
/// the location of the deployment.
/// </summary>
public readonly string? Location;
/// <summary>
/// The name of the deployment.
/// </summary>
public readonly string Name;
/// <summary>
/// Deployment properties.
/// </summary>
public readonly Outputs.DeploymentPropertiesExtendedResponse Properties;
/// <summary>
/// Deployment tags
/// </summary>
public readonly ImmutableDictionary<string, string>? Tags;
/// <summary>
/// The type of the deployment.
/// </summary>
public readonly string Type;
[OutputConstructor]
private GetDeploymentAtScopeResult(
string id,
string? location,
string name,
Outputs.DeploymentPropertiesExtendedResponse properties,
ImmutableDictionary<string, string>? tags,
string type)
{
Id = id;
Location = location;
Name = name;
Properties = properties;
Tags = tags;
Type = type;
}
}
}
| 28.904255 | 192 | 0.586308 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Resources/GetDeploymentAtScope.cs | 2,717 | C# |
using System;
using System.Windows.Input;
namespace pdfjoiner.DesktopClient
{
public class RelayCommand : ICommand
{
private readonly Action<object> _Action;
/// <summary>
/// Event that is fired when the <see cref="CanExecute(object)"/> value has changed.
/// </summary>
public event EventHandler CanExecuteChanged = (sender, e) => { };
public RelayCommand(Action<object> action)
{
_Action = action;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
_Action(parameter);
}
}
}
| 22.354839 | 92 | 0.568543 | [
"MIT"
] | harrystb/pdfjoiner | pdfjoiner.DesktopClient/ViewModelHelpers/RelayCommand.cs | 695 | C# |
using System;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Renci.SshNet.Channels;
using Renci.SshNet.Common;
using Renci.SshNet.Sftp;
using Renci.SshNet.Abstractions;
using Renci.SshNet.Sftp.Responses;
namespace Renci.SshNet.Tests.Classes.Sftp
{
[TestClass]
public class SftpSessionTest_Connected_RequestRead
{
#region SftpSession.Connect()
private Mock<ISession> _sessionMock;
private Mock<IChannelSession> _channelSessionMock;
private ISftpResponseFactory _sftpResponseFactory;
private SftpSession _sftpSession;
private int _operationTimeout;
private Encoding _encoding;
private uint _protocolVersion;
private byte[] _sftpInitRequestBytes;
private SftpVersionResponse _sftpVersionResponse;
private byte[] _sftpRealPathRequestBytes;
private SftpNameResponse _sftpNameResponse;
#endregion SftpSession.Connect()
private byte[] _sftpReadRequestBytes;
private byte[] _sftpDataResponseBytes;
private byte[] _handle;
private uint _offset;
private uint _length;
private byte[] _data;
private byte[] _actual;
[TestInitialize]
public void Setup()
{
Arrange();
Act();
}
private void SetupData()
{
var random = new Random();
#region SftpSession.Connect()
_operationTimeout = random.Next(100, 500);
_protocolVersion = (uint) random.Next(0, 3);
_encoding = Encoding.UTF8;
_sftpResponseFactory = new SftpResponseFactory();
_sftpInitRequestBytes = new SftpInitRequestBuilder().WithVersion(SftpSession.MaximumSupportedVersion)
.Build()
.GetBytes();
_sftpVersionResponse = new SftpVersionResponseBuilder().WithVersion(_protocolVersion)
.Build();
_sftpRealPathRequestBytes = new SftpRealPathRequestBuilder().WithProtocolVersion(_protocolVersion)
.WithRequestId(1)
.WithPath(".")
.WithEncoding(_encoding)
.Build()
.GetBytes();
_sftpNameResponse = new SftpNameResponseBuilder().WithProtocolVersion(_protocolVersion)
.WithResponseId(1)
.WithEncoding(_encoding)
.WithFile("XYZ", SftpFileAttributes.Empty)
.Build();
#endregion SftpSession.Connect()
_handle = CryptoAbstraction.GenerateRandom(random.Next(1, 10));
_offset = (uint) random.Next(1, 5);
_length = (uint) random.Next(30, 50);
_data = CryptoAbstraction.GenerateRandom((int) _length);
_sftpReadRequestBytes = new SftpReadRequestBuilder().WithProtocolVersion(_protocolVersion)
.WithRequestId(2)
.WithHandle(_handle)
.WithOffset(_offset)
.WithLength(_length)
.Build()
.GetBytes();
_sftpDataResponseBytes = new SftpDataResponseBuilder().WithProtocolVersion(_protocolVersion)
.WithResponseId(2)
.WithData(_data)
.Build()
.GetBytes();
}
private void CreateMocks()
{
_sessionMock = new Mock<ISession>(MockBehavior.Strict);
_channelSessionMock = new Mock<IChannelSession>(MockBehavior.Strict);
}
private void SetupMocks()
{
var sequence = new MockSequence();
#region SftpSession.Connect()
_sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object);
_channelSessionMock.InSequence(sequence).Setup(p => p.Open());
_channelSessionMock.InSequence(sequence).Setup(p => p.SendSubsystemRequest("sftp")).Returns(true);
_channelSessionMock.InSequence(sequence).Setup(p => p.IsOpen).Returns(true);
_channelSessionMock.InSequence(sequence).Setup(p => p.SendData(_sftpInitRequestBytes))
.Callback(() =>
{
_channelSessionMock.Raise(c => c.DataReceived += null,
new ChannelDataEventArgs(0, _sftpVersionResponse.GetBytes()));
});
_channelSessionMock.InSequence(sequence).Setup(p => p.IsOpen).Returns(true);
_channelSessionMock.InSequence(sequence).Setup(p => p.SendData(_sftpRealPathRequestBytes))
.Callback(() =>
{
_channelSessionMock.Raise(c => c.DataReceived += null,
new ChannelDataEventArgs(0, _sftpNameResponse.GetBytes()));
});
#endregion SftpSession.Connect()
_channelSessionMock.InSequence(sequence).Setup(p => p.IsOpen).Returns(true);
_channelSessionMock.InSequence(sequence).Setup(p => p.SendData(_sftpReadRequestBytes))
.Callback(() =>
{
_channelSessionMock.Raise(
c => c.DataReceived += null,
new ChannelDataEventArgs(0, _sftpDataResponseBytes.Take(0, 20)));
_channelSessionMock.Raise(
c => c.DataReceived += null,
new ChannelDataEventArgs(0, _sftpDataResponseBytes.Take(20, _sftpDataResponseBytes.Length - 20)));
}
);
}
private void Arrange()
{
SetupData();
CreateMocks();
SetupMocks();
_sftpSession = new SftpSession(_sessionMock.Object, _operationTimeout, _encoding, _sftpResponseFactory);
_sftpSession.Connect();
}
protected void Act()
{
_actual = _sftpSession.RequestRead(_handle, _offset, _length);
}
[TestMethod]
public void ReturnedValueShouldBeDataOfSftpDataResponse()
{
Assert.IsNotNull(_actual);
Assert.IsTrue(_data.SequenceEqual(_actual));
}
}
} | 47.674847 | 144 | 0.474456 | [
"MIT"
] | 0xced/SSH.NET | src/Renci.SshNet.Tests/Classes/Sftp/SftpSessionTest_Connected_RequestRead.cs | 7,773 | C# |
using BcGov.Fams3.Redis;
using BcGov.Fams3.Redis.Model;
using BcGov.Fams3.SearchApi.Contracts.Person;
using BcGov.Fams3.SearchApi.Contracts.PersonSearch;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using SearchApi.Web.Configuration;
using SearchApi.Web.Controllers;
using SearchApi.Web.DeepSearch.Schema;
using SearchApi.Web.Messaging;
using SearchApi.Web.Notifications;
using SearchApi.Web.Search;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace SearchApi.Web.DeepSearch
{
public interface IDeepSearchService
{
Task UpdateDataPartner(string searchRequestKey, string dataPartner, string eventName);
Task UpdateParameters(string eventName, PersonSearchCompleted eventStatus, string searchRequestKey);
Task DeleteFromCache(string searchRequestKey);
Task<bool> IsWaveSearchReadyToFinalize(string searchRequestKey);
}
public class DeepSearchService : IDeepSearchService
{
private readonly ICacheService _cacheService;
private readonly ILogger<DeepSearchService> _logger;
private readonly IDeepSearchDispatcher _deepSearchDispatcher;
private readonly DeepSearchOptions _deepSearchOptions;
public DeepSearchService(ICacheService cacheService, ILogger<DeepSearchService> logger, IOptions<DeepSearchOptions> deepSearchOptions, IDeepSearchDispatcher deepSearchDispatcher)
{
_cacheService = cacheService;
_logger = logger;
_deepSearchOptions = deepSearchOptions.Value;
_deepSearchDispatcher = deepSearchDispatcher;
}
private async Task<bool> CurrentWaveIsCompleted(string searchRequestKey)
{
try
{
SearchRequest sr = await _cacheService.GetRequest(searchRequestKey);
if (sr != null)
return sr.AllFastSearchPartnerCompleted();
else
return true;
}
catch (Exception exception)
{
_logger.LogError($"Check Data Partner Status Failed. [] for {searchRequestKey}. [{exception.Message}]");
return false;
}
}
private async Task<bool> AllSearchDataPartnerIsCompleted(string searchRequestKey)
{
try
{
var request = await _cacheService.GetRequest(searchRequestKey);
if(request != null)
return request.AllPartnerCompleted();
return true;
}
catch (Exception exception)
{
_logger.LogError($"Check Data Partner Status Failed. [] for {searchRequestKey}. [{exception.Message}]");
return false;
}
}
public async Task UpdateDataPartner(string searchRequestKey, string dataPartner, string eventName)
{
try
{
if (eventName.Equals(EventName.Completed) || eventName.Equals(EventName.Rejected))
{
_logger.LogInformation($"Updating data partner as completed for {dataPartner} for {eventName} event");
int tryCount = await _cacheService.UpdateDataPartnerCompleteStatus(searchRequestKey, dataPartner);
_logger.LogInformation("Successfully update data partner status with {tries}",tryCount);
}
}
catch (Exception exception)
{
_logger.LogError($"Update Data Partner Status Failed. [{eventName}] for {searchRequestKey}. [{exception.Message}]");
}
}
public async Task DeleteFromCache(string searchRequestKey)
{
try
{
var searchRequest = await _cacheService.GetRequest(searchRequestKey);
if (searchRequest != null && searchRequest.AllPartnerCompleted())
await _cacheService.DeleteRequest(searchRequestKey);
IEnumerable<string> keys = await SearchDeepSearchKeys(searchRequestKey);
foreach (var key in keys)
await _cacheService.Delete(key);
}
catch (Exception exception)
{
_logger.LogError($"Delete search request failed. for {searchRequestKey}. [{exception.Message}]");
}
}
public async Task UpdateParameters(string eventName, PersonSearchCompleted eventStatus, string searchRequestKey)
{
IEnumerable<WaveSearchData> waveSearches = await GetWaveDataForSearch(searchRequestKey);
if (eventName.Equals(EventName.Completed))
{
List<PersonalIdentifier> existingIds = new List<PersonalIdentifier>();
foreach (var waveitem in waveSearches)
{
_logger.LogInformation($"Store all existing params {waveitem.DataPartner}");
foreach (var person in waveitem.AllParameter)
{
foreach (var identifier in person.Identifiers)
{
if (!existingIds.Any(i => i.Type == identifier.Type && i.Value == identifier.Value))
existingIds.Add(identifier);
}
}
}
var matchedPersons = eventStatus.MatchedPersons;
List<PersonalIdentifier> foundId = new List<PersonalIdentifier>();
_logger.LogInformation($"Store all newly found params from {eventStatus.ProviderProfile.Name}");
foreach (var person in matchedPersons)
{
foreach (var identifier in person.Identifiers)
{
if (!foundId.Any(i => i.Type == identifier.Type && i.Value == identifier.Value))
foundId.Add(identifier);
}
}
foreach (var waveitem in waveSearches)
{
PersonalIdentifierType[] paramsRegistry = ListDataPartnerRegistry(waveitem.DataPartner);
ExtractIds(eventStatus, existingIds, waveitem.DataPartner, foundId, paramsRegistry, waveSearches, out IEnumerable<PersonalIdentifier> filteredExistingIdentifierForDataPartner, out IEnumerable<PersonalIdentifier> filteredNewFoundIdentifierForDataPartner);
var newToBeUsedId = filteredExistingIdentifierForDataPartner.DetailedCompare(filteredNewFoundIdentifierForDataPartner);
_logger.LogInformation($"{newToBeUsedId.Count()} ids to be stored as new parameter for {waveitem.DataPartner}");
_logger.LogDebug($"new to be used ID are: {JsonConvert.SerializeObject(newToBeUsedId)}");
if (newToBeUsedId.Count() > 0)
{
waveitem.AllParameter.Add(new Person { Identifiers = newToBeUsedId });
if (waveitem.NewParameter == null || waveitem.NewParameter?.Count == 0)
waveitem.NewParameter = new List<Person> { new Person { Identifiers = newToBeUsedId } };
else
{
waveitem.NewParameter[0].Identifiers = AddUniqueIds(waveitem.NewParameter[0].Identifiers, newToBeUsedId);
}
}
await _cacheService.Save(searchRequestKey.DeepSearchKey(waveitem.DataPartner), waveitem);
}
}
}
private PersonalIdentifierType[] ListDataPartnerRegistry(string dataPartner)
{
PersonalIdentifierType[] paramsRegistry = new PersonalIdentifierType[] { };
try
{
paramsRegistry = Registry.DataPartnerParameters[dataPartner];
}
catch (Exception ex)
{
_logger.LogError($"{dataPartner} registry not found. Error: {ex.Message}");
}
return paramsRegistry;
}
private void ExtractIds(PersonSearchCompleted eventStatus, List<PersonalIdentifier> existingIds,string DataPartner, List<PersonalIdentifier> foundId, PersonalIdentifierType[] paramsRegistry, IEnumerable<WaveSearchData> waveSearches, out IEnumerable<PersonalIdentifier> filteredExistingIdentifierForDataPartner, out IEnumerable<PersonalIdentifier> filteredNewFoundIdentifierForDataPartner)
{
_logger.LogInformation($"{existingIds.Count()} Identifier exists");
filteredExistingIdentifierForDataPartner = existingIds.Where(identifer => paramsRegistry.Contains(identifer.Type));
_logger.LogInformation($"{existingIds.Count()} Identifier matched the require types for {DataPartner}");
_logger.LogInformation($"{foundId.Count()} Identifier was returned by {eventStatus.ProviderProfile.Name}");
filteredNewFoundIdentifierForDataPartner = foundId.Where(identifer => paramsRegistry.Contains(identifer.Type));
_logger.LogInformation($"{filteredNewFoundIdentifierForDataPartner.Count()} returned Identifier matched the required types for {DataPartner}");
}
private IEnumerable<PersonalIdentifier> AddUniqueIds(IEnumerable<PersonalIdentifier> sourceIds, IEnumerable<PersonalIdentifier> newIds)
{
foreach(PersonalIdentifier pi in newIds)
{
if( !sourceIds.Any(m=>m.Value==pi.Value && m.Type==pi.Type) )
{
sourceIds.ToList().Add(pi);
}
}
return sourceIds;
}
private async Task<IEnumerable<WaveSearchData>> GetWaveDataForSearch(string searchRequestKey)
{
List<WaveSearchData> waveMetaDatas = new List<WaveSearchData>();
IEnumerable<string> keys = await SearchDeepSearchKeys(searchRequestKey);
foreach (var key in keys)
{
waveMetaDatas.Add(JsonConvert.DeserializeObject<WaveSearchData>(await _cacheService.Get(key)));
}
return waveMetaDatas.AsEnumerable();
}
private async Task<IEnumerable<string>> SearchDeepSearchKeys(string searchRequestKey)
{
return await _cacheService.SearchKeys($"deepsearch-{searchRequestKey}*");
}
public async Task<bool> IsWaveSearchReadyToFinalize(string searchRequestKey)
{
var waveData = await GetWaveDataForSearch(searchRequestKey);
if (waveData.Any())
{
if (!await CurrentWaveIsCompleted(searchRequestKey))
return false;
if (waveData.Any(x => x.CurrentWave == _deepSearchOptions.MaxWaveCount) || NoNewParameter(waveData))
{
_logger.Log(LogLevel.Information, $"{searchRequestKey} no new wave to initiate");
return true;
}
else
{
foreach (var wave in waveData)
{
if (wave.NewParameter != null)
{
//new parameter only contain 1 person.
foreach (var person in wave.NewParameter)
{
await _deepSearchDispatcher.StartAnotherWave(searchRequestKey, wave, person, wave.NumberOfRetries, wave.TimeBetweenRetries);
}
}
else
{
string cacheKey = searchRequestKey.DeepSearchKey(wave.DataPartner);
var waveMetaData = await _cacheService.Get(cacheKey);
if (waveMetaData != null)
{
_logger.Log(LogLevel.Information, $"{searchRequestKey} has an active wave but no new parameter");
WaveSearchData metaData = JsonConvert.DeserializeObject<WaveSearchData>(waveMetaData);
_logger.Log(LogLevel.Information, $"{searchRequestKey} Current Metadata Wave : {metaData.CurrentWave}");
metaData.CurrentWave++;
metaData.NewParameter = null;
await _cacheService.Save(cacheKey, metaData);
_logger.Log(LogLevel.Information, $"{searchRequestKey} New wave {metaData.CurrentWave} saved");
}
}
}
return false;
}
}
else
{
return await AllSearchDataPartnerIsCompleted(searchRequestKey);
}
}
private static bool NoNewParameter(IEnumerable<WaveSearchData> waveData)
{
return waveData.Count(w => w.NewParameter == null) == waveData.Count();
}
}
}
| 42.612179 | 397 | 0.586085 | [
"Apache-2.0"
] | KyleKayfish/fams3 | app/SearchApi/SearchApi.Web/DeepSearch/IDeepSearchService.cs | 13,295 | 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("More.NLog")]
[assembly: AssemblyDescription("More.NLog")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("AK107")]
[assembly: AssemblyProduct("More.NLog")]
[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("52f8dc0e-5fb3-4584-a555-79e8101f755d")]
// 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.9")]
[assembly: AssemblyFileVersion("1.0.0.9")]
| 37.972973 | 84 | 0.744484 | [
"MIT"
] | AK107/More.NLog | More.NLog/Properties/AssemblyInfo.cs | 1,408 | C# |
using Castle.Core.Logging;
using GroupService.AzureFunction;
using GroupService.Handlers;
using HelpMyStreet.Contracts.GroupService.Request;
using HelpMyStreet.Contracts.GroupService.Response;
using HelpMyStreet.Contracts.RequestService.Response;
using HelpMyStreet.Contracts.Shared;
using HelpMyStreet.Utils.Utils;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace GroupService.UnitTests.AzureFunctions
{
public class GetGroupByKeyTests
{
private Mock<IMediator> _mediator;
private Mock<ILoggerWrapper<GetGroupByKeyRequest>> _logger;
private GetGroupByKey _classUnderTest;
private GetGroupByKeyResponse _response;
[SetUp]
public void Setup()
{
_logger = new Mock<ILoggerWrapper<GetGroupByKeyRequest>>();
_mediator = new Mock<IMediator>();
_mediator.Setup(x => x.Send(It.IsAny<GetGroupByKeyRequest>(), It.IsAny<CancellationToken>())).ReturnsAsync(()=> _response);
_classUnderTest = new GetGroupByKey(_mediator.Object,_logger.Object);
}
[Test]
public async Task HappyPath_ReturnsGroup()
{
int groupId = 1;
_response = new GetGroupByKeyResponse()
{
GroupId = groupId
};
IActionResult result = await _classUnderTest.Run(new GetGroupByKeyRequest()
{
GroupKey = "GroupKey"
},CancellationToken.None);
OkObjectResult objectResult = result as OkObjectResult;
Assert.IsNotNull(objectResult);
Assert.AreEqual(200, objectResult.StatusCode);
ResponseWrapper<GetGroupByKeyResponse, GroupServiceErrorCode> deserialisedResponse = objectResult.Value as ResponseWrapper<GetGroupByKeyResponse, GroupServiceErrorCode>;
Assert.IsNotNull(deserialisedResponse);
Assert.IsTrue(deserialisedResponse.HasContent);
Assert.IsTrue(deserialisedResponse.IsSuccessful);
Assert.AreEqual(0, deserialisedResponse.Errors.Count());
Assert.AreEqual(groupId, deserialisedResponse.Content.GroupId);
_mediator.Verify(x => x.Send(It.IsAny<GetGroupByKeyRequest>(), It.IsAny<CancellationToken>()),Times.Once);
}
[Test]
public async Task MissingGroupKey_ThrowsValidationError()
{
GetGroupByKeyRequest req = new GetGroupByKeyRequest();
IActionResult result = await _classUnderTest.Run(req, CancellationToken.None);
ObjectResult objectResult = result as ObjectResult;
Assert.IsNotNull(objectResult);
Assert.AreEqual(422, objectResult.StatusCode);
ResponseWrapper<GetGroupByKeyResponse, GroupServiceErrorCode> deserialisedResponse = objectResult.Value as ResponseWrapper<GetGroupByKeyResponse, GroupServiceErrorCode>;
Assert.IsNotNull(deserialisedResponse);
Assert.IsFalse(deserialisedResponse.HasContent);
Assert.IsFalse(deserialisedResponse.IsSuccessful);
Assert.AreEqual(1, deserialisedResponse.Errors.Count());
Assert.AreEqual(GroupServiceErrorCode.ValidationError, deserialisedResponse.Errors[0].ErrorCode);
_mediator.Verify(x => x.Send(It.IsAny<GetGroupByKeyRequest>(), It.IsAny<CancellationToken>()), Times.Never);
}
}
}
| 38.758242 | 181 | 0.694641 | [
"MIT"
] | factor-50-devops-bot/group-service | GroupService/GroupService.UnitTests/AzureFunctions/GetGroupByKeyTests.cs | 3,529 | C# |
#region Disclaimer/Info
///////////////////////////////////////////////////////////////////////////////////////////////////
// Subtext WebLog
//
// Subtext is an open source weblog system that is a fork of the .TEXT
// weblog system.
//
// For updated news and information please visit http://subtextproject.com/
// Subtext is hosted at Google Code at http://code.google.com/p/subtext/
// The development mailing list is at [email protected]
//
// This project is licensed under the BSD license. See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Globalization;
using Subtext.Framework.Data;
using Subtext.Framework.Util;
namespace Subtext.Web.UI.Controls
{
/// <summary>
/// Summary description for ArchiveDay.
/// </summary>
public class ArchiveDay : BaseControl
{
protected Day SingleDay;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (Context != null)
{
try
{
DateTime dayDate = SubtextContext.RequestContext.GetDateFromRequest();
SingleDay.CurrentDay = Cacher.GetEntriesForDay(dayDate, SubtextContext);
Globals.SetTitle(
string.Format(CultureInfo.InvariantCulture, "{0} - {1} Entries", Blog.Title,
dayDate.ToString("D", CultureInfo.CurrentCulture)), Context);
}
catch (FormatException)
{
//Somebody probably is messing with the url.
//404 is set in filenotfound - DF
Response.Redirect("~/SystemMessages/FileNotFound.aspx");
}
}
}
}
} | 34.981481 | 100 | 0.525675 | [
"MIT"
] | Haacked/Subtext | src/Subtext.Web/UI/Controls/ArchiveDay.cs | 1,889 | 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 lambda-2015-03-31.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.Lambda.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Lambda.Model.Internal.MarshallTransformations
{
/// <summary>
/// UpdateEventSourceMapping Request Marshaller
/// </summary>
public class UpdateEventSourceMappingRequestMarshaller : IMarshaller<IRequest, UpdateEventSourceMappingRequest> , 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((UpdateEventSourceMappingRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(UpdateEventSourceMappingRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.Lambda");
request.Headers["Content-Type"] = "application/json";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-03-31";
request.HttpMethod = "PUT";
if (!publicRequest.IsSetUUID())
throw new AmazonLambdaException("Request object does not have required field UUID set");
request.AddPathResource("{UUID}", StringUtils.FromString(publicRequest.UUID));
request.ResourcePath = "/2015-03-31/event-source-mappings/{UUID}";
request.MarshallerVersion = 2;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetBatchSize())
{
context.Writer.WritePropertyName("BatchSize");
context.Writer.Write(publicRequest.BatchSize);
}
if(publicRequest.IsSetEnabled())
{
context.Writer.WritePropertyName("Enabled");
context.Writer.Write(publicRequest.Enabled);
}
if(publicRequest.IsSetFunctionName())
{
context.Writer.WritePropertyName("FunctionName");
context.Writer.Write(publicRequest.FunctionName);
}
if(publicRequest.IsSetMaximumBatchingWindowInSeconds())
{
context.Writer.WritePropertyName("MaximumBatchingWindowInSeconds");
context.Writer.Write(publicRequest.MaximumBatchingWindowInSeconds);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static UpdateEventSourceMappingRequestMarshaller _instance = new UpdateEventSourceMappingRequestMarshaller();
internal static UpdateEventSourceMappingRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static UpdateEventSourceMappingRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.475806 | 163 | 0.624059 | [
"Apache-2.0"
] | TallyUpTeam/aws-sdk-net | sdk/src/Services/Lambda/Generated/Model/Internal/MarshallTransformations/UpdateEventSourceMappingRequestMarshaller.cs | 4,647 | C# |
using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using CslaGenerator.Metadata;
using CslaGenerator.Util;
namespace CslaGenerator.Design
{
public class UnitOfWorkTypeEditor : UITypeEditor
{
private IWindowsFormsEditorService _editorService;
private readonly ListBox _lstProperties;
public UnitOfWorkTypeEditor()
{
_lstProperties = new ListBox();
_lstProperties.DoubleClick += LstPropertiesDoubleClick;
_lstProperties.SelectionMode = SelectionMode.One;
}
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
_editorService = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
if (_editorService != null)
{
if (context.Instance != null)
{
// CR modifying to accomodate PropertyBag
Type instanceType = null;
object objinfo = null;
TypeHelper.GetUnitOfWorkPropertyContextInstanceObject(context, ref objinfo, ref instanceType);
var prop = (UnitOfWorkProperty)objinfo;
_lstProperties.Items.Clear();
_lstProperties.Items.Add("(None)");
foreach (var o in GeneratorController.Current.CurrentUnit.CslaObjects)
{
// waiting to find a way to distinguish collection and non collection child properties
//if(!TypeHelper.IsCollectionType(o.ObjectType))
if (o.ObjectType == CslaObjectType.NameValueList)
_lstProperties.Items.Add(o.ObjectName);
if (o.ObjectType == CslaObjectType.EditableRoot)
_lstProperties.Items.Add(o.ObjectName);
if (o.ObjectType == CslaObjectType.ReadOnlyObject && o.ParentType == string.Empty)
_lstProperties.Items.Add(o.ObjectName);
if (o.ObjectType == CslaObjectType.EditableRootCollection)
_lstProperties.Items.Add(o.ObjectName);
if (o.ObjectType == CslaObjectType.DynamicEditableRootCollection)
_lstProperties.Items.Add(o.ObjectName);
if (o.ObjectType == CslaObjectType.ReadOnlyCollection && o.ParentType==string.Empty)
_lstProperties.Items.Add(o.ObjectName);
}
_lstProperties.Sorted = true;
// waiting to find a way to fetch the CslaObjectInfo
var currentCslaObject = (CslaObjectInfo)GeneratorController.Current.MainForm.ProjectPanel.ListObjects.SelectedItem;
/*var obj = GeneratorController.Current.CurrentUnit.CslaObjects.Find("");
foreach (CslaObjectInfo o in GeneratorController.Current.CurrentUnit.CslaObjects)
{
//if (o.ObjectName != obj.ObjectName)
// lstProperties.Items.Add(o.ObjectName);
if (o.ObjectName != obj.ObjectName)
{
if (RelationRulesEngine.IsParentAllowed(o.ObjectType, obj.ObjectType))
lstProperties.Items.Add(o.ObjectName);
}
}
if (lstProperties.Items.Contains(obj.ParentType))
lstProperties.SelectedItem = obj.ParentType;
else
lstProperties.SelectedItem = "(None)";*/
_lstProperties.SelectedItem = prop.TypeName;
_editorService.DropDownControl(_lstProperties);
if (_lstProperties.SelectedIndex < 0 || _lstProperties.SelectedItem.ToString() == "(None)")
return string.Empty;
return _lstProperties.SelectedItem.ToString();
}
}
return value;
}
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.DropDown;
}
void LstPropertiesDoubleClick(object sender, EventArgs e)
{
_editorService.CloseDropDown();
}
}
} | 48.103093 | 136 | 0.555294 | [
"MIT"
] | CslaGenFork/CslaGenFork | branches/V4-3-RC/Solutions/CslaGenFork/Design/UnitOfWorkTypeEditor.cs | 4,668 | C# |
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using Abp.Authorization;
using JenkinsTryOut.Authorization.Roles;
using JenkinsTryOut.Authorization.Users;
using JenkinsTryOut.MultiTenancy;
using Microsoft.Extensions.Logging;
using Abp.Domain.Uow;
namespace JenkinsTryOut.Identity
{
public class SecurityStampValidator : AbpSecurityStampValidator<Tenant, Role, User>
{
public SecurityStampValidator(
IOptions<SecurityStampValidatorOptions> options,
SignInManager signInManager,
ISystemClock systemClock,
ILoggerFactory loggerFactory,
IUnitOfWorkManager unitOfWorkManager)
: base(options, signInManager, systemClock, loggerFactory, unitOfWorkManager)
{
}
}
}
| 32.115385 | 89 | 0.74491 | [
"MIT"
] | kgamab/jenkins-demo | aspnet-core/src/JenkinsTryOut.Core/Identity/SecurityStampValidator.cs | 837 | C# |
using EventKit;
using Foundation;
using System;
using UIKit;
namespace Calendars
{
public partial class EventsController : UITableViewController
{
private EKEvent[] events;
public EventsController(IntPtr handle) : base(handle) { }
public override void ViewDidLoad()
{
base.ViewDidLoad();
// create our NSPredicate which we'll use for the query
var startDate = (NSDate)DateTime.Now.AddDays(-7);
var endDate = (NSDate)DateTime.Now;
// the third parameter is calendars we want to look in, to use all calendars, we pass null
using (var query = MainViewController.EventStore.PredicateForEvents(startDate, endDate, null))
{
// execute the query
this.events = MainViewController.EventStore.EventsMatching(query);
}
this.TableView.ReloadData();
}
public override nint RowsInSection(UITableView tableView, nint section)
{
return this.events.Length;
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
var cell = tableView.DequeueReusableCell("eventCellIdentifier") ?? new UITableViewCell();
cell.TextLabel.Text = this.events[indexPath.Row].Title;
return cell;
}
}
} | 32.302326 | 106 | 0.62347 | [
"MIT"
] | Art-Lav/ios-samples | Calendars/Calendars/EventsController.cs | 1,389 | C# |
using System.Collections.Generic;
namespace Nez.AI.GOAP
{
/// <summary>
/// Agent provides a simple and concise way to use the planner. It is not necessary to use at all since it is just a convenince wrapper
/// around the ActionPlanner making it easier to get plans and store the results.
/// </summary>
public abstract class Agent
{
public Stack<Action> Actions;
protected ActionPlanner _planner;
public Agent()
{
_planner = new ActionPlanner();
}
public bool Plan(bool debugPlan = false)
{
List<AStarNode> nodes = null;
if (debugPlan)
nodes = new List<AStarNode>();
Actions = _planner.Plan(GetWorldState(), GetGoalState(), nodes);
if (nodes != null && nodes.Count > 0)
{
Debug.Log("---- ActionPlanner plan ----");
Debug.Log("plan cost = {0}\n", nodes[nodes.Count - 1].CostSoFar);
Debug.Log("{0}\t{1}", "start".PadRight(15), GetWorldState().Describe(_planner));
for (var i = 0; i < nodes.Count; i++)
{
Debug.Log("{0}: {1}\t{2}", i, nodes[i].Action.GetType().Name.PadRight(15),
nodes[i].WorldState.Describe(_planner));
Pool<AStarNode>.Free(nodes[i]);
}
}
return HasActionPlan();
}
public bool HasActionPlan()
{
return Actions != null && Actions.Count > 0;
}
/// <summary>
/// current WorldState
/// </summary>
/// <returns>The world state.</returns>
abstract public WorldState GetWorldState();
/// <summary>
/// the goal state that the agent wants to achieve
/// </summary>
/// <returns>The goal state.</returns>
abstract public WorldState GetGoalState();
}
} | 24.181818 | 136 | 0.642231 | [
"MIT"
] | AdrianN17/ZombieSurvivalMonogame | Nez-master/Nez.Portable/AI/GOAP/Agent.cs | 1,598 | C# |
namespace Cavity.Tests
{
using System;
using Cavity.Types;
using Xunit;
public sealed class PropertyTestBaseFacts
{
[Fact]
public void ctor_PropertyInfo_object()
{
Assert.NotNull(new DerivedPropertyTest(typeof(PropertiedClass1).GetProperty("AutoBoolean")));
}
[Fact]
public void op_Check()
{
Assert.Throws<NotImplementedException>(() => new DerivedPropertyTest(typeof(PropertiedClass1).GetProperty("AutoBoolean")).Check());
}
[Fact]
public void prop_Property()
{
var expected = typeof(PropertiedClass1).GetProperty("AutoBoolean");
var obj = new DerivedPropertyTest(null)
{
Property = expected
};
var actual = obj.Property;
Assert.Same(expected, actual);
}
}
} | 26.111111 | 143 | 0.546809 | [
"MIT"
] | cavity-project/unit-testing | src/Class Libraries/Testing.Unit.Facts/Tests/PropertyTestBase.Facts.cs | 942 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Azure.EventHub.Inputs
{
public sealed class EventSubscriptionAdvancedFilterBoolEqualGetArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Specifies the field within the event data that you want to use for filtering. Type of the field can be a number, boolean, or string.
/// </summary>
[Input("key", required: true)]
public Input<string> Key { get; set; } = null!;
/// <summary>
/// Specifies a single value to compare to when using a single value operator.
/// </summary>
[Input("value", required: true)]
public Input<bool> Value { get; set; } = null!;
public EventSubscriptionAdvancedFilterBoolEqualGetArgs()
{
}
}
}
| 33.34375 | 144 | 0.656982 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi-bot/pulumi-azure | sdk/dotnet/EventHub/Inputs/EventSubscriptionAdvancedFilterBoolEqualGetArgs.cs | 1,067 | C# |
using System;
using BristolNightlife.Core.Models;
namespace BristolNightlife.Core.Services
{
public class ApiModelCacheService : IApiModelCacheService
{
public bool ContainsDate(DateTime date)
{
return ApiCache.Cache.ContainsKey(date);
}
public ApiModel.Rootobject GetDateModel(DateTime date)
{
return ApiCache.Cache.ContainsKey(date)
? ApiCache.Cache[date]
: null;
}
public void AddDateModel(DateTime date, ApiModel.Rootobject model)
{
if (model == null)
return;
if(ApiCache.Cache.ContainsKey(date) == false)
ApiCache.Cache.Add(date, model);
}
}
public interface IApiModelCacheService
{
bool ContainsDate(DateTime date);
ApiModel.Rootobject GetDateModel(DateTime date);
void AddDateModel(DateTime date, ApiModel.Rootobject model);
}
} | 23.166667 | 69 | 0.711031 | [
"Apache-2.0"
] | CBurbidge/BristolNightlife | BristolNightlife.Core/Services/ApiModelCacheService.cs | 834 | C# |
using System;
using System.Linq;
using Repository.Models;
namespace Repository
{
public class RepoLogic
{
private readonly Cinephiliacs_DbContext _dbContext;
public RepoLogic(Cinephiliacs_DbContext dbContext)
{
_dbContext = dbContext;
}
public bool AddUser(GlobalModels.User user)
{
User repoUser = new User();
repoUser.Username = user.Username;
repoUser.FirstName = user.Firstname;
repoUser.LastName = user.Lastname;
repoUser.Email = user.Email;
repoUser.Permissions = user.Permissions;
_dbContext.Users.Add(repoUser);
if(_dbContext.SaveChanges() > 0)
{
return true;
}
return false;
}
public GlobalModels.User GetUser(string username)
{
User repoUser = _dbContext.Users.Where(a => a.Username == username).FirstOrDefault<User>();
return new GlobalModels.User(repoUser.Username, repoUser.FirstName, repoUser.LastName, repoUser.Email, repoUser.Permissions);
}
}
}
| 27.926829 | 137 | 0.59738 | [
"MIT"
] | Kugelsicher/webapidemo | Repository/RepoLogic.cs | 1,147 | C# |
using System;
namespace HtmlConsole.Css
{
public class AutoStyleValue : StyleValue
{
public override Type GetStyleValueType() => GetType();
}
} | 18.333333 | 62 | 0.672727 | [
"MIT"
] | mzabsky/HtmlConsole | HtmlConsole/Css/AutoStyleValue.cs | 167 | C# |
using Com.Danliris.Service.Packing.Inventory.Application.Utilities;
using Com.Danliris.Service.Packing.Inventory.Infrastructure.IdentityProvider;
using Com.Danliris.Service.Packing.Inventory.Infrastructure.Repositories.GarmentShipping.CreditAdvice;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Dynamic.Core;
namespace Com.Danliris.Service.Packing.Inventory.Application.ToBeRefactored.GarmentShipping.Monitoring.GarmentCreditAdvice
{
public class GarmentCreditAdviceMonitoringService : IGarmentCreditAdviceMonitoringService
{
private readonly IGarmentShippingCreditAdviceRepository carepository;
private readonly IIdentityProvider _identityProvider;
public GarmentCreditAdviceMonitoringService(IServiceProvider serviceProvider)
{
carepository = serviceProvider.GetService<IGarmentShippingCreditAdviceRepository>();
_identityProvider = serviceProvider.GetService<IIdentityProvider>();
}
public IQueryable<GarmentCreditAdviceMonitoringViewModel> GetData(string buyerAgent, string invoiceNo, string paymentTerm, DateTime? dateFrom, DateTime? dateTo, int offset)
{
var queryCA = carepository.ReadAll();
if (!string.IsNullOrWhiteSpace(buyerAgent))
{
queryCA = queryCA.Where(w => w.BuyerName == buyerAgent);
}
if (!string.IsNullOrWhiteSpace(invoiceNo))
{
queryCA = queryCA.Where(w => w.InvoiceNo == invoiceNo);
}
DateTime DateFrom = dateFrom == null ? new DateTime(1970, 1, 1) : (DateTime)dateFrom;
DateTime DateTo = dateTo == null ? DateTime.Now : (DateTime)dateTo;
queryCA = queryCA.Where(w => w.PaymentDate.AddHours(offset).Date >= DateFrom.Date && w.PaymentDate.AddHours(offset).Date <= DateTo.Date);
queryCA = queryCA.OrderBy(w => w.InvoiceNo);
var Query = (from a in queryCA
where a.PaymentTerm == (string.IsNullOrWhiteSpace(paymentTerm) ? a.PaymentTerm : paymentTerm)
select new GarmentCreditAdviceMonitoringViewModel
{
InvoiceNo = a.InvoiceNo,
InvoiceDate = a.Date,
PaymentDate = a.PaymentDate,
DocUploadDate = a.DocumentSendDate,
PaymentTerm = a.PaymentTerm,
Amount = a.Amount,
ToBePaid = a.AmountToBePaid,
NettNego = a.NettNego + a.BankCharges + a.OtherCharge + a.BankComission + a.DiscrepancyFee + a.CreditInterest,
BuyerName = a.BuyerName,
BuyerAddress = a.BuyerAddress,
BankName = a.BankAccountName,
NettNegoTT = a.PaymentTerm == "TT/OA" ? a.NettNego : 0,
BankChargeTT = a.PaymentTerm == "TT/OA" ? a.BankCharges : 0,
OtherChargeTT = a.PaymentTerm == "TT/OA" ? a.OtherCharge : 0,
SRNo = a.PaymentTerm == "LC" ? a.SRNo : "-",
SRDate = a.PaymentTerm == "LC" ? a.NegoDate : new DateTime(1970, 1, 1),
LCNo = a.PaymentTerm == "LC" ? a.LCNo : "-",
NettNegoLC = a.PaymentTerm == "LC" ? a.NettNego : 0,
BankChargeLC = a.PaymentTerm == "LC" ? a.BankCharges : 0,
BankComissionLC = a.PaymentTerm == "LC" ? a.BankComission : 0,
DiscreapancyFeeLC = a.PaymentTerm == "LC" ? a.DiscrepancyFee : 0,
CreditInterestLC = a.PaymentTerm == "LC" ? a.CreditInterest : 0,
});
return Query;
}
public List<GarmentCreditAdviceMonitoringViewModel> GetReportData(string buyerAgent, string invoiceNo, string paymentTerm, DateTime? dateFrom, DateTime? dateTo, int offset)
{
var Query = GetData(buyerAgent, invoiceNo, paymentTerm, dateFrom, dateTo, offset);
Query = Query.OrderBy(w => w.InvoiceNo);
return Query.ToList();
}
public MemoryStream GenerateExcel(string buyerAgent, string invoiceNo, string paymentTerm, DateTime? dateFrom, DateTime? dateTo, int offset)
{
var Query = GetData(buyerAgent, invoiceNo, paymentTerm, dateFrom, dateTo, offset);
DataTable result = new DataTable();
result.Columns.Add(new DataColumn() { ColumnName = "No", DataType = typeof(string) });
result.Columns.Add(new DataColumn() { ColumnName = "No Invoice", DataType = typeof(string) });
result.Columns.Add(new DataColumn() { ColumnName = "Tgl Invoice", DataType = typeof(string) });
result.Columns.Add(new DataColumn() { ColumnName = "Tgl Payment", DataType = typeof(string) });
result.Columns.Add(new DataColumn() { ColumnName = "Tgl Kirim Dokumen", DataType = typeof(string) });
result.Columns.Add(new DataColumn() { ColumnName = "Payment Term", DataType = typeof(string) });
result.Columns.Add(new DataColumn() { ColumnName = "Buyer Name", DataType = typeof(string) });
result.Columns.Add(new DataColumn() { ColumnName = "Buyer Address", DataType = typeof(string) });
result.Columns.Add(new DataColumn() { ColumnName = "Bank Name", DataType = typeof(string) });
result.Columns.Add(new DataColumn() { ColumnName = "Amount", DataType = typeof(string) });
result.Columns.Add(new DataColumn() { ColumnName = "Amount To Be Paid", DataType = typeof(string) });
result.Columns.Add(new DataColumn() { ColumnName = "Nett Nego | TT", DataType = typeof(string) });
result.Columns.Add(new DataColumn() { ColumnName = "Bank Charges | TT", DataType = typeof(string) });
result.Columns.Add(new DataColumn() { ColumnName = "Other Charges | TT", DataType = typeof(string) });
result.Columns.Add(new DataColumn() { ColumnName = "No LC | LC", DataType = typeof(string) });
result.Columns.Add(new DataColumn() { ColumnName = "No SR | LC", DataType = typeof(string) });
result.Columns.Add(new DataColumn() { ColumnName = "Tanggal SR | LC", DataType = typeof(string) });
result.Columns.Add(new DataColumn() { ColumnName = "Nett Nego | LC", DataType = typeof(string) });
result.Columns.Add(new DataColumn() { ColumnName = "Bank Comission | LC", DataType = typeof(string) });
result.Columns.Add(new DataColumn() { ColumnName = "Discreapancy Fee | LC", DataType = typeof(string) });
result.Columns.Add(new DataColumn() { ColumnName = "Credit Interest | LC", DataType = typeof(string) });
result.Columns.Add(new DataColumn() { ColumnName = "Bank Charges | LC", DataType = typeof(string) });
if (Query.ToArray().Count() == 0)
result.Rows.Add("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
else
{
Dictionary<string, List<GarmentCreditAdviceMonitoringViewModel>> dataByBrand = new Dictionary<string, List<GarmentCreditAdviceMonitoringViewModel>>();
Dictionary<string, double> subTotalAMT = new Dictionary<string, double>();
Dictionary<string, double> subTotalTBP = new Dictionary<string, double>();
Dictionary<string, double> subTotalNett = new Dictionary<string, double>();
Dictionary<string, double> subTotalNettTT = new Dictionary<string, double>();
Dictionary<string, double> subTotalNettLC = new Dictionary<string, double>();
Dictionary<string, double> outStanding = new Dictionary<string, double>();
foreach (GarmentCreditAdviceMonitoringViewModel item in Query.ToList())
{
string BrandName = item.InvoiceNo;
if (!dataByBrand.ContainsKey(BrandName)) dataByBrand.Add(BrandName, new List<GarmentCreditAdviceMonitoringViewModel> { });
dataByBrand[BrandName].Add(new GarmentCreditAdviceMonitoringViewModel
{
InvoiceNo = item.InvoiceNo,
InvoiceDate = item.InvoiceDate,
PaymentDate = item.PaymentDate,
DocUploadDate = item.DocUploadDate,
PaymentTerm = item.PaymentTerm,
Amount = item.Amount,
ToBePaid = item.ToBePaid,
BuyerName = item.BuyerName,
BuyerAddress = item.BuyerAddress,
BankName = item.BankName,
NettNego = item.NettNego,
NettNegoTT = item.NettNegoTT,
BankChargeTT = item.BankChargeTT,
OtherChargeTT = item.OtherChargeTT,
SRNo = item.SRNo,
SRDate = item.SRDate,
LCNo = item.LCNo,
NettNegoLC = item.NettNegoLC,
BankChargeLC = item.BankChargeLC,
BankComissionLC = item.BankComissionLC,
DiscreapancyFeeLC = item.DiscreapancyFeeLC,
CreditInterestLC = item.CreditInterestLC,
});
if (!subTotalNett.ContainsKey(BrandName))
{
subTotalNett.Add(BrandName, 0);
};
if (!subTotalNettTT.ContainsKey(BrandName))
{
subTotalNettTT.Add(BrandName, 0);
};
if (!subTotalNettLC.ContainsKey(BrandName))
{
subTotalNettLC.Add(BrandName, 0);
};
subTotalAMT[BrandName] = item.Amount;
subTotalTBP[BrandName] = item.ToBePaid;
subTotalNett[BrandName] += item.NettNego;
subTotalNettTT[BrandName] += item.NettNegoTT;
subTotalNettLC[BrandName] += item.NettNegoLC;
outStanding[BrandName] = subTotalTBP[BrandName] - subTotalNett[BrandName];
}
int rowPosition = 1;
foreach (KeyValuePair<string, List<GarmentCreditAdviceMonitoringViewModel>> BuyerBrand in dataByBrand)
{
string BrandCode = "";
int index = 0;
foreach (GarmentCreditAdviceMonitoringViewModel item in BuyerBrand.Value)
{
index++;
string InvDate = item.InvoiceDate == new DateTime(1970, 1, 1) ? "-" : item.InvoiceDate.ToOffset(new TimeSpan(offset, 0, 0)).ToString("dd MMM yyyy", new CultureInfo("id-ID"));
string DocDate = item.DocUploadDate == new DateTime(1970, 1, 1) ? "-" : item.DocUploadDate.ToOffset(new TimeSpan(offset, 0, 0)).ToString("dd MMM yyyy", new CultureInfo("id-ID"));
string SRDate = item.SRDate == new DateTime(1970, 1, 1) ? "-" : item.SRDate.ToOffset(new TimeSpan(offset, 0, 0)).ToString("dd MMM yyyy", new CultureInfo("id-ID"));
string PayDate = item.PaymentDate == new DateTime(1970, 1, 1) ? "-" : item.PaymentDate.ToOffset(new TimeSpan(offset, 0, 0)).ToString("dd MMM yyyy", new CultureInfo("id-ID"));
string AmtFOB = string.Format("{0:N2}", item.Amount);
string AmtPaid = string.Format("{0:N2}", item.ToBePaid);
string NettTT = string.Format("{0:N2}", item.Amount);
string BChrgTT = string.Format("{0:N2}", item.ToBePaid);
string OChrgTT = string.Format("{0:N2}", item.Amount);
string CommLC = string.Format("{0:N2}", item.ToBePaid);
string FeeLC = string.Format("{0:N2}", item.Amount);
string NettLC = string.Format("{0:N2}", item.ToBePaid);
string IntLC = string.Format("{0:N2}", item.Amount);
string BChrgLC = string.Format("{0:N2}", item.ToBePaid);
result.Rows.Add(index, item.InvoiceNo, InvDate, PayDate, DocDate, item.PaymentTerm, item.BuyerName, item.BuyerAddress, item.BankName,
AmtFOB, AmtPaid, NettTT, BChrgTT, OChrgTT, item.LCNo, item.SRNo, SRDate, CommLC, FeeLC, NettLC, IntLC, BChrgLC);
rowPosition += 1;
BrandCode = item.InvoiceNo;
}
result.Rows.Add("", "", "INVOICE NO :", BrandCode, "", "AMOUNT :", Math.Round(subTotalAMT[BuyerBrand.Key], 2), "", "AMOUNT TO BE PAID :", Math.Round(subTotalTBP[BuyerBrand.Key], 2), "", "PAID AMOUNT :", Math.Round(subTotalNett[BuyerBrand.Key], 2), "", "OUTSTANDING AMOUNT :", Math.Round(outStanding[BuyerBrand.Key], 2), "", "", "");
rowPosition += 1;
}
}
return Excel.CreateExcel(new List<KeyValuePair<DataTable, string>>() { new KeyValuePair<DataTable, string>(result, "Sheet1") }, true);
}
}
}
| 60.026087 | 352 | 0.558525 | [
"MIT"
] | AndreaZain/com-danliris-service-packing-inventory | src/Com.Danliris.Service.Packing.Inventory.Application/ToBeRefactored/GarmentShipping/Monitoring/GarmentCreditAdvice/GarmentCreditAdviceMonitoringService.cs | 13,808 | C# |
using System.Diagnostics;
namespace BorderlessGaming.Logic.Extensions
{
internal static class ProcessExtensions
{
private static string FindIndexedProcessName(int pid)
{
var processName = Process.GetProcessById(pid).ProcessName;
var processesByName = Process.GetProcessesByName(processName);
string processIndexdName = null;
for (var index = 0; index < processesByName.Length; index++)
{
processIndexdName = index == 0 ? processName : processName + "#" + index;
var processId = new PerformanceCounter("Process", "ID Process", processIndexdName);
if ((int) processId.NextValue() == pid)
{
return processIndexdName;
}
}
return processIndexdName;
}
private static Process FindPidFromIndexedProcessName(string indexedProcessName)
{
var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);
return Process.GetProcessById((int) parentId.NextValue());
}
public static Process Parent(this Process process)
{
return FindPidFromIndexedProcessName(FindIndexedProcessName(process.Id));
}
}
} | 35.837838 | 104 | 0.610106 | [
"MIT"
] | aliostad/deep-learning-lang-detection | data/test/csharp/49f521f84e08750105b678bbc2b20557b7a8d4b6ProcessExtensions.cs | 1,328 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WDE.QuestChainEditor.Editor.ViewModels;
namespace WDE.QuestChainEditor.Editor.Views
{
/// <summary>
/// Interaction logic for QuestPickerWindow.xaml
/// </summary>
public partial class QuestPickerWindow : Window
{
public QuestPickerWindow()
{
InitializeComponent();
}
private void NodePicker_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
DialogResult = true;
Close();
}
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
e.Handled = true;
DialogResult = true;
Close();
}
else
base.OnPreviewKeyDown(e);
}
}
}
| 25.104167 | 94 | 0.624896 | [
"Unlicense"
] | alexkulya/WoWDatabaseEditor | WDE.QuestChainEditor/Editor/Views/QuestPickerWindow.xaml.cs | 1,207 | C# |
//
// Copyright (c) 2006-2018 Erik Ylvisaker
//
// 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.
//
namespace AgateLib.Mathematics.Geometry.Algorithms.CollisionDetection
{
/// <summary>
/// Structure which contains information about collision between two polygons.
/// </summary>
public class ContactPoint
{
/// <summary>
/// The first polygon.
/// </summary>
public Polygon FirstPolygon { get; set; }
/// <summary>
/// The second polygon.
/// </summary>
public Polygon SecondPolygon { get; set; }
/// <summary>
/// The point on the perimeter of the first polygon that contacts the second polygon.
/// </summary>
public Microsoft.Xna.Framework.Vector2 FirstPolygonContactPoint { get; set; }
/// <summary>
/// The point on the perimeter of the second polygon that contacts the first polygon.
/// </summary>
public Microsoft.Xna.Framework.Vector2 SecondPolygonContactPoint { get; set; }
/// <summary>
/// The penetration vector.
/// </summary>
public Microsoft.Xna.Framework.Vector2 PenetrationDepth { get; set; }
/// <summary>
/// True if the two polygons touch, false if they do not.
/// </summary>
public bool Contact { get; set; }
/// <summary>
/// The normal of the contact edge for the first polygon.
/// </summary>
public Microsoft.Xna.Framework.Vector2 FirstPolygonNormal { get; set; }
/// <summary>
/// The normal of the contact edge for the second polygon.
/// </summary>
public Microsoft.Xna.Framework.Vector2 SecondPolygonNormal { get; set; }
/// <summary>
/// If the two polygons do not touch, this is the closest distance between them.
/// </summary>
public float DistanceToContact { get; set; }
}
} | 41.109589 | 93 | 0.648117 | [
"MIT"
] | eylvisaker/AgateLib | src/AgateLib/Mathematics/Geometry/Algorithms/CollisionDetection/ContactPoint.cs | 3,001 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
namespace NuGet.Insights
{
public static class XmlUtility
{
public static XDocument LoadXml(Stream stream)
{
var settings = new XmlReaderSettings
{
IgnoreWhitespace = true,
IgnoreComments = true,
IgnoreProcessingInstructions = true,
};
using (var streamReader = new StreamReader(stream))
using (var xmlReader = XmlReader.Create(streamReader, settings))
{
var document = XDocument.Load(xmlReader, LoadOptions.None);
// Make the document immutable.
document.Changing += (s, ev) =>
{
throw new NotSupportedException();
};
return document;
}
}
}
}
| 28.236842 | 111 | 0.560112 | [
"Apache-2.0"
] | NuGet/Insights | src/Logic/Support/XmlUtility.cs | 1,075 | C# |
using System;
namespace TXTCommunication.Fischertechnik.Txt.Response
{
class ResponseStopCamera : ResponseBase
{
public ResponseStopCamera()
{
ResponseId = TxtInterface.ResponseIdStopCameraOnline;
}
public override void FromByteArray(byte[] bytes)
{
if (bytes.Length < GetResponseLength())
{
throw new InvalidOperationException($"The byte array is to short to read. Length is {bytes.Length} bytes and {GetResponseLength()} bytes are needed");
}
var id = BitConverter.ToUInt32(bytes, 0);
if (id != ResponseId)
{
throw new InvalidOperationException($"The byte array does not match the response id. Expected id is {ResponseId} and response id is {id}");
}
}
}
}
| 29.413793 | 166 | 0.59789 | [
"MIT"
] | Bennik2000/FtApp | FtApp/FtApp/Fischertechnik/Txt/Response/ResponseStopCamera.cs | 855 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using backend.Models;
using Microsoft.Extensions.Logging;
using Nest;
namespace MeasurementApi.Services.Sensors
{
public interface ICurrentSensorValues {
Task<Device> SetSensorData(int deviceId, MetricType metricType, decimal value);
Task<Device> GetDevice(int deviceId);
decimal GetSensorData(int deviceId, MetricType metricType);
IEnumerable<Device> Devices { get; }
}
public class CurrentSensorValues : ICurrentSensorValues {
private readonly ISensorService _sensorService;
private readonly ILogger<CurrentSensorValues> _logger;
private readonly Dictionary<int, Device> _deviceCache;
public CurrentSensorValues(
Dictionary<int, Device> deviceCache,
ISensorService sensorService,
ILogger<CurrentSensorValues> logger) {
_deviceCache = deviceCache;
_sensorService = sensorService;
_logger = logger;
}
public IEnumerable<Device> Devices => _deviceCache.Values;
public async Task<Device> SetSensorData(int deviceId, MetricType metricType, decimal value) {
_logger.LogDebug("Looking for device id {deviceId}", deviceId);
if (!_deviceCache.ContainsKey(deviceId)) {
_logger.LogInformation("No device found");
var device = await GetOrCreateSensor(deviceId);
_deviceCache[device.DeviceId] = device;
}
_deviceCache[deviceId].AddTemperature(value);
return _deviceCache[deviceId];
}
private async Task<Device> GetOrCreateSensor(int deviceId) {
_logger.LogDebug("Find device with id {deviceId}", deviceId);
var metadata = await _sensorService.Get(deviceId);
if (metadata == null) {
metadata = new DeviceMetadata {DeviceId = deviceId};
_logger.LogInformation("Saving device {deviceId}", deviceId);
var result = await _sensorService.Add(metadata);
if(!result) {
_logger.LogError("Failed saving device {deviceId}", deviceId);
throw new Exception("Unable to add sensor");
}
_logger.LogInformation("Device {deviceId} saved", deviceId);
}
var device = new Device(metadata);
return device;
}
public async Task<Device> GetDevice(int deviceId) {
return await GetOrCreateSensor(deviceId);
}
public decimal GetSensorData(int deviceId, MetricType metricType) {
return _deviceCache.ContainsKey(deviceId)
? _deviceCache[deviceId].Temperature.Value
: -1;
}
}
public class Device {
private readonly Temperature _temperature = new Temperature();
public Device(DeviceMetadata metadata) {
Metadata = metadata;
}
public DeviceMetadata Metadata { get; set; }
public DateTime LastMeasurement { get; set; }
public string Timestamp => LastMeasurement.ToString("u");
public DeviceStatus Status { get; set; }
public int DeviceId => Metadata.DeviceId;
public void AddTemperature(decimal value) {
LastMeasurement = DateTime.Now;
Status = DeviceStatus.Ok;
_temperature.Value = value;
}
public Temperature Temperature => _temperature;
}
public enum DeviceStatus {
Initializing,
Ok,
Late
}
public abstract class Sensor<T> {
public abstract MetricType Type { get; }
public T Value { get; set; }
}
public class Temperature : Sensor<decimal> {
public override MetricType Type => MetricType.Temperature;
}
} | 35.418182 | 101 | 0.623973 | [
"MIT"
] | fhelje/CollectSens | src/backend/Services/Sensors/CurrentSensorValues.cs | 3,896 | C# |
//MIT License
//Copyright (c) 2020 Mohammed Iqubal Hussain
//Website : Polyandcode.com
using UnityEngine.UI;
using UnityEditor.AnimatedValues;
using UnityEditor;
using UnityEngine;
namespace PolyAndCode.UI
{
[CustomEditor(typeof(RecyclableScrollRect), true)]
[CanEditMultipleObjects]
/// <summary>
/// Custom Editor for the Recyclable Scroll Rect Component which is derived from Scroll Rect.
/// </summary>
public class RecyclableScrollRectEditor : Editor
{
SerializedProperty m_Content;
SerializedProperty m_MovementType;
SerializedProperty m_Elasticity;
SerializedProperty m_Inertia;
SerializedProperty m_DecelerationRate;
SerializedProperty m_ScrollSensitivity;
SerializedProperty m_Viewport;
SerializedProperty m_OnValueChanged;
//inherited
SerializedProperty _protoTypeCell;
SerializedProperty _selfInitialize;
SerializedProperty _direction;
SerializedProperty _type;
AnimBool m_ShowElasticity;
AnimBool m_ShowDecelerationRate;
RecyclableScrollRect _script;
protected virtual void OnEnable()
{
_script = (RecyclableScrollRect)target;
m_Content = serializedObject.FindProperty("m_Content");
m_MovementType = serializedObject.FindProperty("m_MovementType");
m_Elasticity = serializedObject.FindProperty("m_Elasticity");
m_Inertia = serializedObject.FindProperty("m_Inertia");
m_DecelerationRate = serializedObject.FindProperty("m_DecelerationRate");
m_ScrollSensitivity = serializedObject.FindProperty("m_ScrollSensitivity");
m_Viewport = serializedObject.FindProperty("m_Viewport");
m_OnValueChanged = serializedObject.FindProperty("m_OnValueChanged");
//Inherited
_protoTypeCell = serializedObject.FindProperty("PrototypeCell");
_selfInitialize = serializedObject.FindProperty("SelfInitialize");
_direction = serializedObject.FindProperty("Direction");
_type = serializedObject.FindProperty("IsGrid");
m_ShowElasticity = new AnimBool(Repaint);
m_ShowDecelerationRate = new AnimBool(Repaint);
SetAnimBools(true);
}
protected virtual void OnDisable()
{
m_ShowElasticity.valueChanged.RemoveListener(Repaint);
m_ShowDecelerationRate.valueChanged.RemoveListener(Repaint);
}
void SetAnimBools(bool instant)
{
SetAnimBool(m_ShowElasticity, !m_MovementType.hasMultipleDifferentValues && m_MovementType.enumValueIndex == (int)ScrollRect.MovementType.Elastic, instant);
SetAnimBool(m_ShowDecelerationRate, !m_Inertia.hasMultipleDifferentValues && m_Inertia.boolValue, instant);
}
void SetAnimBool(AnimBool a, bool value, bool instant)
{
if (instant)
a.value = value;
else
a.target = value;
}
public override void OnInspectorGUI()
{
SetAnimBools(false);
serializedObject.Update();
EditorGUILayout.PropertyField(_direction);
EditorGUILayout.PropertyField(_type, new GUIContent("Grid"));
if (_type.boolValue)
{
string title = _direction.enumValueIndex == (int)RecyclableScrollRect.DirectionType.Vertical ? "Coloumns" : "Rows";
_script.Segments = EditorGUILayout.IntField(title, _script.Segments);
}
EditorGUILayout.PropertyField(_selfInitialize);
EditorGUILayout.PropertyField(m_Viewport);
EditorGUILayout.PropertyField(m_Content);
EditorGUILayout.PropertyField(_protoTypeCell);
EditorGUILayout.Space();
EditorGUILayout.PropertyField(m_MovementType);
if (EditorGUILayout.BeginFadeGroup(m_ShowElasticity.faded))
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_Elasticity);
EditorGUI.indentLevel--;
}
EditorGUILayout.EndFadeGroup();
EditorGUILayout.PropertyField(m_Inertia);
if (EditorGUILayout.BeginFadeGroup(m_ShowDecelerationRate.faded))
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_DecelerationRate);
EditorGUI.indentLevel--;
}
EditorGUILayout.EndFadeGroup();
EditorGUILayout.PropertyField(m_ScrollSensitivity);
EditorGUILayout.Space();
EditorGUILayout.PropertyField(m_OnValueChanged);
serializedObject.ApplyModifiedProperties();
}
}
} | 37.333333 | 168 | 0.653447 | [
"MIT"
] | MdIqubal/Recyclable-Scroll-Rect | Assets/Recyclable Scroll Rect/Main/Editor/RecyclableScrollRectEditor.cs | 4,818 | C# |
// <copyright file="ApiKeyAuthenticationRequest.cs" company="Stormpath, Inc.">
// Copyright (c) 2016 Stormpath, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using Stormpath.SDK.AccountStore;
using Stormpath.SDK.Auth;
namespace Stormpath.SDK.Impl.Auth
{
internal sealed class ApiKeyAuthenticationRequest : IAuthenticationRequest
{
private readonly string id;
private readonly string secret;
public ApiKeyAuthenticationRequest(string id, string secret)
{
this.id = id;
this.secret = secret;
}
string IAuthenticationRequest<string, string>.Principals => this.id;
string IAuthenticationRequest<string, string>.Credentials => this.secret;
IAccountStore IAuthenticationRequest<string, string>.AccountStore => null;
}
}
| 33.875 | 82 | 0.712915 | [
"Apache-2.0"
] | stormpath/stormpath-sdk-csharp | src/Stormpath.SDK.Core/Impl/Auth/ApiKeyAuthenticationRequest.cs | 1,357 | C# |
using BTCPayServer.Client.Models;
using BTCPayServer.HostedServices;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
namespace BTCPayServer.Controllers.Greenfield
{
[Controller]
[EnableCors(CorsPolicies.All)]
public class GreenfieldHealthController : ControllerBase
{
private readonly NBXplorerDashboard _dashBoard;
public GreenfieldHealthController(NBXplorerDashboard dashBoard)
{
_dashBoard = dashBoard;
}
[AllowAnonymous]
[HttpGet("~/api/v1/health")]
public ActionResult GetHealth()
{
ApiHealthData model = new ApiHealthData()
{
Synchronized = _dashBoard.IsFullySynched()
};
return Ok(model);
}
}
}
| 26.806452 | 71 | 0.65343 | [
"MIT"
] | BTCparadigm/btcpayserver | BTCPayServer/Controllers/GreenField/GreenfieldHealthController.cs | 831 | C# |
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace Dex.Uwp.Controls
{
public class PointerAppBarButton : AppBarToggleButton
{
private static readonly CoreCursor arrowCursor = new CoreCursor(CoreCursorType.Arrow, 1);
private static readonly CoreCursor handCursor = new CoreCursor(CoreCursorType.Hand, 1);
public PointerAppBarButton()
{
PointerEntered += (sender, e) =>
{
Window.Current.CoreWindow.PointerCursor = handCursor;
};
PointerExited += (sender, e) =>
{
Window.Current.CoreWindow.PointerCursor = arrowCursor;
};
}
}
} | 30 | 97 | 0.611111 | [
"MIT"
] | disklosr/Dexr | Dex.Uwp/Controls/PointerAppBarButton.cs | 722 | C# |
using System;
using NUnit.Framework;
using Suckless.Asserts.Tests.Base;
namespace Suckless.Asserts.Tests.ExtensionMethods
{
internal partial class EmptyTest : AssertBaseTest<ArgumentOutOfRangeException>
{
[Test]
public void Empty_WhenStringIsNull_DoesNotThrowException()
{
StubMetadata<string>(null).Empty();
}
[Test]
public void Empty_WhenStringIsEmpty_DoesNotThrowException()
{
StubMetadata("").Empty();
}
[TestCase(null), TestCase("AnyName")]
public void Empty_WhenStringIsNotEmpty_ThrowsExceptionWithCorrectMessage(string fieldName)
{
var expectedMessagePart = "must be empty.";
AssertExceptionMessage<string>(() => StubMetadata("Any", fieldName).Empty(),
expectedName: fieldName,
expectedMessagePart);
}
[TestCase(null), TestCase("AnyName")]
public void Empty_WhenAssertionFailedAdnCustomMessageWasSpecyfied_ThrowsExceptionWithCorrectMessage(string fieldName)
{
AssertCustomExceptionMessage(() => StubMetadata("Any", fieldName).Empty(CUSTOM_MESSAGE),
expected: CUSTOM_MESSAGE);
}
}
}
| 31.948718 | 125 | 0.649278 | [
"MIT"
] | Ja-rek/Suckless.Assert | Suckless.Asserts.Tests/ExtensionMethods/EmptyTest.String.cs | 1,246 | C# |
using UnityEngine;
using UnityEngine.UI;
namespace PUNLobby.Room
{
public class RoomSlotPanel : MonoBehaviour
{
public Image roomMaster;
public Image readySign;
public Text playerNameText;
public void Set(bool isMaster, string playerName, bool isReady)
{
roomMaster.gameObject.SetActive(isMaster);
readySign.gameObject.SetActive(isMaster || isReady);
playerNameText.text = playerName;
}
}
}
| 24.5 | 71 | 0.646939 | [
"MIT"
] | ArcturusZhang/Mahjong | Assets/Scripts/PUNLobby/Room/RoomSlotPanel.cs | 492 | C# |
using System;
using System.Collections.Generic;
using AutoMapper;
using DotNetCore.CAP;
using FreeSql;
using LinCms.Application.Contracts.Blog.Notifications;
using LinCms.Application.Contracts.Blog.Notifications.Dtos;
using LinCms.Application.Contracts.Blog.UserSubscribes;
using LinCms.Application.Contracts.Blog.UserSubscribes.Dtos;
using LinCms.Application.Contracts.Cms.Users;
using LinCms.Application.Contracts.Cms.Users.Dtos;
using LinCms.Core.Data;
using LinCms.Core.Entities;
using LinCms.Core.Entities.Blog;
using LinCms.Core.Exceptions;
using LinCms.Core.Extensions;
using LinCms.Core.IRepositories;
using LinCms.Core.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace LinCms.Web.Controllers.Blog
{
/// <summary>
/// 用户订阅
/// </summary>
[Route("v1/subscribe")]
[ApiController]
[Authorize]
public class UserSubscribeController : ControllerBase
{
private readonly IAuditBaseRepository<UserSubscribe> _userSubscribeRepository;
private readonly IUserRepository _userRepository;
private readonly ICurrentUser _currentUser;
private readonly BaseRepository<UserTag> _userTagRepository;
private readonly ICapPublisher _capBus;
public UserSubscribeController(IAuditBaseRepository<UserSubscribe> userSubscribeRepository, ICurrentUser currentUser, IUserRepository userRepository, BaseRepository<UserTag> userTagRepository, ICapPublisher capPublisher)
{
_userSubscribeRepository = userSubscribeRepository;
_currentUser = currentUser;
_userRepository = userRepository;
_userTagRepository = userTagRepository;
_capBus = capPublisher;
}
/// <summary>
/// 判断当前登录的用户是否关注了beSubscribeUserId
/// </summary>
/// <param name="subscribeUserId"></param>
/// <returns></returns>
[HttpGet("{subscribeUserId}")]
[AllowAnonymous]
public bool Get(long subscribeUserId)
{
if (_currentUser.Id == null) return false;
return _userSubscribeRepository.Select.Any(r => r.SubscribeUserId == subscribeUserId && r.CreateUserId == _currentUser.Id);
}
/// <summary>
/// 取消关注用户
/// </summary>
/// <param name="subscribeUserId"></param>
[HttpDelete("{subscribeUserId}")]
public void Delete(long subscribeUserId)
{
bool any = _userSubscribeRepository.Select.Any(r => r.CreateUserId == _currentUser.Id && r.SubscribeUserId == subscribeUserId);
if (!any)
{
throw new LinCmsException("已取消关注");
}
_userSubscribeRepository.Delete(r => r.SubscribeUserId == subscribeUserId && r.CreateUserId == _currentUser.Id);
}
/// <summary>
/// 关注用户
/// </summary>
/// <param name="subscribeUserId"></param>
[HttpPost("{subscribeUserId}")]
public void Post(long subscribeUserId)
{
if (subscribeUserId == _currentUser.Id)
{
throw new LinCmsException("您无法关注自己");
}
LinUser linUser = _userRepository.Select.Where(r => r.Id == subscribeUserId).ToOne();
if (linUser == null)
{
throw new LinCmsException("该用户不存在");
}
if (!linUser.IsActive())
{
throw new LinCmsException("该用户已被拉黑");
}
bool any = _userSubscribeRepository.Select.Any(r =>
r.CreateUserId == _currentUser.Id && r.SubscribeUserId == subscribeUserId);
if (any)
{
throw new LinCmsException("您已关注该用户");
}
UserSubscribe userSubscribe = new UserSubscribe() { SubscribeUserId = subscribeUserId };
_userSubscribeRepository.Insert(userSubscribe);
_capBus.Publish("NotificationController.Post", new CreateNotificationDto()
{
NotificationType = NotificationType.UserLikeUser,
NotificationRespUserId = subscribeUserId,
UserInfoId = _currentUser.Id ?? 0,
CreateTime = DateTime.Now,
});
}
/// <summary>
/// 得到某个用户的关注
/// </summary>
/// <returns></returns>
[HttpGet]
[AllowAnonymous]
public PagedResultDto<UserSubscribeDto> GetUserSubscribeeeList([FromQuery]UserSubscribeSearchDto searchDto)
{
var userSubscribes = _userSubscribeRepository.Select.Include(r => r.SubscribeUser)
.Where(r => r.CreateUserId == searchDto.UserId)
.OrderByDescending(r => r.CreateTime)
.ToPager(searchDto, out long count)
.ToList(r => new UserSubscribeDto
{
CreateUserId = r.CreateUserId,
SubscribeUserId = r.SubscribeUserId,
Subscribeer = new OpenUserDto()
{
Id = r.SubscribeUser.Id,
Introduction = r.SubscribeUser.Introduction,
Nickname = !r.SubscribeUser.IsDeleted ? r.SubscribeUser.Nickname : "该用户已注销",
Avatar = r.SubscribeUser.Avatar,
Username = r.SubscribeUser.Username,
},
IsSubscribeed = _userSubscribeRepository.Select.Any(u =>
u.CreateUserId == _currentUser.Id && u.SubscribeUserId == r.SubscribeUserId)
});
userSubscribes.ForEach(r => { r.Subscribeer.Avatar = _currentUser.GetFileUrl(r.Subscribeer.Avatar); });
return new PagedResultDto<UserSubscribeDto>(userSubscribes, count);
}
/// <summary>
/// 得到某个用户的粉丝
/// </summary>
/// <returns></returns>
[HttpGet("fans")]
[AllowAnonymous]
public PagedResultDto<UserSubscribeDto> GetUserFansList([FromQuery]UserSubscribeSearchDto searchDto)
{
List<UserSubscribeDto> userSubscribes = _userSubscribeRepository.Select.Include(r => r.LinUser)
.Where(r => r.SubscribeUserId == searchDto.UserId)
.OrderByDescending(r => r.CreateTime)
.ToPager(searchDto, out long count)
.ToList(r => new UserSubscribeDto
{
CreateUserId = r.CreateUserId,
SubscribeUserId = r.SubscribeUserId,
Subscribeer = new OpenUserDto()
{
Id = r.LinUser.Id,
Introduction = r.LinUser.Introduction,
Nickname = !r.LinUser.IsDeleted ? r.LinUser.Nickname:"该用户已注销",
Avatar = r.LinUser.Avatar,
Username = r.LinUser.Username,
},
//当前登录的用户是否关注了这个粉丝
IsSubscribeed = _userSubscribeRepository.Select.Any(
u => u.CreateUserId == _currentUser.Id && u.SubscribeUserId == r.CreateUserId)
});
userSubscribes.ForEach(r => { r.Subscribeer.Avatar = _currentUser.GetFileUrl(r.Subscribeer.Avatar); });
return new PagedResultDto<UserSubscribeDto>(userSubscribes, count);
}
/// <summary>
/// 得到某个用户的关注了、关注者、标签总数
/// </summary>
/// <param name="userId"></param>
[HttpGet("user/{userId}")]
[AllowAnonymous]
public SubscribeCountDto GetUserSubscribeInfo(long userId)
{
long subscribeCount = _userSubscribeRepository.Select
.Where(r => r.CreateUserId == userId)
.Count();
long fansCount = _userSubscribeRepository.Select
.Where(r => r.SubscribeUserId == userId)
.Count();
long tagCount = _userTagRepository.Select.Include(r => r.Tag)
.Where(r => r.CreateUserId == userId).Count();
return new SubscribeCountDto
{
SubscribeCount = subscribeCount,
FansCount = fansCount,
TagCount = tagCount
};
}
}
} | 39.260664 | 228 | 0.582931 | [
"MIT"
] | gufeng0719/lin-cms-dotnetcore | src/LinCms.Web/Controllers/Blog/UserSubscribeController.cs | 8,536 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace DAL
{
public class DALAssembly
{
}
}
| 11.636364 | 33 | 0.695313 | [
"MIT"
] | adnanioricce/DHsys | src/Libraries/DAL/DAL.cs | 130 | C# |
using Kros.Authorization.Api.Domain;
using Kros.Utils;
using Mapster;
using MediatR;
using Microsoft.Extensions.Caching.Memory;
using System.Threading;
using System.Threading.Tasks;
namespace Kros.Authorization.Api.Application.Commands
{
/// <summary>
/// Update user command handler.
/// </summary>
public class UpdateUserCommandHandler : IRequestHandler<UpdateUserCommand>
{
private readonly IUserRepository _repository;
private readonly IMemoryCache _cache;
/// <summary>
/// Ctor.
/// </summary>
/// <param name="repository">User repository.</param>
/// <param name="cache">Cache.</param>
public UpdateUserCommandHandler(IUserRepository repository, IMemoryCache cache)
{
_repository = Check.NotNull(repository, nameof(repository));
_cache = Check.NotNull(cache, nameof(cache));
}
/// <inheritdoc />
public async Task<Unit> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
{
var user = request.Adapt<User>();
await _repository.UpdateUserAsync(user);
_cache.Remove(request.Email);
return Unit.Value;
}
}
}
| 29.619048 | 102 | 0.645498 | [
"MIT"
] | Kros-sk/Kros.AspNetCore.BestPractices | src/Services/Kros.Authorization.Api/Application/Commands/UpdateUser/UpdateUserCommandHandler.cs | 1,246 | C# |
using Microsoft.EntityFrameworkCore;
using SharedTrip.Data;
using SharedTrip.Services;
using SharedTrip.Services.Contacts;
using System.Threading.Tasks;
using MyWebServer;
using MyWebServer.Controllers;
using SharedTrip.Controllers;
using MyWebServer.Results.Views;
namespace SharedTrip
{
public class Startup
{
public static async Task Main()
=> await HttpServer
.WithRoutes(routes => routes
.MapStaticFiles()
.MapControllers())
.WithServices(services => services
.Add<IViewEngine, CompilationViewEngine>()
.Add<ApplicationDbContext>()
.Add<IValidator, Validator>()
.Add<IUserService, UserService>()
.Add<IPasswordHasher, PasswordHasher>())
.WithConfiguration<ApplicationDbContext>(c => c.Database.Migrate())
.Start();
}
}
| 32.066667 | 83 | 0.602911 | [
"MIT"
] | TsonevD/CSharpWebBasics | SharedTrips/SharedTrip/Startup.cs | 964 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ivony.Html.Parser.ContentModels;
namespace Ivony.Html.Parser
{
/// <summary>
/// HTML 内容元素读取枚举器
/// </summary>
public interface IHtmlReader
{
/// <summary>
/// 正在读取分析的 HTML 文本
/// </summary>
string HtmlText
{
get;
}
/// <summary>
/// 获取 HTML 内容元素枚举器
/// </summary>
/// <returns>HTML 内容枚举器</returns>
IEnumerable<HtmlContentFragment> EnumerateContent();
/// <summary>
/// 进入 CData 元素读取模式
/// </summary>
/// <remarks>读取器一旦进入CData元素读取模式,便会将除了元素结束标签之外的一切 HTML 内容当作文本返回。当遇到元素结束标签时,读取器应当自动退出 CData 元素读取模式</remarks>
/// <param name="elementName">CData 元素名</param>
void EnterCDataMode( string elementName );
}
}
| 19.268293 | 110 | 0.639241 | [
"Apache-2.0"
] | ArmyMedalMei/Jumony | Ivony.Html.Parser/IHtmlReader.cs | 1,008 | C# |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using asp_assignment.Models.BagStore;
namespace asp_assignment.Migrations
{
[DbContext(typeof(StoreContext))]
[Migration("20170510015247_NewData")]
partial class NewData
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.0-rtm-21431")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("asp_assignment.Models.BagStore.CartItem", b =>
{
b.Property<int>("CartItemId")
.ValueGeneratedOnAdd();
b.Property<DateTime>("LastUpdated");
b.Property<DateTime>("PriceCalculated");
b.Property<decimal>("PricePerUnit");
b.Property<int>("ProductId");
b.Property<int>("Quantity");
b.Property<string>("UserId");
b.HasKey("CartItemId");
b.HasIndex("ProductId");
b.ToTable("CartItems");
});
modelBuilder.Entity("asp_assignment.Models.BagStore.Category", b =>
{
b.Property<int>("CategoryId")
.ValueGeneratedOnAdd();
b.Property<string>("DisplayName")
.IsRequired();
b.Property<int?>("ParentCategoryId");
b.HasKey("CategoryId");
b.HasIndex("ParentCategoryId");
b.ToTable("Categories");
});
modelBuilder.Entity("asp_assignment.Models.BagStore.Order", b =>
{
b.Property<int>("OrderId")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CheckoutBegan");
b.Property<decimal>("GrandTotal");
b.Property<DateTime?>("OrderPlaced");
b.Property<int>("State");
b.Property<decimal>("Total");
b.Property<string>("UserId");
b.HasKey("OrderId");
b.ToTable("Orders");
});
modelBuilder.Entity("asp_assignment.Models.BagStore.OrderLine", b =>
{
b.Property<int>("OrderId");
b.Property<int>("ProductId");
b.Property<decimal>("PricePerUnit");
b.Property<int>("Quantity");
b.HasKey("OrderId", "ProductId");
b.HasIndex("OrderId");
b.HasIndex("ProductId");
b.ToTable("OrderLine");
});
modelBuilder.Entity("asp_assignment.Models.BagStore.OrderShippingDetails", b =>
{
b.Property<int>("OrderId");
b.Property<string>("Addressee")
.IsRequired();
b.Property<string>("CityOrTown")
.IsRequired();
b.Property<string>("Country")
.IsRequired();
b.Property<string>("LineOne")
.IsRequired();
b.Property<string>("LineTwo");
b.Property<string>("StateOrProvince")
.IsRequired();
b.Property<string>("ZipOrPostalCode")
.IsRequired();
b.HasKey("OrderId");
b.HasIndex("OrderId")
.IsUnique();
b.ToTable("OrderShippingDetails");
});
modelBuilder.Entity("asp_assignment.Models.BagStore.Product", b =>
{
b.Property<int>("ProductId")
.ValueGeneratedOnAdd();
b.Property<int>("CategoryId");
b.Property<decimal>("CurrentPrice");
b.Property<string>("Description");
b.Property<string>("DisplayName")
.IsRequired();
b.Property<string>("ImageUrl");
b.Property<bool>("InStock");
b.Property<decimal>("MSRP");
b.Property<string>("SKU")
.IsRequired();
b.Property<int>("SupplierId");
b.HasKey("ProductId");
b.HasAlternateKey("SKU");
b.HasIndex("CategoryId");
b.HasIndex("SupplierId");
b.ToTable("Products");
});
modelBuilder.Entity("asp_assignment.Models.BagStore.Supplier", b =>
{
b.Property<int>("SupplierId")
.ValueGeneratedOnAdd();
b.Property<string>("Email")
.IsRequired();
b.Property<int>("HomePhone");
b.Property<int>("MobilePhone");
b.Property<string>("Name")
.IsRequired();
b.Property<int>("WorkPhone");
b.HasKey("SupplierId");
b.ToTable("Suppliers");
});
modelBuilder.Entity("asp_assignment.Models.BagStore.WebsiteAd", b =>
{
b.Property<int>("WebsiteAdId")
.ValueGeneratedOnAdd();
b.Property<string>("Details");
b.Property<DateTime?>("End");
b.Property<string>("ImageUrl");
b.Property<DateTime?>("Start");
b.Property<string>("TagLine");
b.Property<string>("Url");
b.HasKey("WebsiteAdId");
b.ToTable("WebsiteAds");
});
modelBuilder.Entity("asp_assignment.Models.BagStore.CartItem", b =>
{
b.HasOne("asp_assignment.Models.BagStore.Product", "Product")
.WithMany()
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("asp_assignment.Models.BagStore.Category", b =>
{
b.HasOne("asp_assignment.Models.BagStore.Category", "ParentCategory")
.WithMany("Children")
.HasForeignKey("ParentCategoryId");
});
modelBuilder.Entity("asp_assignment.Models.BagStore.OrderLine", b =>
{
b.HasOne("asp_assignment.Models.BagStore.Order", "Order")
.WithMany("Lines")
.HasForeignKey("OrderId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("asp_assignment.Models.BagStore.Product", "Product")
.WithMany()
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("asp_assignment.Models.BagStore.OrderShippingDetails", b =>
{
b.HasOne("asp_assignment.Models.BagStore.Order")
.WithOne("ShippingDetails")
.HasForeignKey("asp_assignment.Models.BagStore.OrderShippingDetails", "OrderId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("asp_assignment.Models.BagStore.Product", b =>
{
b.HasOne("asp_assignment.Models.BagStore.Category", "Category")
.WithMany("Products")
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("asp_assignment.Models.BagStore.Supplier", "Supplier")
.WithMany()
.HasForeignKey("SupplierId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| 32.109434 | 117 | 0.461629 | [
"MIT"
] | kapiton09/asp.netcoremvc-eccommerce-website | src/asp_assignment/Migrations/20170510015247_NewData.Designer.cs | 8,511 | C# |
using System.Collections.Generic;
namespace Discore.Http
{
/// <summary>
/// An optional set of parameters for modifying a guild voice channel.
/// </summary>
public class GuildVoiceChannelOptions
{
/// <summary>
/// Gets or sets the name of the channel (or null to leave unchanged).
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the sorting position of the channel (or null to leave unchanged).
/// </summary>
public int? Position { get; set; }
/// <summary>
/// Gets or sets the bitrate of the voice channel (or null to leave unchanged).
/// </summary>
public int? Bitrate { get; set; }
/// <summary>
/// Gets or sets the user limit of the voice channel (or null to leave unchanged).
/// <para>Set to zero to remove the user limit.</para>
/// </summary>
public int? UserLimit { get; set; }
/// <summary>
/// Gets or sets the ID of the parent category channel (or null to leave unchanged).
/// <para>Note: Set to <see cref="Snowflake.None"/> to clear the parent ID.</para>
/// </summary>
public Snowflake? ParentId { get; set; }
/// <summary>
/// Gets or sets the list of permission overwrites (or null to leave unchanged).
/// </summary>
public IList<OverwriteOptions> PermissionOverwrites { get; set; }
/// <summary>
/// Sets the name of the channel.
/// </summary>
public GuildVoiceChannelOptions SetName(string name)
{
Name = name;
return this;
}
/// <summary>
/// Sets the sorting position of the channel.
/// </summary>
public GuildVoiceChannelOptions SetPosition(int position)
{
Position = position;
return this;
}
/// <summary>
/// Sets the bitrate of the voice channel.
/// </summary>
public GuildVoiceChannelOptions SetBitrate(int bitrate)
{
Bitrate = bitrate;
return this;
}
/// <summary>
/// Sets the user limit of the voice channel.
/// </summary>
/// <param name="userLimit">The maximum number of users or zero to remove the limit.</param>
public GuildVoiceChannelOptions SetUserLimit(int userLimit)
{
UserLimit = userLimit;
return this;
}
/// <summary>
/// Sets the ID of the parent category channel.
/// </summary>
/// <param name="parentId">
/// The ID of the category to use as a parent or <see cref="Snowflake.None"/> to clear the parent ID.
/// </param>
public GuildVoiceChannelOptions SetParentId(Snowflake parentId)
{
ParentId = parentId;
return this;
}
/// <summary>
/// Sets the list of permission overwrites.
/// </summary>
public GuildVoiceChannelOptions SetPermissionOverwrites(IList<OverwriteOptions> permissionOverwrites)
{
PermissionOverwrites = permissionOverwrites;
return this;
}
internal DiscordApiData Build()
{
DiscordApiData data = new DiscordApiData(DiscordApiDataType.Container);
if (Name != null)
data.Set("name", Name);
if (Position.HasValue)
data.Set("position", Position.Value);
if (Bitrate.HasValue)
data.Set("bitrate", Bitrate.Value);
if (UserLimit.HasValue)
data.Set("user_limit", UserLimit.Value);
if (ParentId.HasValue)
{
if (ParentId.Value == Snowflake.None)
data.SetSnowflake("parent_id", null);
else
data.SetSnowflake("parent_id", ParentId.Value);
}
if (PermissionOverwrites != null)
{
DiscordApiData permissionOverwritesArray = new DiscordApiData(DiscordApiDataType.Array);
foreach (OverwriteOptions overwriteParam in PermissionOverwrites)
permissionOverwritesArray.Values.Add(overwriteParam.Build());
data.Set("permission_overwrites", permissionOverwritesArray);
}
return data;
}
}
}
| 33.276119 | 109 | 0.55416 | [
"MIT"
] | Francessco121/Discore | src/Discore/Http/GuildVoiceChannelOptions.cs | 4,461 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801
{
using static Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Extensions;
/// <summary>Collection of Diagnostic Categories</summary>
public partial class DiagnosticCategoryCollection
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject into a new instance of <see cref="DiagnosticCategoryCollection" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject instance to deserialize from.</param>
internal DiagnosticCategoryCollection(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
{_nextLink = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonString>("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)NextLink;}
{_value = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonArray>("value"), out var __jsonValue) ? If( __jsonValue as Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonArray, out var __v) ? new global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDiagnosticCategory[]>(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDiagnosticCategory) (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.DiagnosticCategory.FromJson(__u) )) ))() : null : Value;}
AfterFromJson(json);
}
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDiagnosticCategoryCollection.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDiagnosticCategoryCollection.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDiagnosticCategoryCollection FromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject json ? new DiagnosticCategoryCollection(json) : null;
}
/// <summary>
/// Serializes this instance of <see cref="DiagnosticCategoryCollection" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="DiagnosticCategoryCollection" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode" />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add );
}
if (null != this._value)
{
var __w = new Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.XNodeArray();
foreach( var __x in this._value )
{
AddIf(__x?.ToJson(null, serializationMode) ,__w.Add);
}
container.Add("value",__w);
}
AfterToJson(ref container);
return container;
}
}
} | 70.324561 | 661 | 0.683423 | [
"MIT"
] | Arsasana/azure-powershell | src/Functions/generated/api/Models/Api20190801/DiagnosticCategoryCollection.json.cs | 7,904 | C# |
#pragma checksum "/workspace/HandsWork/src/App/Views/Produtos/Index.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "76e44e4d3063dcd82ee75e7927ebacff380af3dd"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Produtos_Index), @"mvc.1.0.view", @"/Views/Produtos/Index.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "/workspace/HandsWork/src/App/Views/_ViewImports.cshtml"
using App;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"76e44e4d3063dcd82ee75e7927ebacff380af3dd", @"/Views/Produtos/Index.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"fb66e1bc724abc87aa845ae534bd1318213bdfd8", @"/Views/_ViewImports.cshtml")]
public class Views_Produtos_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<IEnumerable<App.ProdutoViewModel>>
{
private global::AspNetCore.Views_Produtos_Index.__Generated__SummaryViewComponentTagHelper __SummaryViewComponentTagHelper;
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("btn btn-info"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Create", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("supress-by-claim-name", "Produto", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("supress-by-claim-value", "Adicionar", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("name", "_ListaProdutos", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
#pragma warning restore 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::App.Extensions.ApagaElementoByClaimTagHelper __App_Extensions_ApagaElementoByClaimTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral("\n");
#nullable restore
#line 3 "/workspace/HandsWork/src/App/Views/Produtos/Index.cshtml"
ViewData["Title"] = "Lista de Produtos";
#line default
#line hidden
#nullable disable
WriteLiteral("\n<h1>");
#nullable restore
#line 7 "/workspace/HandsWork/src/App/Views/Produtos/Index.cshtml"
Write(ViewData["Title"]);
#line default
#line hidden
#nullable disable
WriteLiteral("</h1>\n<hr />\n\n");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("vc:Summary", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "76e44e4d3063dcd82ee75e7927ebacff380af3dd5193", async() => {
}
);
__SummaryViewComponentTagHelper = CreateTagHelper<global::AspNetCore.Views_Produtos_Index.__Generated__SummaryViewComponentTagHelper>();
__tagHelperExecutionContext.Add(__SummaryViewComponentTagHelper);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\n\n");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("p", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "76e44e4d3063dcd82ee75e7927ebacff380af3dd6080", async() => {
WriteLiteral("\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "76e44e4d3063dcd82ee75e7927ebacff380af3dd6335", async() => {
WriteLiteral("Novo Produto");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_1.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\n");
}
);
__App_Extensions_ApagaElementoByClaimTagHelper = CreateTagHelper<global::App.Extensions.ApagaElementoByClaimTagHelper>();
__tagHelperExecutionContext.Add(__App_Extensions_ApagaElementoByClaimTagHelper);
__App_Extensions_ApagaElementoByClaimTagHelper.IdentityClaimName = (string)__tagHelperAttribute_2.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2);
__App_Extensions_ApagaElementoByClaimTagHelper.IdentityClaimValue = (string)__tagHelperAttribute_3.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\n\n");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("partial", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "76e44e4d3063dcd82ee75e7927ebacff380af3dd8700", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper.Name = (string)__tagHelperAttribute_4.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<IEnumerable<App.ProdutoViewModel>> Html { get; private set; }
[Microsoft.AspNetCore.Razor.TagHelpers.HtmlTargetElementAttribute("vc:summary")]
public class __Generated__SummaryViewComponentTagHelper : Microsoft.AspNetCore.Razor.TagHelpers.TagHelper
{
private readonly global::Microsoft.AspNetCore.Mvc.IViewComponentHelper __helper = null;
public __Generated__SummaryViewComponentTagHelper(global::Microsoft.AspNetCore.Mvc.IViewComponentHelper helper)
{
__helper = helper;
}
[Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeNotBoundAttribute, global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewContextAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.ViewContext ViewContext { get; set; }
public override async global::System.Threading.Tasks.Task ProcessAsync(Microsoft.AspNetCore.Razor.TagHelpers.TagHelperContext __context, Microsoft.AspNetCore.Razor.TagHelpers.TagHelperOutput __output)
{
(__helper as global::Microsoft.AspNetCore.Mvc.ViewFeatures.IViewContextAware)?.Contextualize(ViewContext);
var __helperContent = await __helper.InvokeAsync("Summary", new { });
__output.TagName = null;
__output.Content.SetHtmlContent(__helperContent);
}
}
}
}
#pragma warning restore 1591
| 70.409357 | 350 | 0.745598 | [
"MIT"
] | RondineleG/HandsWork | src/App/obj/Debug/netcoreapp3.1/Razor/Views/Produtos/Index.cshtml.g.cs | 12,040 | C# |
using Newtonsoft.Json;
namespace PddOpenSdk.Models.Response.WayBill
{
public partial class UpdateWaybillResponseModel : PddResponseModel
{
/// <summary>
/// response
/// </summary>
[JsonProperty("pdd_waybill_update_response")]
public PddWaybillUpdateResponseResponseModel PddWaybillUpdateResponse { get; set; }
public partial class PddWaybillUpdateResponseResponseModel : PddResponseModel
{
/// <summary>
/// 模板内容
/// </summary>
[JsonProperty("print_data")]
public string PrintData { get; set; }
/// <summary>
/// 面单号
/// </summary>
[JsonProperty("waybill_code")]
public string WaybillCode { get; set; }
}
}
}
| 27.896552 | 91 | 0.569839 | [
"Apache-2.0"
] | niltor/open-pdd-net-sdk | PddOpenSdk/PddOpenSdk/Models/Response/WayBill/UpdateWaybillResponseModel.cs | 823 | C# |
using System;
using UnityEngine;
namespace MultiPacMan.Player.Turbo {
public class LocalTurboController : TurboController {
[SerializeField]
private float turboCapacity = 100.0f;
[SerializeField]
private float currentTurboCapacity = 100.0f;
[SerializeField]
private float turboPerSecond = 30.0f;
[SerializeField]
private float turboRecoveryPerSecond = 10.0f;
public delegate bool IsTurboInUse ();
public IsTurboInUse turboDelegate;
void Update () {
if (turboDelegate == null) {
return;
}
if (IsTurboOn ()) {
trail.enabled = true;
} else {
trail.enabled = false;
}
if (turboDelegate ()) {
float turboUsed = (turboPerSecond * Time.deltaTime);
currentTurboCapacity = Mathf.Max (currentTurboCapacity - turboUsed, 0);
} else {
float turboRecovered = (turboRecoveryPerSecond * Time.deltaTime);
currentTurboCapacity = Mathf.Min (currentTurboCapacity + turboRecovered, turboCapacity);
}
}
public override bool IsTurboOn () {
if (turboDelegate == null) {
return false;
}
return turboDelegate () && (currentTurboCapacity > 0);
}
public override float GetTurboFuelPercentage () {
return currentTurboCapacity / turboCapacity;
}
}
} | 30.117647 | 104 | 0.561849 | [
"MIT"
] | carlossdparaujo/MultiPacMan | MultiPacMan/Assets/Scripts/Player/Turbo/LocalTurboController.cs | 1,536 | C# |
using Ionic.Zip;
using RelhaxModpack.Atlases;
using RelhaxModpack.Common;
using RelhaxModpack.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using TeximpNet;
using TeximpNet.Unmanaged;
namespace RelhaxModpack
{
/// <summary>
/// A wrapper class around the TexImpNet NvidiaTT library class.
/// </summary>
/// <remarks>The class handles 32 and 64 bit library loading determination, extraction, and loading into memory.</remarks>
public class RelhaxNvTexLibrary : IRelhaxUnmanagedLibrary
{
private NvTextureToolsLibrary library = NvTextureToolsLibrary.Instance;
/// <summary>
/// Gets the name of the embedded zip file containing the dll, 32 or 64 bit version.
/// </summary>
public string EmbeddedFilename
{
get { return UnmanagedLibrary.Is64Bit ? "nvtt64.zip" : "nvtt32.zip"; }
}
/// <summary>
/// Gets the name of the dll file inside the embedded zip file, 32 or 64bit version.
/// </summary>
public string ExtractedFilename
{
get { return UnmanagedLibrary.Is64Bit ? "nvtt64.dll" : "nvtt32.dll"; }
}
/// <summary>
/// Gets the absolute path to the dll file.
/// </summary>
public string Filepath
{
get { return Path.Combine(ApplicationConstants.RelhaxLibrariesFolderPath, ExtractedFilename); }
}
/// <summary>
/// Determines if the file is extracted to the Filepath property location. Also checks if latest version is extracted.
/// </summary>
public bool IsExtracted
{
get
{
if (!File.Exists(Filepath))
{
Logging.Info("Teximpnet library file does not exist, extracting: {0}", EmbeddedFilename);
return false;
}
Logging.Info("Teximpnet library file exists, checking if latest via Hash comparison not exist, extracting: {0}", EmbeddedFilename);
string extractedHash = FileUtils.CreateMD5Hash(Filepath);
Logging.Debug("{0} hash local: {1}", EmbeddedFilename, extractedHash);
//file exists, but is it up to date?
string embeddedHash = string.Empty;
string resourceName = CommonUtils.GetAssemblyName(EmbeddedFilename);
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
using (ZipFile zout = ZipFile.Read(stream))
using(Stream dllStream = zout[0].OpenReader())
{
embeddedHash = FileUtils.CreateMD5Hash(dllStream);
}
Logging.Debug("{0} hash internal: {1}", EmbeddedFilename, embeddedHash);
return extractedHash.Equals(embeddedHash);
}
}
/// <summary>
/// Determines if the library is loaded into memory.
/// </summary>
public bool IsLoaded
{
get { return library.IsLibraryLoaded; }
}
/// <summary>
/// Attempts to load the library using the Filepath property.
/// </summary>
/// <returns>True if the library load was successful.</returns>
public bool Load()
{
if (!IsExtracted)
Extract();
try
{
return library.LoadLibrary(Filepath);
}
catch (TeximpException ex)
{
Logging.Exception("failed to load native library");
Logging.Exception(ex.ToString());
return false;
}
}
/// <summary>
/// Attempts to unload the library.
/// </summary>
/// <returns>True if the library was unloaded, false otherwise.</returns>
public bool Unload()
{
if (!IsLoaded)
return true;
else
{
return library.FreeLibrary();
}
}
/// <summary>
/// Extracts the embedded compressed library to the location in the Filepath property.
/// </summary>
public void Extract()
{
if (IsExtracted)
{
Logging.Warning("Unmanaged library {0} is already extracted", EmbeddedFilename);
return;
}
if (File.Exists(Filepath))
File.Delete(Filepath);
//https://stackoverflow.com/questions/38381684/reading-zip-file-from-byte-array-using-ionic-zip
string resourceName = CommonUtils.GetAssemblyName(EmbeddedFilename);
Logging.Info("Extracting unmanaged teximpnet library: {0}", EmbeddedFilename);
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
using (ZipFile zout = ZipFile.Read(stream))
{
zout.ExtractAll(ApplicationConstants.RelhaxLibrariesFolderPath);
}
}
}
}
| 35.236486 | 147 | 0.572963 | [
"Apache-2.0"
] | Willster419/RelicModManager | RelhaxModpack/RelhaxModpack/Atlases/RelhaxNvTexLibrary.cs | 5,217 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/MsHTML.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop.Windows;
/// <include file='styleTextSizeAdjust.xml' path='doc/member[@name="styleTextSizeAdjust"]/*' />
public enum styleTextSizeAdjust
{
/// <include file='styleTextSizeAdjust.xml' path='doc/member[@name="styleTextSizeAdjust.styleTextSizeAdjustNone"]/*' />
styleTextSizeAdjustNone = 0,
/// <include file='styleTextSizeAdjust.xml' path='doc/member[@name="styleTextSizeAdjust.styleTextSizeAdjustAuto"]/*' />
styleTextSizeAdjustAuto = 1,
/// <include file='styleTextSizeAdjust.xml' path='doc/member[@name="styleTextSizeAdjust.styleTextSizeAdjust_Max"]/*' />
styleTextSizeAdjust_Max = 2147483647,
}
| 46.75 | 145 | 0.752941 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | sources/Interop/Windows/Windows/um/MsHTML/styleTextSizeAdjust.cs | 937 | C# |
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using Rocket.API;
using Rocket.Core.Assets;
using Rocket.Unturned.Player;
namespace AdminWarnings.Helpers
{
public class WarningLogger
{
private static string filePath = $"{Environment.CurrentDirectory}/Plugins/AdminWarnings/WarningLogs.xml";
public static Asset<WarningLogs> logs = new Asset<WarningLogs>();
public static void Init()
{
logs = new XMLFileAsset<WarningLogs>(filePath);
}
public static void LogWarning(string issuerId, string issuerName, UnturnedPlayer victim, string reason)
{
logs.Instance.entries.Add(new WarningLog
{
AdminId = $"{issuerId} {issuerName}",
VictimId = $"{victim.CSteamID} {victim.DisplayName}",
Reason = reason
});
logs.Save();
}
public static void LogWarning(UnturnedPlayer issuer, UnturnedPlayer victim, string reason)
{
logs.Instance.entries.Add(new WarningLog
{
AdminId = $"{issuer.CSteamID} {issuer.DisplayName}",
VictimId = $"{victim.CSteamID} {victim.DisplayName}",
Reason = reason
});
logs.Save();
}
public static void ClearWarningLogs()
{
logs.Instance.entries.Clear();
logs.Save();
}
}
public class WarningLogs : IDefaultable
{
[XmlArrayItem(ElementName = "Log")]
public List<WarningLog> entries;
public void LoadDefaults()
{
entries = new List<WarningLog>();
}
}
public class WarningLog
{
//[XmlElement("AdminId")]
[XmlAttribute("Admin")]
public string AdminId;
//[XmlElement("VictimId")]
[XmlAttribute("Victim")]
public string VictimId;
[XmlElement("Reason")]
public string Reason;
}
}
| 27.216216 | 113 | 0.573486 | [
"MIT"
] | sharkbound/AdminWarnings | Helpers/WarningLogger.cs | 2,016 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
namespace Microsoft.Data.Entity.Design.UI.ViewModels.PropertyWindow.Descriptors
{
using Microsoft.Data.Entity.Design.Model.Entity;
internal class EFSEntityContainerDescriptor : EFAnnotatableElementDescriptor<StorageEntityContainer>
{
internal override bool IsReadOnlyName()
{
return true;
}
public override string GetComponentName()
{
return TypedEFElement.NormalizedNameExternal;
}
public override string GetClassName()
{
return "StorageEntityContainer";
}
}
}
| 29.4 | 144 | 0.678912 | [
"MIT"
] | dotnet/ef6tools | src/EFTools/EntityDesign/UI/ViewModels/PropertyWindow/Descriptors/EFSEntityContainerDescriptor.cs | 735 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace AlibabaCloud.SDK.ROS.CDK.Cs
{
/// <summary>Properties for defining a `ALIYUN::CS::KubernetesCluster`.</summary>
[JsiiInterface(nativeType: typeof(IRosKubernetesClusterProps), fullyQualifiedName: "@alicloud/ros-cdk-cs.RosKubernetesClusterProps")]
public interface IRosKubernetesClusterProps
{
/// <remarks>
/// <strong>Property</strong>: masterInstanceTypes: Master node ECS specification type code. For more details, see Instance Type Family. Each item correspond to MasterVSwitchIds.
/// List size must be 3, Instance Type can be repeated.
/// </remarks>
[JsiiProperty(name: "masterInstanceTypes", typeJson: "{\"union\":{\"types\":[{\"collection\":{\"elementtype\":{\"primitive\":\"any\"},\"kind\":\"array\"}},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")]
object MasterInstanceTypes
{
get;
}
/// <remarks>
/// <strong>Property</strong>: masterVSwitchIds: Master node switch ID. To ensure high availability of the cluster, it is recommended that you select 3 switches and distribute them in different Availability Zones.
/// </remarks>
[JsiiProperty(name: "masterVSwitchIds", typeJson: "{\"union\":{\"types\":[{\"collection\":{\"elementtype\":{\"primitive\":\"any\"},\"kind\":\"array\"}},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")]
object MasterVSwitchIds
{
get;
}
/// <remarks>
/// <strong>Property</strong>: name: The name of the cluster. The cluster name can use uppercase and lowercase letters, Chinese characters, numbers, and dashes.
/// </remarks>
[JsiiProperty(name: "name", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")]
object Name
{
get;
}
/// <remarks>
/// <strong>Property</strong>: vpcId: VPC ID.
/// </remarks>
[JsiiProperty(name: "vpcId", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")]
object VpcId
{
get;
}
/// <remarks>
/// <strong>Property</strong>: workerInstanceTypes: Worker node ECS specification type code. For more details, see Instance Specification Family.
/// </remarks>
[JsiiProperty(name: "workerInstanceTypes", typeJson: "{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"collection\":{\"elementtype\":{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}},\"kind\":\"array\"}}]}}")]
object WorkerInstanceTypes
{
get;
}
/// <remarks>
/// <strong>Property</strong>: workerVSwitchIds: The virtual switch ID of the worker node.
/// </remarks>
[JsiiProperty(name: "workerVSwitchIds", typeJson: "{\"union\":{\"types\":[{\"collection\":{\"elementtype\":{\"primitive\":\"any\"},\"kind\":\"array\"}},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")]
object WorkerVSwitchIds
{
get;
}
/// <remarks>
/// <strong>Property</strong>: addons: A combination of addon plugins for Kubernetes clusters.
/// Network plug-in: including Flannel and Terway network plug-ins
/// Log service: Optional. If the log service is not enabled, the cluster audit function cannot be used.
/// Ingress: The installation of the Ingress component is enabled by default.
/// </remarks>
[JsiiProperty(name: "addons", typeJson: "{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"collection\":{\"elementtype\":{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"fqn\":\"@alicloud/ros-cdk-cs.RosKubernetesCluster.AddonsProperty\"}]}},\"kind\":\"array\"}}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? Addons
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: cloudMonitorFlags: Whether to install the cloud monitoring plugin:
/// true: indicates installation
/// false: Do not install
/// Default to false
/// </remarks>
[JsiiProperty(name: "cloudMonitorFlags", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? CloudMonitorFlags
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: containerCidr: The container network segment cannot conflict with the VPC network segment. When the sytem is selected to automatically create a VPC, the network segment 172.16.0.0/16 is used by default.
/// </remarks>
[JsiiProperty(name: "containerCidr", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? ContainerCidr
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: cpuPolicy: CPU policy. The cluster version is 1.12.6 and above supports both static and none strategies.
/// </remarks>
[JsiiProperty(name: "cpuPolicy", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? CpuPolicy
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: disableRollback: Whether the failure was rolled back:
/// true: indicates that it fails to roll back
/// false: rollback failed
/// The default is true. If rollback fails, resources produced during the creation process will be released. False is not recommended.
/// </remarks>
[JsiiProperty(name: "disableRollback", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? DisableRollback
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: endpointPublicAccess: Whether to enable the public network API Server:
/// true: which means that the public network API Server is open.
/// false: If set to false, the API server on the public network will not be created, only the API server on the private network will be created.Default to false.
/// </remarks>
[JsiiProperty(name: "endpointPublicAccess", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? EndpointPublicAccess
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: keyPair: Key pair name. Specify one of KeyPair or LoginPassword.
/// </remarks>
[JsiiProperty(name: "keyPair", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? KeyPair
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: kubernetesVersion: The version of the Kubernetes cluster.
/// </remarks>
[JsiiProperty(name: "kubernetesVersion", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? KubernetesVersion
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: loginPassword: SSH login password. Password rules are 8-30 characters and contain three items (upper and lower case letters, numbers, and special symbols). Specify one of KeyPair or LoginPassword.
/// </remarks>
[JsiiProperty(name: "loginPassword", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? LoginPassword
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: masterAutoRenew: Whether the master node automatically renews. It takes effect when the value of MasterInstanceChargeType is PrePaid. The optional values are:
/// true: automatic renewal
/// false: do not renew automatically
/// Default to true.
/// </remarks>
[JsiiProperty(name: "masterAutoRenew", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? MasterAutoRenew
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: masterAutoRenewPeriod: Automatic renewal cycle, which takes effect when prepaid and automatic renewal are selected, and is required:
/// When PeriodUnit = Week, the values are: {"1", "2", "3"}
/// When PeriodUnit = Month, the value is {"1", "2", "3", "6", "12"}
/// Default to 1.
/// </remarks>
[JsiiProperty(name: "masterAutoRenewPeriod", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? MasterAutoRenewPeriod
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: masterCount: Number of master instances. The value can be 3 or 5. The default value is 3.
/// </remarks>
[JsiiProperty(name: "masterCount", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? MasterCount
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: masterDataDisk: Whether the master node mounts data disks can be selected as:
/// true: mount the data disk
/// false: no data disk is mounted, default is false
/// </remarks>
[JsiiProperty(name: "masterDataDisk", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? MasterDataDisk
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: masterDataDisks: Master data disk type, size and other configuration combinations. This parameter is valid only when the master node data disk is mounted.
/// </remarks>
[JsiiProperty(name: "masterDataDisks", typeJson: "{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"collection\":{\"elementtype\":{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"fqn\":\"@alicloud/ros-cdk-cs.RosKubernetesCluster.MasterDataDisksProperty\"}]}},\"kind\":\"array\"}}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? MasterDataDisks
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: masterInstanceChargeType: Master node payment type. The optional values are:
/// PrePaid: prepaid
/// PostPaid: Pay as you go
/// Default to PostPaid.
/// </remarks>
[JsiiProperty(name: "masterInstanceChargeType", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? MasterInstanceChargeType
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: masterPeriod: The duration of the annual subscription and monthly subscription. It takes effect when the master_instance_charge_type value is PrePaid and is a required value. The value range is:
/// When PeriodUnit = Week, Period values are: {"1", "2", "3", "4"}
/// When PeriodUnit = Month, Period values are: {"1", "2", "3", "4", "5", "6", "7", "8", "9", "12", "24", "36", "48", "60"}
/// Default to 1.
/// </remarks>
[JsiiProperty(name: "masterPeriod", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? MasterPeriod
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: masterPeriodUnit: When you specify PrePaid, you need to specify the period. The options are:
/// Week: Time is measured in weeks
/// Month: time in months
/// Default to Month
/// </remarks>
[JsiiProperty(name: "masterPeriodUnit", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? MasterPeriodUnit
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: masterSystemDiskCategory: Master disk system disk type. The value includes:
/// cloud_efficiency: efficient cloud disk
/// cloud_ssd: SSD cloud disk
/// cloud_essd: ESSD cloud diskDefault to cloud_ssd.
/// </remarks>
[JsiiProperty(name: "masterSystemDiskCategory", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? MasterSystemDiskCategory
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: masterSystemDiskSize: Master disk system disk size in GiB.
/// Default to 120.
/// </remarks>
[JsiiProperty(name: "masterSystemDiskSize", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? MasterSystemDiskSize
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: nodePortRange: Node service port. The value range is [30000, 65535].
/// Default to 30000-65535.
/// </remarks>
[JsiiProperty(name: "nodePortRange", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? NodePortRange
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: numOfNodes: Number of worker nodes. The range is [0,300].
/// Default to 3.
/// </remarks>
[JsiiProperty(name: "numOfNodes", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? NumOfNodes
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: podVswitchIds: The list of pod vSwitches. For each vSwitch that is allocated to nodes,
/// you must specify at least one pod vSwitch in the same zone.
/// The pod vSwitches cannot be the same as the node vSwitches.
/// We recommend that you set the mask length of the CIDR block to a value no
/// greater than 19 for the pod vSwitches.
/// The pod_vswitch_ids parameter is required when the Terway network
/// plug-in is selected for the cluster.
/// </remarks>
[JsiiProperty(name: "podVswitchIds", typeJson: "{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"collection\":{\"elementtype\":{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}},\"kind\":\"array\"}}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? PodVswitchIds
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: proxyMode: kube-proxy proxy mode, supports both iptables and ipvs modes. The default is iptables.
/// </remarks>
[JsiiProperty(name: "proxyMode", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? ProxyMode
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: runtime: The container runtime of the cluster. The default runtime is Docker.
/// </remarks>
[JsiiProperty(name: "runtime", typeJson: "{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"fqn\":\"@alicloud/ros-cdk-cs.RosKubernetesCluster.RuntimeProperty\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? Runtime
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: securityGroupId: Specifies the ID of the security group to which the cluster ECS instance belongs.
/// </remarks>
[JsiiProperty(name: "securityGroupId", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? SecurityGroupId
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: serviceCidr: The service network segment cannot conflict with the VPC network segment and the container network segment. When the system is selected to automatically create a VPC, the network segment 172.19.0.0/20 is used by default.
/// </remarks>
[JsiiProperty(name: "serviceCidr", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? ServiceCidr
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: snatEntry: Whether to configure SNAT for the network.
/// When a VPC can access the public network environment, set it to false.
/// When an existing VPC cannot access the public network environment:
/// When set to True, SNAT is configured and the public network environment can be accessed at this time.
/// If set to false, it means that SNAT is not configured and the public network environment cannot be accessed at this time.
/// Default to true.
/// </remarks>
[JsiiProperty(name: "snatEntry", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? SnatEntry
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: sshFlags: Whether to enable public network SSH login:
/// true: open
/// false: not open
/// </remarks>
[JsiiProperty(name: "sshFlags", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? SshFlags
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: tags: Tag the cluster.
/// </remarks>
[JsiiProperty(name: "tags", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"@alicloud/ros-cdk-cs.RosKubernetesCluster.TagsProperty\"},\"kind\":\"array\"}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
AlibabaCloud.SDK.ROS.CDK.Cs.RosKubernetesCluster.ITagsProperty[]? Tags
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: taint: It is used to mark nodes with taints. It is usually used for the scheduling strategy of Pods. The corresponding concept is: tolerance. If there is a corresponding tolerance mark on the Pods, the stain on the node can be tolerated and scheduled to the node.
/// </remarks>
[JsiiProperty(name: "taint", typeJson: "{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"collection\":{\"elementtype\":{\"collection\":{\"elementtype\":{\"primitive\":\"any\"},\"kind\":\"map\"}},\"kind\":\"array\"}}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? Taint
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: timeoutMins: Cluster resource stack creation timeout, in minutes. The default value is 60.
/// </remarks>
[JsiiProperty(name: "timeoutMins", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? TimeoutMins
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: workerAutoRenew: Whether to enable automatic renewal of Worker nodes. The optional values are:
/// true: automatic renewal
/// false: do not renew automatically
/// Default to true.
/// </remarks>
[JsiiProperty(name: "workerAutoRenew", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? WorkerAutoRenew
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: workerAutoRenewPeriod: Automatic renewal cycle, which takes effect when prepaid and automatic renewal are selected, and is required:
/// When PeriodUnit = Week, the values are: {"1", "2", "3"}
/// When PeriodUnit = Month, the value is {"1", "2", "3", "6", "12"}
/// Default to 1.
/// </remarks>
[JsiiProperty(name: "workerAutoRenewPeriod", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? WorkerAutoRenewPeriod
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: workerDataDisk: Whether to mount the data disk. The options are as follows:
/// true: indicates that the worker node mounts data disks.
/// false: indicates that the worker node does not mount data disks.
/// Default to false.
/// </remarks>
[JsiiProperty(name: "workerDataDisk", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? WorkerDataDisk
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: workerDataDisks: A combination of configurations such as worker data disk type and size. This parameter is valid only when the worker node data disk is mounted.
/// </remarks>
[JsiiProperty(name: "workerDataDisks", typeJson: "{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"collection\":{\"elementtype\":{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"fqn\":\"@alicloud/ros-cdk-cs.RosKubernetesCluster.WorkerDataDisksProperty\"}]}},\"kind\":\"array\"}}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? WorkerDataDisks
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: workerInstanceChargeType: Worker node payment type. The optional values are:
/// PrePaid: prepaid
/// PostPaid: Pay as you go
/// Default to PostPaid.
/// </remarks>
[JsiiProperty(name: "workerInstanceChargeType", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? WorkerInstanceChargeType
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: workerPeriod: The duration of the annual and monthly subscription. It takes effect when the worker_instance_charge_type value is PrePaid and is required. The value range is:
/// When PeriodUnit = Week, Period values are: {"1", "2", "3", "4"}
/// When PeriodUnit = Month, Period values are: {"1", "2", "3", "4", "5", "6", "7", "8", "9", "12", "24", "36", "48", "60"}
/// Default to 1.
/// </remarks>
[JsiiProperty(name: "workerPeriod", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? WorkerPeriod
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: workerPeriodUnit: When you specify PrePaid, you need to specify the period. The options are:
/// Week: Time is measured in weeks
/// Month: time in months
/// Default to Month.
/// </remarks>
[JsiiProperty(name: "workerPeriodUnit", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? WorkerPeriodUnit
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: workerSystemDiskCategory: Worker node system disk type. The value includes:
/// cloud_efficiency: efficient cloud disk
/// cloud_ssd: SSD cloud disk
/// Default to cloud_efficiency.
/// </remarks>
[JsiiProperty(name: "workerSystemDiskCategory", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? WorkerSystemDiskCategory
{
get
{
return null;
}
}
/// <remarks>
/// <strong>Property</strong>: workerSystemDiskSize: Worker disk system disk size, the unit is GiB.
/// Default to 120.
/// </remarks>
[JsiiProperty(name: "workerSystemDiskSize", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
object? WorkerSystemDiskSize
{
get
{
return null;
}
}
/// <summary>Properties for defining a `ALIYUN::CS::KubernetesCluster`.</summary>
[JsiiTypeProxy(nativeType: typeof(IRosKubernetesClusterProps), fullyQualifiedName: "@alicloud/ros-cdk-cs.RosKubernetesClusterProps")]
internal sealed class _Proxy : DeputyBase, AlibabaCloud.SDK.ROS.CDK.Cs.IRosKubernetesClusterProps
{
private _Proxy(ByRefValue reference): base(reference)
{
}
/// <remarks>
/// <strong>Property</strong>: masterInstanceTypes: Master node ECS specification type code. For more details, see Instance Type Family. Each item correspond to MasterVSwitchIds.
/// List size must be 3, Instance Type can be repeated.
/// </remarks>
[JsiiProperty(name: "masterInstanceTypes", typeJson: "{\"union\":{\"types\":[{\"collection\":{\"elementtype\":{\"primitive\":\"any\"},\"kind\":\"array\"}},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")]
public object MasterInstanceTypes
{
get => GetInstanceProperty<object>()!;
}
/// <remarks>
/// <strong>Property</strong>: masterVSwitchIds: Master node switch ID. To ensure high availability of the cluster, it is recommended that you select 3 switches and distribute them in different Availability Zones.
/// </remarks>
[JsiiProperty(name: "masterVSwitchIds", typeJson: "{\"union\":{\"types\":[{\"collection\":{\"elementtype\":{\"primitive\":\"any\"},\"kind\":\"array\"}},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")]
public object MasterVSwitchIds
{
get => GetInstanceProperty<object>()!;
}
/// <remarks>
/// <strong>Property</strong>: name: The name of the cluster. The cluster name can use uppercase and lowercase letters, Chinese characters, numbers, and dashes.
/// </remarks>
[JsiiProperty(name: "name", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")]
public object Name
{
get => GetInstanceProperty<object>()!;
}
/// <remarks>
/// <strong>Property</strong>: vpcId: VPC ID.
/// </remarks>
[JsiiProperty(name: "vpcId", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")]
public object VpcId
{
get => GetInstanceProperty<object>()!;
}
/// <remarks>
/// <strong>Property</strong>: workerInstanceTypes: Worker node ECS specification type code. For more details, see Instance Specification Family.
/// </remarks>
[JsiiProperty(name: "workerInstanceTypes", typeJson: "{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"collection\":{\"elementtype\":{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}},\"kind\":\"array\"}}]}}")]
public object WorkerInstanceTypes
{
get => GetInstanceProperty<object>()!;
}
/// <remarks>
/// <strong>Property</strong>: workerVSwitchIds: The virtual switch ID of the worker node.
/// </remarks>
[JsiiProperty(name: "workerVSwitchIds", typeJson: "{\"union\":{\"types\":[{\"collection\":{\"elementtype\":{\"primitive\":\"any\"},\"kind\":\"array\"}},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")]
public object WorkerVSwitchIds
{
get => GetInstanceProperty<object>()!;
}
/// <remarks>
/// <strong>Property</strong>: addons: A combination of addon plugins for Kubernetes clusters.
/// Network plug-in: including Flannel and Terway network plug-ins
/// Log service: Optional. If the log service is not enabled, the cluster audit function cannot be used.
/// Ingress: The installation of the Ingress component is enabled by default.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "addons", typeJson: "{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"collection\":{\"elementtype\":{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"fqn\":\"@alicloud/ros-cdk-cs.RosKubernetesCluster.AddonsProperty\"}]}},\"kind\":\"array\"}}]}}", isOptional: true)]
public object? Addons
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: cloudMonitorFlags: Whether to install the cloud monitoring plugin:
/// true: indicates installation
/// false: Do not install
/// Default to false
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "cloudMonitorFlags", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? CloudMonitorFlags
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: containerCidr: The container network segment cannot conflict with the VPC network segment. When the sytem is selected to automatically create a VPC, the network segment 172.16.0.0/16 is used by default.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "containerCidr", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? ContainerCidr
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: cpuPolicy: CPU policy. The cluster version is 1.12.6 and above supports both static and none strategies.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "cpuPolicy", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? CpuPolicy
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: disableRollback: Whether the failure was rolled back:
/// true: indicates that it fails to roll back
/// false: rollback failed
/// The default is true. If rollback fails, resources produced during the creation process will be released. False is not recommended.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "disableRollback", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? DisableRollback
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: endpointPublicAccess: Whether to enable the public network API Server:
/// true: which means that the public network API Server is open.
/// false: If set to false, the API server on the public network will not be created, only the API server on the private network will be created.Default to false.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "endpointPublicAccess", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? EndpointPublicAccess
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: keyPair: Key pair name. Specify one of KeyPair or LoginPassword.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "keyPair", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? KeyPair
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: kubernetesVersion: The version of the Kubernetes cluster.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "kubernetesVersion", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? KubernetesVersion
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: loginPassword: SSH login password. Password rules are 8-30 characters and contain three items (upper and lower case letters, numbers, and special symbols). Specify one of KeyPair or LoginPassword.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "loginPassword", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? LoginPassword
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: masterAutoRenew: Whether the master node automatically renews. It takes effect when the value of MasterInstanceChargeType is PrePaid. The optional values are:
/// true: automatic renewal
/// false: do not renew automatically
/// Default to true.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "masterAutoRenew", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? MasterAutoRenew
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: masterAutoRenewPeriod: Automatic renewal cycle, which takes effect when prepaid and automatic renewal are selected, and is required:
/// When PeriodUnit = Week, the values are: {"1", "2", "3"}
/// When PeriodUnit = Month, the value is {"1", "2", "3", "6", "12"}
/// Default to 1.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "masterAutoRenewPeriod", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? MasterAutoRenewPeriod
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: masterCount: Number of master instances. The value can be 3 or 5. The default value is 3.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "masterCount", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? MasterCount
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: masterDataDisk: Whether the master node mounts data disks can be selected as:
/// true: mount the data disk
/// false: no data disk is mounted, default is false
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "masterDataDisk", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? MasterDataDisk
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: masterDataDisks: Master data disk type, size and other configuration combinations. This parameter is valid only when the master node data disk is mounted.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "masterDataDisks", typeJson: "{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"collection\":{\"elementtype\":{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"fqn\":\"@alicloud/ros-cdk-cs.RosKubernetesCluster.MasterDataDisksProperty\"}]}},\"kind\":\"array\"}}]}}", isOptional: true)]
public object? MasterDataDisks
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: masterInstanceChargeType: Master node payment type. The optional values are:
/// PrePaid: prepaid
/// PostPaid: Pay as you go
/// Default to PostPaid.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "masterInstanceChargeType", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? MasterInstanceChargeType
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: masterPeriod: The duration of the annual subscription and monthly subscription. It takes effect when the master_instance_charge_type value is PrePaid and is a required value. The value range is:
/// When PeriodUnit = Week, Period values are: {"1", "2", "3", "4"}
/// When PeriodUnit = Month, Period values are: {"1", "2", "3", "4", "5", "6", "7", "8", "9", "12", "24", "36", "48", "60"}
/// Default to 1.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "masterPeriod", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? MasterPeriod
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: masterPeriodUnit: When you specify PrePaid, you need to specify the period. The options are:
/// Week: Time is measured in weeks
/// Month: time in months
/// Default to Month
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "masterPeriodUnit", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? MasterPeriodUnit
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: masterSystemDiskCategory: Master disk system disk type. The value includes:
/// cloud_efficiency: efficient cloud disk
/// cloud_ssd: SSD cloud disk
/// cloud_essd: ESSD cloud diskDefault to cloud_ssd.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "masterSystemDiskCategory", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? MasterSystemDiskCategory
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: masterSystemDiskSize: Master disk system disk size in GiB.
/// Default to 120.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "masterSystemDiskSize", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? MasterSystemDiskSize
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: nodePortRange: Node service port. The value range is [30000, 65535].
/// Default to 30000-65535.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "nodePortRange", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? NodePortRange
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: numOfNodes: Number of worker nodes. The range is [0,300].
/// Default to 3.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "numOfNodes", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? NumOfNodes
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: podVswitchIds: The list of pod vSwitches. For each vSwitch that is allocated to nodes,
/// you must specify at least one pod vSwitch in the same zone.
/// The pod vSwitches cannot be the same as the node vSwitches.
/// We recommend that you set the mask length of the CIDR block to a value no
/// greater than 19 for the pod vSwitches.
/// The pod_vswitch_ids parameter is required when the Terway network
/// plug-in is selected for the cluster.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "podVswitchIds", typeJson: "{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"collection\":{\"elementtype\":{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}},\"kind\":\"array\"}}]}}", isOptional: true)]
public object? PodVswitchIds
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: proxyMode: kube-proxy proxy mode, supports both iptables and ipvs modes. The default is iptables.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "proxyMode", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? ProxyMode
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: runtime: The container runtime of the cluster. The default runtime is Docker.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "runtime", typeJson: "{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"fqn\":\"@alicloud/ros-cdk-cs.RosKubernetesCluster.RuntimeProperty\"}]}}", isOptional: true)]
public object? Runtime
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: securityGroupId: Specifies the ID of the security group to which the cluster ECS instance belongs.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "securityGroupId", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? SecurityGroupId
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: serviceCidr: The service network segment cannot conflict with the VPC network segment and the container network segment. When the system is selected to automatically create a VPC, the network segment 172.19.0.0/20 is used by default.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "serviceCidr", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? ServiceCidr
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: snatEntry: Whether to configure SNAT for the network.
/// When a VPC can access the public network environment, set it to false.
/// When an existing VPC cannot access the public network environment:
/// When set to True, SNAT is configured and the public network environment can be accessed at this time.
/// If set to false, it means that SNAT is not configured and the public network environment cannot be accessed at this time.
/// Default to true.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "snatEntry", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? SnatEntry
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: sshFlags: Whether to enable public network SSH login:
/// true: open
/// false: not open
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "sshFlags", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? SshFlags
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: tags: Tag the cluster.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "tags", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"@alicloud/ros-cdk-cs.RosKubernetesCluster.TagsProperty\"},\"kind\":\"array\"}}", isOptional: true)]
public AlibabaCloud.SDK.ROS.CDK.Cs.RosKubernetesCluster.ITagsProperty[]? Tags
{
get => GetInstanceProperty<AlibabaCloud.SDK.ROS.CDK.Cs.RosKubernetesCluster.ITagsProperty[]?>();
}
/// <remarks>
/// <strong>Property</strong>: taint: It is used to mark nodes with taints. It is usually used for the scheduling strategy of Pods. The corresponding concept is: tolerance. If there is a corresponding tolerance mark on the Pods, the stain on the node can be tolerated and scheduled to the node.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "taint", typeJson: "{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"collection\":{\"elementtype\":{\"collection\":{\"elementtype\":{\"primitive\":\"any\"},\"kind\":\"map\"}},\"kind\":\"array\"}}]}}", isOptional: true)]
public object? Taint
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: timeoutMins: Cluster resource stack creation timeout, in minutes. The default value is 60.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "timeoutMins", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? TimeoutMins
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: workerAutoRenew: Whether to enable automatic renewal of Worker nodes. The optional values are:
/// true: automatic renewal
/// false: do not renew automatically
/// Default to true.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "workerAutoRenew", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? WorkerAutoRenew
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: workerAutoRenewPeriod: Automatic renewal cycle, which takes effect when prepaid and automatic renewal are selected, and is required:
/// When PeriodUnit = Week, the values are: {"1", "2", "3"}
/// When PeriodUnit = Month, the value is {"1", "2", "3", "6", "12"}
/// Default to 1.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "workerAutoRenewPeriod", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? WorkerAutoRenewPeriod
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: workerDataDisk: Whether to mount the data disk. The options are as follows:
/// true: indicates that the worker node mounts data disks.
/// false: indicates that the worker node does not mount data disks.
/// Default to false.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "workerDataDisk", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? WorkerDataDisk
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: workerDataDisks: A combination of configurations such as worker data disk type and size. This parameter is valid only when the worker node data disk is mounted.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "workerDataDisks", typeJson: "{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"collection\":{\"elementtype\":{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"fqn\":\"@alicloud/ros-cdk-cs.RosKubernetesCluster.WorkerDataDisksProperty\"}]}},\"kind\":\"array\"}}]}}", isOptional: true)]
public object? WorkerDataDisks
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: workerInstanceChargeType: Worker node payment type. The optional values are:
/// PrePaid: prepaid
/// PostPaid: Pay as you go
/// Default to PostPaid.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "workerInstanceChargeType", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? WorkerInstanceChargeType
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: workerPeriod: The duration of the annual and monthly subscription. It takes effect when the worker_instance_charge_type value is PrePaid and is required. The value range is:
/// When PeriodUnit = Week, Period values are: {"1", "2", "3", "4"}
/// When PeriodUnit = Month, Period values are: {"1", "2", "3", "4", "5", "6", "7", "8", "9", "12", "24", "36", "48", "60"}
/// Default to 1.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "workerPeriod", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? WorkerPeriod
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: workerPeriodUnit: When you specify PrePaid, you need to specify the period. The options are:
/// Week: Time is measured in weeks
/// Month: time in months
/// Default to Month.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "workerPeriodUnit", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? WorkerPeriodUnit
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: workerSystemDiskCategory: Worker node system disk type. The value includes:
/// cloud_efficiency: efficient cloud disk
/// cloud_ssd: SSD cloud disk
/// Default to cloud_efficiency.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "workerSystemDiskCategory", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? WorkerSystemDiskCategory
{
get => GetInstanceProperty<object?>();
}
/// <remarks>
/// <strong>Property</strong>: workerSystemDiskSize: Worker disk system disk size, the unit is GiB.
/// Default to 120.
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "workerSystemDiskSize", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)]
public object? WorkerSystemDiskSize
{
get => GetInstanceProperty<object?>();
}
}
}
}
| 50.582843 | 366 | 0.55654 | [
"Apache-2.0"
] | aliyun/Resource-Orchestration-Service-Cloud-Development-K | multiple-languages/dotnet/AlibabaCloud.SDK.ROS.CDK.Cs/AlibabaCloud/SDK/ROS/CDK/Cs/IRosKubernetesClusterProps.cs | 60,143 | C# |
using System;
using System.Reflection.Emit;
namespace FluentMethods.UnitTests
{
public partial class ILGeneratorFixture
{
#if NetCore
[Xunit.Fact]
#else
[NUnit.Framework.Test]
#endif
public void BranchIfTrue()
{
var method = new DynamicMethod("x", typeof(bool), new[] { typeof(bool) });
var il = method.GetILGenerator();
var elseLabel = il.DefineLabel();
var endLabel = il.DefineLabel();
il.Emit(OpCodes.Ldarg_0);
il.BranchTo(elseLabel).IfTrue();
il.LoadConst(false);
il.Emit(OpCodes.Br, endLabel);
il.MarkLabel(elseLabel);
il.LoadConst(true);
il.MarkLabel(endLabel);
il.Emit(OpCodes.Ret);
var func = (Func<bool, bool>)method.CreateDelegate(typeof(Func<bool, bool>));
Assert.True(func(true));
Assert.False(func(false));
}
#if NetCore
[Xunit.Fact]
#else
[NUnit.Framework.Test]
#endif
public void BranchIfTrueShortForm()
{
var method = new DynamicMethod("x", typeof(bool), new[] { typeof(bool) });
var il = method.GetILGenerator();
var elseLabel = il.DefineLabel();
var endLabel = il.DefineLabel();
il.Emit(OpCodes.Ldarg_0);
il.BranchShortTo(elseLabel).IfTrue();
il.LoadConst(false);
il.Emit(OpCodes.Br, endLabel);
il.MarkLabel(elseLabel);
il.LoadConst(true);
il.MarkLabel(endLabel);
il.Emit(OpCodes.Ret);
var func = (Func<bool, bool>)method.CreateDelegate(typeof(Func<bool, bool>));
Assert.True(func(true));
Assert.False(func(false));
}
}
}
| 31.440678 | 90 | 0.536388 | [
"MIT"
] | edwardmeng/FluentMethods | test/Core/System.Reflection.Emit.ILGenerator/Branch/IfTrue.cs | 1,857 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace aws
{
#pragma warning disable CS8618
[JsiiByValue(fqn: "aws.CloudformationStackSetInstanceConfig")]
public class CloudformationStackSetInstanceConfig : aws.ICloudformationStackSetInstanceConfig
{
[JsiiProperty(name: "stackSetName", typeJson: "{\"primitive\":\"string\"}", isOverride: true)]
public string StackSetName
{
get;
set;
}
[JsiiOptional]
[JsiiProperty(name: "accountId", typeJson: "{\"primitive\":\"string\"}", isOptional: true, isOverride: true)]
public string? AccountId
{
get;
set;
}
[JsiiOptional]
[JsiiProperty(name: "parameterOverrides", typeJson: "{\"collection\":{\"elementtype\":{\"primitive\":\"string\"},\"kind\":\"map\"}}", isOptional: true, isOverride: true)]
public System.Collections.Generic.IDictionary<string, string>? ParameterOverrides
{
get;
set;
}
[JsiiOptional]
[JsiiProperty(name: "region", typeJson: "{\"primitive\":\"string\"}", isOptional: true, isOverride: true)]
public string? Region
{
get;
set;
}
[JsiiOptional]
[JsiiProperty(name: "retainStack", typeJson: "{\"primitive\":\"boolean\"}", isOptional: true, isOverride: true)]
public bool? RetainStack
{
get;
set;
}
/// <summary>timeouts block.</summary>
[JsiiOptional]
[JsiiProperty(name: "timeouts", typeJson: "{\"fqn\":\"aws.CloudformationStackSetInstanceTimeouts\"}", isOptional: true, isOverride: true)]
public aws.ICloudformationStackSetInstanceTimeouts? Timeouts
{
get;
set;
}
/// <remarks>
/// <strong>Stability</strong>: Experimental
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "count", typeJson: "{\"primitive\":\"number\"}", isOptional: true, isOverride: true)]
public double? Count
{
get;
set;
}
/// <remarks>
/// <strong>Stability</strong>: Experimental
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "dependsOn", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"cdktf.ITerraformDependable\"},\"kind\":\"array\"}}", isOptional: true, isOverride: true)]
public HashiCorp.Cdktf.ITerraformDependable[]? DependsOn
{
get;
set;
}
/// <remarks>
/// <strong>Stability</strong>: Experimental
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "lifecycle", typeJson: "{\"fqn\":\"cdktf.TerraformResourceLifecycle\"}", isOptional: true, isOverride: true)]
public HashiCorp.Cdktf.ITerraformResourceLifecycle? Lifecycle
{
get;
set;
}
/// <remarks>
/// <strong>Stability</strong>: Experimental
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "provider", typeJson: "{\"fqn\":\"cdktf.TerraformProvider\"}", isOptional: true, isOverride: true)]
public HashiCorp.Cdktf.TerraformProvider? Provider
{
get;
set;
}
}
}
| 32.085714 | 185 | 0.55981 | [
"MIT"
] | scottenriquez/cdktf-alpha-csharp-testing | resources/.gen/aws/aws/CloudformationStackSetInstanceConfig.cs | 3,369 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using PropertyDataMut = Microsoft.PowerShell.CrossCompatibility.Data.Types.PropertyData;
namespace Microsoft.PowerShell.CrossCompatibility.Query
{
/// <summary>
/// Readonly query object for a property member on a .NET type.
/// </summary>
public class PropertyData
{
private readonly PropertyDataMut _propertyData;
/// <summary>
/// Create a new query object around collected .NET property data.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="propertyData">Collected property data.</param>
public PropertyData(string name, PropertyDataMut propertyData)
{
Name = name;
_propertyData = propertyData;
}
/// <summary>
/// The name of the property.
/// </summary>
public string Name { get; }
/// <summary>
/// The full name of the type of the property.
/// </summary>
public string Type => _propertyData.Type;
/// <summary>
/// List of the available accessors (get, set) on the property.
/// </summary>
public IReadOnlyList<AccessorType> Accessors => _propertyData.Accessors;
}
}
| 31.860465 | 88 | 0.621168 | [
"MIT"
] | ConnectionMaster/PSScriptAnalyzer | PSCompatibilityAnalyzer/Microsoft.PowerShell.CrossCompatibility/Query/Types/PropertyData.cs | 1,370 | C# |
using System;
using System.Xml.Serialization;
using Top.Api.Domain;
namespace Top.Api.Response
{
/// <summary>
/// DdMenuDetailResponse.
/// </summary>
public class DdMenuDetailResponse : TopResponse
{
/// <summary>
/// 点菜单订单详情
/// </summary>
[XmlElement("result")]
public DdTopMenuDetailVO Result { get; set; }
}
}
| 20.052632 | 53 | 0.593176 | [
"MIT"
] | objectyan/MyTools | OY.Solution/OY.TopSdk/Response/DdMenuDetailResponse.cs | 395 | C# |
namespace Orchard.ContentManagement.Handlers {
public class InitializingContentContext {
public string ContentType { get; set; }
public ContentItem ContentItem { get; set; }
}
} | 33.666667 | 52 | 0.69802 | [
"BSD-3-Clause"
] | 1996dylanriley/Orchard | src/Orchard/ContentManagement/Handlers/InitializingContentContext.cs | 204 | C# |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
namespace Microsoft.Scripting.Runtime {
/// <summary>
/// Implements explicit casts supported by the runtime.
/// </summary>
[GeneratedCode("DLR", "2.0")]
public static partial class Cast {
#region Generated Type Casts
// *** BEGIN GENERATED CODE ***
// generated by function: generate_type_casts from: generate_casts.py
public static Boolean ExplicitCastToBoolean(object o) {
if (o != null) {
Type type = o.GetType();
if (type == BooleanType) {
return (Boolean)(Boolean)o;
} else if (type == NullableBooleanType) {
return (Boolean)(Nullable<Boolean>)o;
}
}
throw InvalidCast(o, "Boolean");
}
public static Byte ExplicitCastToByte(object o) {
if (o != null) {
Type type = o.GetType();
if (type == Int32Type) {
return (Byte)(Int32)o;
} else if (type == DoubleType) {
return (Byte)(Double)o;
} else if (type == Int64Type) {
return (Byte)(Int64)o;
} else if (type == Int16Type) {
return (Byte)(Int16)o;
} else if (type == UInt32Type) {
return (Byte)(UInt32)o;
} else if (type == UInt64Type) {
return (Byte)(UInt64)o;
} else if (type == UInt16Type) {
return (Byte)(UInt16)o;
} else if (type == SByteType) {
return (Byte)(SByte)o;
} else if (type == ByteType) {
return (Byte)(Byte)o;
} else if (type == SingleType) {
return (Byte)(Single)o;
} else if (type == CharType) {
return (Byte)(Char)o;
} else if (type == DecimalType) {
return (Byte)(Decimal)o;
} else if (type.IsEnum) {
return (Byte)ExplicitCastEnumToByte(o);
} else if (type == NullableInt32Type) {
return (Byte)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (Byte)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (Byte)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (Byte)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (Byte)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (Byte)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (Byte)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (Byte)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (Byte)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (Byte)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (Byte)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (Byte)(Nullable<Decimal>)o;
}
}
throw InvalidCast(o, "Byte");
}
public static Char ExplicitCastToChar(object o) {
if (o != null) {
Type type = o.GetType();
if (type == Int32Type) {
return (Char)(Int32)o;
} else if (type == DoubleType) {
return (Char)(Double)o;
} else if (type == Int64Type) {
return (Char)(Int64)o;
} else if (type == Int16Type) {
return (Char)(Int16)o;
} else if (type == UInt32Type) {
return (Char)(UInt32)o;
} else if (type == UInt64Type) {
return (Char)(UInt64)o;
} else if (type == UInt16Type) {
return (Char)(UInt16)o;
} else if (type == SByteType) {
return (Char)(SByte)o;
} else if (type == ByteType) {
return (Char)(Byte)o;
} else if (type == SingleType) {
return (Char)(Single)o;
} else if (type == CharType) {
return (Char)(Char)o;
} else if (type == DecimalType) {
return (Char)(Decimal)o;
} else if (type.IsEnum) {
return (Char)ExplicitCastEnumToInt32(o);
} else if (type == NullableInt32Type) {
return (Char)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (Char)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (Char)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (Char)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (Char)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (Char)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (Char)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (Char)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (Char)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (Char)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (Char)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (Char)(Nullable<Decimal>)o;
}
}
throw InvalidCast(o, "Char");
}
public static Decimal ExplicitCastToDecimal(object o) {
if (o != null) {
Type type = o.GetType();
if (type == Int32Type) {
return (Decimal)(Int32)o;
} else if (type == DoubleType) {
return (Decimal)(Double)o;
} else if (type == Int64Type) {
return (Decimal)(Int64)o;
} else if (type == Int16Type) {
return (Decimal)(Int16)o;
} else if (type == UInt32Type) {
return (Decimal)(UInt32)o;
} else if (type == UInt64Type) {
return (Decimal)(UInt64)o;
} else if (type == UInt16Type) {
return (Decimal)(UInt16)o;
} else if (type == SByteType) {
return (Decimal)(SByte)o;
} else if (type == ByteType) {
return (Decimal)(Byte)o;
} else if (type == SingleType) {
return (Decimal)(Single)o;
} else if (type == CharType) {
return (Decimal)(Char)o;
} else if (type == DecimalType) {
return (Decimal)(Decimal)o;
} else if (type.IsEnum) {
return (Decimal)ExplicitCastEnumToInt64(o);
} else if (type == NullableInt32Type) {
return (Decimal)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (Decimal)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (Decimal)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (Decimal)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (Decimal)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (Decimal)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (Decimal)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (Decimal)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (Decimal)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (Decimal)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (Decimal)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (Decimal)(Nullable<Decimal>)o;
}
}
throw InvalidCast(o, "Decimal");
}
public static Double ExplicitCastToDouble(object o) {
if (o != null) {
Type type = o.GetType();
if (type == Int32Type) {
return (Double)(Int32)o;
} else if (type == DoubleType) {
return (Double)(Double)o;
} else if (type == Int64Type) {
return (Double)(Int64)o;
} else if (type == Int16Type) {
return (Double)(Int16)o;
} else if (type == UInt32Type) {
return (Double)(UInt32)o;
} else if (type == UInt64Type) {
return (Double)(UInt64)o;
} else if (type == UInt16Type) {
return (Double)(UInt16)o;
} else if (type == SByteType) {
return (Double)(SByte)o;
} else if (type == ByteType) {
return (Double)(Byte)o;
} else if (type == SingleType) {
return (Double)(Single)o;
} else if (type == CharType) {
return (Double)(Char)o;
} else if (type == DecimalType) {
return (Double)(Decimal)o;
} else if (type.IsEnum) {
return (Double)ExplicitCastEnumToInt64(o);
} else if (type == NullableInt32Type) {
return (Double)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (Double)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (Double)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (Double)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (Double)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (Double)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (Double)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (Double)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (Double)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (Double)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (Double)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (Double)(Nullable<Decimal>)o;
}
}
throw InvalidCast(o, "Double");
}
public static Int16 ExplicitCastToInt16(object o) {
if (o != null) {
Type type = o.GetType();
if (type == Int32Type) {
return (Int16)(Int32)o;
} else if (type == DoubleType) {
return (Int16)(Double)o;
} else if (type == Int64Type) {
return (Int16)(Int64)o;
} else if (type == Int16Type) {
return (Int16)(Int16)o;
} else if (type == UInt32Type) {
return (Int16)(UInt32)o;
} else if (type == UInt64Type) {
return (Int16)(UInt64)o;
} else if (type == UInt16Type) {
return (Int16)(UInt16)o;
} else if (type == SByteType) {
return (Int16)(SByte)o;
} else if (type == ByteType) {
return (Int16)(Byte)o;
} else if (type == SingleType) {
return (Int16)(Single)o;
} else if (type == CharType) {
return (Int16)(Char)o;
} else if (type == DecimalType) {
return (Int16)(Decimal)o;
} else if (type.IsEnum) {
return (Int16)ExplicitCastEnumToInt16(o);
} else if (type == NullableInt32Type) {
return (Int16)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (Int16)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (Int16)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (Int16)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (Int16)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (Int16)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (Int16)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (Int16)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (Int16)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (Int16)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (Int16)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (Int16)(Nullable<Decimal>)o;
}
}
throw InvalidCast(o, "Int16");
}
public static Int32 ExplicitCastToInt32(object o) {
if (o != null) {
Type type = o.GetType();
if (type == Int32Type) {
return (Int32)(Int32)o;
} else if (type == DoubleType) {
return (Int32)(Double)o;
} else if (type == Int64Type) {
return (Int32)(Int64)o;
} else if (type == Int16Type) {
return (Int32)(Int16)o;
} else if (type == UInt32Type) {
return (Int32)(UInt32)o;
} else if (type == UInt64Type) {
return (Int32)(UInt64)o;
} else if (type == UInt16Type) {
return (Int32)(UInt16)o;
} else if (type == SByteType) {
return (Int32)(SByte)o;
} else if (type == ByteType) {
return (Int32)(Byte)o;
} else if (type == SingleType) {
return (Int32)(Single)o;
} else if (type == CharType) {
return (Int32)(Char)o;
} else if (type == DecimalType) {
return (Int32)(Decimal)o;
} else if (type.IsEnum) {
return (Int32)ExplicitCastEnumToInt32(o);
} else if (type == NullableInt32Type) {
return (Int32)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (Int32)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (Int32)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (Int32)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (Int32)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (Int32)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (Int32)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (Int32)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (Int32)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (Int32)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (Int32)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (Int32)(Nullable<Decimal>)o;
}
}
throw InvalidCast(o, "Int32");
}
public static Int64 ExplicitCastToInt64(object o) {
if (o != null) {
Type type = o.GetType();
if (type == Int32Type) {
return (Int64)(Int32)o;
} else if (type == DoubleType) {
return (Int64)(Double)o;
} else if (type == Int64Type) {
return (Int64)(Int64)o;
} else if (type == Int16Type) {
return (Int64)(Int16)o;
} else if (type == UInt32Type) {
return (Int64)(UInt32)o;
} else if (type == UInt64Type) {
return (Int64)(UInt64)o;
} else if (type == UInt16Type) {
return (Int64)(UInt16)o;
} else if (type == SByteType) {
return (Int64)(SByte)o;
} else if (type == ByteType) {
return (Int64)(Byte)o;
} else if (type == SingleType) {
return (Int64)(Single)o;
} else if (type == CharType) {
return (Int64)(Char)o;
} else if (type == DecimalType) {
return (Int64)(Decimal)o;
} else if (type.IsEnum) {
return (Int64)ExplicitCastEnumToInt64(o);
} else if (type == NullableInt32Type) {
return (Int64)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (Int64)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (Int64)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (Int64)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (Int64)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (Int64)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (Int64)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (Int64)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (Int64)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (Int64)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (Int64)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (Int64)(Nullable<Decimal>)o;
}
}
throw InvalidCast(o, "Int64");
}
[CLSCompliant(false)]
public static SByte ExplicitCastToSByte(object o) {
if (o != null) {
Type type = o.GetType();
if (type == Int32Type) {
return (SByte)(Int32)o;
} else if (type == DoubleType) {
return (SByte)(Double)o;
} else if (type == Int64Type) {
return (SByte)(Int64)o;
} else if (type == Int16Type) {
return (SByte)(Int16)o;
} else if (type == UInt32Type) {
return (SByte)(UInt32)o;
} else if (type == UInt64Type) {
return (SByte)(UInt64)o;
} else if (type == UInt16Type) {
return (SByte)(UInt16)o;
} else if (type == SByteType) {
return (SByte)(SByte)o;
} else if (type == ByteType) {
return (SByte)(Byte)o;
} else if (type == SingleType) {
return (SByte)(Single)o;
} else if (type == CharType) {
return (SByte)(Char)o;
} else if (type == DecimalType) {
return (SByte)(Decimal)o;
} else if (type.IsEnum) {
return (SByte)ExplicitCastEnumToSByte(o);
} else if (type == NullableInt32Type) {
return (SByte)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (SByte)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (SByte)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (SByte)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (SByte)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (SByte)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (SByte)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (SByte)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (SByte)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (SByte)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (SByte)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (SByte)(Nullable<Decimal>)o;
}
}
throw InvalidCast(o, "SByte");
}
public static Single ExplicitCastToSingle(object o) {
if (o != null) {
Type type = o.GetType();
if (type == Int32Type) {
return (Single)(Int32)o;
} else if (type == DoubleType) {
return (Single)(Double)o;
} else if (type == Int64Type) {
return (Single)(Int64)o;
} else if (type == Int16Type) {
return (Single)(Int16)o;
} else if (type == UInt32Type) {
return (Single)(UInt32)o;
} else if (type == UInt64Type) {
return (Single)(UInt64)o;
} else if (type == UInt16Type) {
return (Single)(UInt16)o;
} else if (type == SByteType) {
return (Single)(SByte)o;
} else if (type == ByteType) {
return (Single)(Byte)o;
} else if (type == SingleType) {
return (Single)(Single)o;
} else if (type == CharType) {
return (Single)(Char)o;
} else if (type == DecimalType) {
return (Single)(Decimal)o;
} else if (type.IsEnum) {
return (Single)ExplicitCastEnumToInt64(o);
} else if (type == NullableInt32Type) {
return (Single)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (Single)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (Single)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (Single)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (Single)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (Single)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (Single)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (Single)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (Single)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (Single)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (Single)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (Single)(Nullable<Decimal>)o;
}
}
throw InvalidCast(o, "Single");
}
[CLSCompliant(false)]
public static UInt16 ExplicitCastToUInt16(object o) {
if (o != null) {
Type type = o.GetType();
if (type == Int32Type) {
return (UInt16)(Int32)o;
} else if (type == DoubleType) {
return (UInt16)(Double)o;
} else if (type == Int64Type) {
return (UInt16)(Int64)o;
} else if (type == Int16Type) {
return (UInt16)(Int16)o;
} else if (type == UInt32Type) {
return (UInt16)(UInt32)o;
} else if (type == UInt64Type) {
return (UInt16)(UInt64)o;
} else if (type == UInt16Type) {
return (UInt16)(UInt16)o;
} else if (type == SByteType) {
return (UInt16)(SByte)o;
} else if (type == ByteType) {
return (UInt16)(Byte)o;
} else if (type == SingleType) {
return (UInt16)(Single)o;
} else if (type == CharType) {
return (UInt16)(Char)o;
} else if (type == DecimalType) {
return (UInt16)(Decimal)o;
} else if (type.IsEnum) {
return (UInt16)ExplicitCastEnumToUInt16(o);
} else if (type == NullableInt32Type) {
return (UInt16)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (UInt16)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (UInt16)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (UInt16)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (UInt16)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (UInt16)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (UInt16)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (UInt16)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (UInt16)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (UInt16)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (UInt16)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (UInt16)(Nullable<Decimal>)o;
}
}
throw InvalidCast(o, "UInt16");
}
[CLSCompliant(false)]
public static UInt32 ExplicitCastToUInt32(object o) {
if (o != null) {
Type type = o.GetType();
if (type == Int32Type) {
return (UInt32)(Int32)o;
} else if (type == DoubleType) {
return (UInt32)(Double)o;
} else if (type == Int64Type) {
return (UInt32)(Int64)o;
} else if (type == Int16Type) {
return (UInt32)(Int16)o;
} else if (type == UInt32Type) {
return (UInt32)(UInt32)o;
} else if (type == UInt64Type) {
return (UInt32)(UInt64)o;
} else if (type == UInt16Type) {
return (UInt32)(UInt16)o;
} else if (type == SByteType) {
return (UInt32)(SByte)o;
} else if (type == ByteType) {
return (UInt32)(Byte)o;
} else if (type == SingleType) {
return (UInt32)(Single)o;
} else if (type == CharType) {
return (UInt32)(Char)o;
} else if (type == DecimalType) {
return (UInt32)(Decimal)o;
} else if (type.IsEnum) {
return (UInt32)ExplicitCastEnumToUInt32(o);
} else if (type == NullableInt32Type) {
return (UInt32)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (UInt32)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (UInt32)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (UInt32)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (UInt32)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (UInt32)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (UInt32)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (UInt32)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (UInt32)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (UInt32)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (UInt32)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (UInt32)(Nullable<Decimal>)o;
}
}
throw InvalidCast(o, "UInt32");
}
[CLSCompliant(false)]
public static UInt64 ExplicitCastToUInt64(object o) {
if (o != null) {
Type type = o.GetType();
if (type == Int32Type) {
return (UInt64)(Int32)o;
} else if (type == DoubleType) {
return (UInt64)(Double)o;
} else if (type == Int64Type) {
return (UInt64)(Int64)o;
} else if (type == Int16Type) {
return (UInt64)(Int16)o;
} else if (type == UInt32Type) {
return (UInt64)(UInt32)o;
} else if (type == UInt64Type) {
return (UInt64)(UInt64)o;
} else if (type == UInt16Type) {
return (UInt64)(UInt16)o;
} else if (type == SByteType) {
return (UInt64)(SByte)o;
} else if (type == ByteType) {
return (UInt64)(Byte)o;
} else if (type == SingleType) {
return (UInt64)(Single)o;
} else if (type == CharType) {
return (UInt64)(Char)o;
} else if (type == DecimalType) {
return (UInt64)(Decimal)o;
} else if (type.IsEnum) {
return (UInt64)ExplicitCastEnumToUInt64(o);
} else if (type == NullableInt32Type) {
return (UInt64)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (UInt64)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (UInt64)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (UInt64)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (UInt64)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (UInt64)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (UInt64)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (UInt64)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (UInt64)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (UInt64)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (UInt64)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (UInt64)(Nullable<Decimal>)o;
}
}
throw InvalidCast(o, "UInt64");
}
public static Nullable<Boolean> ExplicitCastToNullableBoolean(object o) {
if (o == null) {
return new Nullable<Boolean>();
}
Type type = o.GetType();
if (type == BooleanType) {
return (Nullable<Boolean>)(Boolean)o;
} else if (type == NullableBooleanType) {
return (Nullable<Boolean>)(Nullable<Boolean>)o;
}
throw InvalidCast(o, "Boolean");
}
public static Nullable<Byte> ExplicitCastToNullableByte(object o) {
if (o == null) {
return new Nullable<Byte>();
}
Type type = o.GetType();
if (type == Int32Type) {
return (Nullable<Byte>)(Int32)o;
} else if (type == DoubleType) {
return (Nullable<Byte>)(Double)o;
} else if (type == Int64Type) {
return (Nullable<Byte>)(Int64)o;
} else if (type == Int16Type) {
return (Nullable<Byte>)(Int16)o;
} else if (type == UInt32Type) {
return (Nullable<Byte>)(UInt32)o;
} else if (type == UInt64Type) {
return (Nullable<Byte>)(UInt64)o;
} else if (type == UInt16Type) {
return (Nullable<Byte>)(UInt16)o;
} else if (type == SByteType) {
return (Nullable<Byte>)(SByte)o;
} else if (type == ByteType) {
return (Nullable<Byte>)(Byte)o;
} else if (type == SingleType) {
return (Nullable<Byte>)(Single)o;
} else if (type == CharType) {
return (Nullable<Byte>)(Char)o;
} else if (type == DecimalType) {
return (Nullable<Byte>)(Decimal)o;
} else if (type.IsEnum) {
return (Nullable<Byte>)ExplicitCastEnumToByte(o);
} else if (type == NullableInt32Type) {
return (Nullable<Byte>)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (Nullable<Byte>)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (Nullable<Byte>)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (Nullable<Byte>)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (Nullable<Byte>)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (Nullable<Byte>)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (Nullable<Byte>)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (Nullable<Byte>)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (Nullable<Byte>)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (Nullable<Byte>)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (Nullable<Byte>)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (Nullable<Byte>)(Nullable<Decimal>)o;
}
throw InvalidCast(o, "Byte");
}
public static Nullable<Char> ExplicitCastToNullableChar(object o) {
if (o == null) {
return new Nullable<Char>();
}
Type type = o.GetType();
if (type == Int32Type) {
return (Nullable<Char>)(Int32)o;
} else if (type == DoubleType) {
return (Nullable<Char>)(Double)o;
} else if (type == Int64Type) {
return (Nullable<Char>)(Int64)o;
} else if (type == Int16Type) {
return (Nullable<Char>)(Int16)o;
} else if (type == UInt32Type) {
return (Nullable<Char>)(UInt32)o;
} else if (type == UInt64Type) {
return (Nullable<Char>)(UInt64)o;
} else if (type == UInt16Type) {
return (Nullable<Char>)(UInt16)o;
} else if (type == SByteType) {
return (Nullable<Char>)(SByte)o;
} else if (type == ByteType) {
return (Nullable<Char>)(Byte)o;
} else if (type == SingleType) {
return (Nullable<Char>)(Single)o;
} else if (type == CharType) {
return (Nullable<Char>)(Char)o;
} else if (type == DecimalType) {
return (Nullable<Char>)(Decimal)o;
} else if (type.IsEnum) {
return (Nullable<Char>)ExplicitCastEnumToInt32(o);
} else if (type == NullableInt32Type) {
return (Nullable<Char>)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (Nullable<Char>)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (Nullable<Char>)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (Nullable<Char>)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (Nullable<Char>)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (Nullable<Char>)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (Nullable<Char>)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (Nullable<Char>)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (Nullable<Char>)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (Nullable<Char>)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (Nullable<Char>)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (Nullable<Char>)(Nullable<Decimal>)o;
}
throw InvalidCast(o, "Char");
}
public static Nullable<Decimal> ExplicitCastToNullableDecimal(object o) {
if (o == null) {
return new Nullable<Decimal>();
}
Type type = o.GetType();
if (type == Int32Type) {
return (Nullable<Decimal>)(Int32)o;
} else if (type == DoubleType) {
return (Nullable<Decimal>)(Double)o;
} else if (type == Int64Type) {
return (Nullable<Decimal>)(Int64)o;
} else if (type == Int16Type) {
return (Nullable<Decimal>)(Int16)o;
} else if (type == UInt32Type) {
return (Nullable<Decimal>)(UInt32)o;
} else if (type == UInt64Type) {
return (Nullable<Decimal>)(UInt64)o;
} else if (type == UInt16Type) {
return (Nullable<Decimal>)(UInt16)o;
} else if (type == SByteType) {
return (Nullable<Decimal>)(SByte)o;
} else if (type == ByteType) {
return (Nullable<Decimal>)(Byte)o;
} else if (type == SingleType) {
return (Nullable<Decimal>)(Single)o;
} else if (type == CharType) {
return (Nullable<Decimal>)(Char)o;
} else if (type == DecimalType) {
return (Nullable<Decimal>)(Decimal)o;
} else if (type.IsEnum) {
return (Nullable<Decimal>)ExplicitCastEnumToInt64(o);
} else if (type == NullableInt32Type) {
return (Nullable<Decimal>)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (Nullable<Decimal>)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (Nullable<Decimal>)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (Nullable<Decimal>)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (Nullable<Decimal>)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (Nullable<Decimal>)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (Nullable<Decimal>)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (Nullable<Decimal>)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (Nullable<Decimal>)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (Nullable<Decimal>)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (Nullable<Decimal>)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (Nullable<Decimal>)(Nullable<Decimal>)o;
}
throw InvalidCast(o, "Decimal");
}
public static Nullable<Double> ExplicitCastToNullableDouble(object o) {
if (o == null) {
return new Nullable<Double>();
}
Type type = o.GetType();
if (type == Int32Type) {
return (Nullable<Double>)(Int32)o;
} else if (type == DoubleType) {
return (Nullable<Double>)(Double)o;
} else if (type == Int64Type) {
return (Nullable<Double>)(Int64)o;
} else if (type == Int16Type) {
return (Nullable<Double>)(Int16)o;
} else if (type == UInt32Type) {
return (Nullable<Double>)(UInt32)o;
} else if (type == UInt64Type) {
return (Nullable<Double>)(UInt64)o;
} else if (type == UInt16Type) {
return (Nullable<Double>)(UInt16)o;
} else if (type == SByteType) {
return (Nullable<Double>)(SByte)o;
} else if (type == ByteType) {
return (Nullable<Double>)(Byte)o;
} else if (type == SingleType) {
return (Nullable<Double>)(Single)o;
} else if (type == CharType) {
return (Nullable<Double>)(Char)o;
} else if (type == DecimalType) {
return (Nullable<Double>)(Decimal)o;
} else if (type.IsEnum) {
return (Nullable<Double>)ExplicitCastEnumToInt64(o);
} else if (type == NullableInt32Type) {
return (Nullable<Double>)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (Nullable<Double>)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (Nullable<Double>)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (Nullable<Double>)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (Nullable<Double>)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (Nullable<Double>)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (Nullable<Double>)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (Nullable<Double>)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (Nullable<Double>)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (Nullable<Double>)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (Nullable<Double>)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (Nullable<Double>)(Nullable<Decimal>)o;
}
throw InvalidCast(o, "Double");
}
public static Nullable<Int16> ExplicitCastToNullableInt16(object o) {
if (o == null) {
return new Nullable<Int16>();
}
Type type = o.GetType();
if (type == Int32Type) {
return (Nullable<Int16>)(Int32)o;
} else if (type == DoubleType) {
return (Nullable<Int16>)(Double)o;
} else if (type == Int64Type) {
return (Nullable<Int16>)(Int64)o;
} else if (type == Int16Type) {
return (Nullable<Int16>)(Int16)o;
} else if (type == UInt32Type) {
return (Nullable<Int16>)(UInt32)o;
} else if (type == UInt64Type) {
return (Nullable<Int16>)(UInt64)o;
} else if (type == UInt16Type) {
return (Nullable<Int16>)(UInt16)o;
} else if (type == SByteType) {
return (Nullable<Int16>)(SByte)o;
} else if (type == ByteType) {
return (Nullable<Int16>)(Byte)o;
} else if (type == SingleType) {
return (Nullable<Int16>)(Single)o;
} else if (type == CharType) {
return (Nullable<Int16>)(Char)o;
} else if (type == DecimalType) {
return (Nullable<Int16>)(Decimal)o;
} else if (type.IsEnum) {
return (Nullable<Int16>)ExplicitCastEnumToInt16(o);
} else if (type == NullableInt32Type) {
return (Nullable<Int16>)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (Nullable<Int16>)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (Nullable<Int16>)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (Nullable<Int16>)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (Nullable<Int16>)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (Nullable<Int16>)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (Nullable<Int16>)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (Nullable<Int16>)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (Nullable<Int16>)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (Nullable<Int16>)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (Nullable<Int16>)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (Nullable<Int16>)(Nullable<Decimal>)o;
}
throw InvalidCast(o, "Int16");
}
public static Nullable<Int32> ExplicitCastToNullableInt32(object o) {
if (o == null) {
return new Nullable<Int32>();
}
Type type = o.GetType();
if (type == Int32Type) {
return (Nullable<Int32>)(Int32)o;
} else if (type == DoubleType) {
return (Nullable<Int32>)(Double)o;
} else if (type == Int64Type) {
return (Nullable<Int32>)(Int64)o;
} else if (type == Int16Type) {
return (Nullable<Int32>)(Int16)o;
} else if (type == UInt32Type) {
return (Nullable<Int32>)(UInt32)o;
} else if (type == UInt64Type) {
return (Nullable<Int32>)(UInt64)o;
} else if (type == UInt16Type) {
return (Nullable<Int32>)(UInt16)o;
} else if (type == SByteType) {
return (Nullable<Int32>)(SByte)o;
} else if (type == ByteType) {
return (Nullable<Int32>)(Byte)o;
} else if (type == SingleType) {
return (Nullable<Int32>)(Single)o;
} else if (type == CharType) {
return (Nullable<Int32>)(Char)o;
} else if (type == DecimalType) {
return (Nullable<Int32>)(Decimal)o;
} else if (type.IsEnum) {
return (Nullable<Int32>)ExplicitCastEnumToInt32(o);
} else if (type == NullableInt32Type) {
return (Nullable<Int32>)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (Nullable<Int32>)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (Nullable<Int32>)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (Nullable<Int32>)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (Nullable<Int32>)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (Nullable<Int32>)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (Nullable<Int32>)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (Nullable<Int32>)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (Nullable<Int32>)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (Nullable<Int32>)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (Nullable<Int32>)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (Nullable<Int32>)(Nullable<Decimal>)o;
}
throw InvalidCast(o, "Int32");
}
public static Nullable<Int64> ExplicitCastToNullableInt64(object o) {
if (o == null) {
return new Nullable<Int64>();
}
Type type = o.GetType();
if (type == Int32Type) {
return (Nullable<Int64>)(Int32)o;
} else if (type == DoubleType) {
return (Nullable<Int64>)(Double)o;
} else if (type == Int64Type) {
return (Nullable<Int64>)(Int64)o;
} else if (type == Int16Type) {
return (Nullable<Int64>)(Int16)o;
} else if (type == UInt32Type) {
return (Nullable<Int64>)(UInt32)o;
} else if (type == UInt64Type) {
return (Nullable<Int64>)(UInt64)o;
} else if (type == UInt16Type) {
return (Nullable<Int64>)(UInt16)o;
} else if (type == SByteType) {
return (Nullable<Int64>)(SByte)o;
} else if (type == ByteType) {
return (Nullable<Int64>)(Byte)o;
} else if (type == SingleType) {
return (Nullable<Int64>)(Single)o;
} else if (type == CharType) {
return (Nullable<Int64>)(Char)o;
} else if (type == DecimalType) {
return (Nullable<Int64>)(Decimal)o;
} else if (type.IsEnum) {
return (Nullable<Int64>)ExplicitCastEnumToInt64(o);
} else if (type == NullableInt32Type) {
return (Nullable<Int64>)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (Nullable<Int64>)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (Nullable<Int64>)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (Nullable<Int64>)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (Nullable<Int64>)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (Nullable<Int64>)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (Nullable<Int64>)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (Nullable<Int64>)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (Nullable<Int64>)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (Nullable<Int64>)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (Nullable<Int64>)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (Nullable<Int64>)(Nullable<Decimal>)o;
}
throw InvalidCast(o, "Int64");
}
[CLSCompliant(false)]
public static Nullable<SByte> ExplicitCastToNullableSByte(object o) {
if (o == null) {
return new Nullable<SByte>();
}
Type type = o.GetType();
if (type == Int32Type) {
return (Nullable<SByte>)(Int32)o;
} else if (type == DoubleType) {
return (Nullable<SByte>)(Double)o;
} else if (type == Int64Type) {
return (Nullable<SByte>)(Int64)o;
} else if (type == Int16Type) {
return (Nullable<SByte>)(Int16)o;
} else if (type == UInt32Type) {
return (Nullable<SByte>)(UInt32)o;
} else if (type == UInt64Type) {
return (Nullable<SByte>)(UInt64)o;
} else if (type == UInt16Type) {
return (Nullable<SByte>)(UInt16)o;
} else if (type == SByteType) {
return (Nullable<SByte>)(SByte)o;
} else if (type == ByteType) {
return (Nullable<SByte>)(Byte)o;
} else if (type == SingleType) {
return (Nullable<SByte>)(Single)o;
} else if (type == CharType) {
return (Nullable<SByte>)(Char)o;
} else if (type == DecimalType) {
return (Nullable<SByte>)(Decimal)o;
} else if (type.IsEnum) {
return (Nullable<SByte>)ExplicitCastEnumToSByte(o);
} else if (type == NullableInt32Type) {
return (Nullable<SByte>)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (Nullable<SByte>)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (Nullable<SByte>)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (Nullable<SByte>)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (Nullable<SByte>)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (Nullable<SByte>)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (Nullable<SByte>)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (Nullable<SByte>)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (Nullable<SByte>)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (Nullable<SByte>)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (Nullable<SByte>)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (Nullable<SByte>)(Nullable<Decimal>)o;
}
throw InvalidCast(o, "SByte");
}
public static Nullable<Single> ExplicitCastToNullableSingle(object o) {
if (o == null) {
return new Nullable<Single>();
}
Type type = o.GetType();
if (type == Int32Type) {
return (Nullable<Single>)(Int32)o;
} else if (type == DoubleType) {
return (Nullable<Single>)(Double)o;
} else if (type == Int64Type) {
return (Nullable<Single>)(Int64)o;
} else if (type == Int16Type) {
return (Nullable<Single>)(Int16)o;
} else if (type == UInt32Type) {
return (Nullable<Single>)(UInt32)o;
} else if (type == UInt64Type) {
return (Nullable<Single>)(UInt64)o;
} else if (type == UInt16Type) {
return (Nullable<Single>)(UInt16)o;
} else if (type == SByteType) {
return (Nullable<Single>)(SByte)o;
} else if (type == ByteType) {
return (Nullable<Single>)(Byte)o;
} else if (type == SingleType) {
return (Nullable<Single>)(Single)o;
} else if (type == CharType) {
return (Nullable<Single>)(Char)o;
} else if (type == DecimalType) {
return (Nullable<Single>)(Decimal)o;
} else if (type.IsEnum) {
return (Nullable<Single>)ExplicitCastEnumToInt64(o);
} else if (type == NullableInt32Type) {
return (Nullable<Single>)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (Nullable<Single>)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (Nullable<Single>)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (Nullable<Single>)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (Nullable<Single>)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (Nullable<Single>)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (Nullable<Single>)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (Nullable<Single>)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (Nullable<Single>)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (Nullable<Single>)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (Nullable<Single>)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (Nullable<Single>)(Nullable<Decimal>)o;
}
throw InvalidCast(o, "Single");
}
[CLSCompliant(false)]
public static Nullable<UInt16> ExplicitCastToNullableUInt16(object o) {
if (o == null) {
return new Nullable<UInt16>();
}
Type type = o.GetType();
if (type == Int32Type) {
return (Nullable<UInt16>)(Int32)o;
} else if (type == DoubleType) {
return (Nullable<UInt16>)(Double)o;
} else if (type == Int64Type) {
return (Nullable<UInt16>)(Int64)o;
} else if (type == Int16Type) {
return (Nullable<UInt16>)(Int16)o;
} else if (type == UInt32Type) {
return (Nullable<UInt16>)(UInt32)o;
} else if (type == UInt64Type) {
return (Nullable<UInt16>)(UInt64)o;
} else if (type == UInt16Type) {
return (Nullable<UInt16>)(UInt16)o;
} else if (type == SByteType) {
return (Nullable<UInt16>)(SByte)o;
} else if (type == ByteType) {
return (Nullable<UInt16>)(Byte)o;
} else if (type == SingleType) {
return (Nullable<UInt16>)(Single)o;
} else if (type == CharType) {
return (Nullable<UInt16>)(Char)o;
} else if (type == DecimalType) {
return (Nullable<UInt16>)(Decimal)o;
} else if (type.IsEnum) {
return (Nullable<UInt16>)ExplicitCastEnumToUInt16(o);
} else if (type == NullableInt32Type) {
return (Nullable<UInt16>)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (Nullable<UInt16>)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (Nullable<UInt16>)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (Nullable<UInt16>)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (Nullable<UInt16>)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (Nullable<UInt16>)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (Nullable<UInt16>)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (Nullable<UInt16>)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (Nullable<UInt16>)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (Nullable<UInt16>)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (Nullable<UInt16>)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (Nullable<UInt16>)(Nullable<Decimal>)o;
}
throw InvalidCast(o, "UInt16");
}
[CLSCompliant(false)]
public static Nullable<UInt32> ExplicitCastToNullableUInt32(object o) {
if (o == null) {
return new Nullable<UInt32>();
}
Type type = o.GetType();
if (type == Int32Type) {
return (Nullable<UInt32>)(Int32)o;
} else if (type == DoubleType) {
return (Nullable<UInt32>)(Double)o;
} else if (type == Int64Type) {
return (Nullable<UInt32>)(Int64)o;
} else if (type == Int16Type) {
return (Nullable<UInt32>)(Int16)o;
} else if (type == UInt32Type) {
return (Nullable<UInt32>)(UInt32)o;
} else if (type == UInt64Type) {
return (Nullable<UInt32>)(UInt64)o;
} else if (type == UInt16Type) {
return (Nullable<UInt32>)(UInt16)o;
} else if (type == SByteType) {
return (Nullable<UInt32>)(SByte)o;
} else if (type == ByteType) {
return (Nullable<UInt32>)(Byte)o;
} else if (type == SingleType) {
return (Nullable<UInt32>)(Single)o;
} else if (type == CharType) {
return (Nullable<UInt32>)(Char)o;
} else if (type == DecimalType) {
return (Nullable<UInt32>)(Decimal)o;
} else if (type.IsEnum) {
return (Nullable<UInt32>)ExplicitCastEnumToUInt32(o);
} else if (type == NullableInt32Type) {
return (Nullable<UInt32>)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (Nullable<UInt32>)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (Nullable<UInt32>)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (Nullable<UInt32>)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (Nullable<UInt32>)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (Nullable<UInt32>)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (Nullable<UInt32>)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (Nullable<UInt32>)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (Nullable<UInt32>)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (Nullable<UInt32>)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (Nullable<UInt32>)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (Nullable<UInt32>)(Nullable<Decimal>)o;
}
throw InvalidCast(o, "UInt32");
}
[CLSCompliant(false)]
public static Nullable<UInt64> ExplicitCastToNullableUInt64(object o) {
if (o == null) {
return new Nullable<UInt64>();
}
Type type = o.GetType();
if (type == Int32Type) {
return (Nullable<UInt64>)(Int32)o;
} else if (type == DoubleType) {
return (Nullable<UInt64>)(Double)o;
} else if (type == Int64Type) {
return (Nullable<UInt64>)(Int64)o;
} else if (type == Int16Type) {
return (Nullable<UInt64>)(Int16)o;
} else if (type == UInt32Type) {
return (Nullable<UInt64>)(UInt32)o;
} else if (type == UInt64Type) {
return (Nullable<UInt64>)(UInt64)o;
} else if (type == UInt16Type) {
return (Nullable<UInt64>)(UInt16)o;
} else if (type == SByteType) {
return (Nullable<UInt64>)(SByte)o;
} else if (type == ByteType) {
return (Nullable<UInt64>)(Byte)o;
} else if (type == SingleType) {
return (Nullable<UInt64>)(Single)o;
} else if (type == CharType) {
return (Nullable<UInt64>)(Char)o;
} else if (type == DecimalType) {
return (Nullable<UInt64>)(Decimal)o;
} else if (type.IsEnum) {
return (Nullable<UInt64>)ExplicitCastEnumToUInt64(o);
} else if (type == NullableInt32Type) {
return (Nullable<UInt64>)(Nullable<Int32>)o;
} else if (type == NullableDoubleType) {
return (Nullable<UInt64>)(Nullable<Double>)o;
} else if (type == NullableInt64Type) {
return (Nullable<UInt64>)(Nullable<Int64>)o;
} else if (type == NullableInt16Type) {
return (Nullable<UInt64>)(Nullable<Int16>)o;
} else if (type == NullableUInt32Type) {
return (Nullable<UInt64>)(Nullable<UInt32>)o;
} else if (type == NullableUInt64Type) {
return (Nullable<UInt64>)(Nullable<UInt64>)o;
} else if (type == NullableUInt16Type) {
return (Nullable<UInt64>)(Nullable<UInt16>)o;
} else if (type == NullableSByteType) {
return (Nullable<UInt64>)(Nullable<SByte>)o;
} else if (type == NullableByteType) {
return (Nullable<UInt64>)(Nullable<Byte>)o;
} else if (type == NullableSingleType) {
return (Nullable<UInt64>)(Nullable<Single>)o;
} else if (type == NullableCharType) {
return (Nullable<UInt64>)(Nullable<Char>)o;
} else if (type == NullableDecimalType) {
return (Nullable<UInt64>)(Nullable<Decimal>)o;
}
throw InvalidCast(o, "UInt64");
}
// *** END GENERATED CODE ***
#endregion
#region Generated Nullable Instance
// *** BEGIN GENERATED CODE ***
// generated by function: generate_nullable_instance from: generate_casts.py
public static object NewNullableInstance(Type type) {
if (type == Int32Type) {
return new Nullable<Int32>();
} else if (type == DoubleType) {
return new Nullable<Double>();
} else if (type == BooleanType) {
return new Nullable<Boolean>();
} else if (type == Int64Type) {
return new Nullable<Int64>();
} else if (type == Int16Type) {
return new Nullable<Int16>();
} else if (type == UInt32Type) {
return new Nullable<UInt32>();
} else if (type == UInt64Type) {
return new Nullable<UInt64>();
} else if (type == UInt16Type) {
return new Nullable<UInt16>();
} else if (type == SByteType) {
return new Nullable<SByte>();
} else if (type == ByteType) {
return new Nullable<Byte>();
} else if (type == SingleType) {
return new Nullable<Single>();
} else if (type == CharType) {
return new Nullable<Char>();
} else if (type == DecimalType) {
return new Nullable<Decimal>();
} else {
return NewNullableInstanceSlow(type);
}
}
// *** END GENERATED CODE ***
#endregion
#region Generated Enum Casts
// *** BEGIN GENERATED CODE ***
// generated by function: generate_enum_casts from: generate_casts.py
internal static Byte ExplicitCastEnumToByte(object o) {
Debug.Assert(o is Enum);
switch (((Enum)o).GetTypeCode()) {
case TypeCode.Byte: return (Byte)(Byte)o;
case TypeCode.SByte: return (Byte)(SByte)o;
case TypeCode.Int16: return (Byte)(Int16)o;
case TypeCode.UInt16: return (Byte)(UInt16)o;
case TypeCode.Int32: return (Byte)(Int32)o;
case TypeCode.UInt32: return (Byte)(UInt32)o;
case TypeCode.Int64: return (Byte)(Int64)o;
case TypeCode.UInt64: return (Byte)(UInt64)o;
}
throw new InvalidOperationException("Invalid enum");
}
internal static SByte ExplicitCastEnumToSByte(object o) {
Debug.Assert(o is Enum);
switch (((Enum)o).GetTypeCode()) {
case TypeCode.Byte: return (SByte)(Byte)o;
case TypeCode.SByte: return (SByte)(SByte)o;
case TypeCode.Int16: return (SByte)(Int16)o;
case TypeCode.UInt16: return (SByte)(UInt16)o;
case TypeCode.Int32: return (SByte)(Int32)o;
case TypeCode.UInt32: return (SByte)(UInt32)o;
case TypeCode.Int64: return (SByte)(Int64)o;
case TypeCode.UInt64: return (SByte)(UInt64)o;
}
throw new InvalidOperationException("Invalid enum");
}
internal static Int16 ExplicitCastEnumToInt16(object o) {
Debug.Assert(o is Enum);
switch (((Enum)o).GetTypeCode()) {
case TypeCode.Byte: return (Int16)(Byte)o;
case TypeCode.SByte: return (Int16)(SByte)o;
case TypeCode.Int16: return (Int16)(Int16)o;
case TypeCode.UInt16: return (Int16)(UInt16)o;
case TypeCode.Int32: return (Int16)(Int32)o;
case TypeCode.UInt32: return (Int16)(UInt32)o;
case TypeCode.Int64: return (Int16)(Int64)o;
case TypeCode.UInt64: return (Int16)(UInt64)o;
}
throw new InvalidOperationException("Invalid enum");
}
internal static UInt16 ExplicitCastEnumToUInt16(object o) {
Debug.Assert(o is Enum);
switch (((Enum)o).GetTypeCode()) {
case TypeCode.Byte: return (UInt16)(Byte)o;
case TypeCode.SByte: return (UInt16)(SByte)o;
case TypeCode.Int16: return (UInt16)(Int16)o;
case TypeCode.UInt16: return (UInt16)(UInt16)o;
case TypeCode.Int32: return (UInt16)(Int32)o;
case TypeCode.UInt32: return (UInt16)(UInt32)o;
case TypeCode.Int64: return (UInt16)(Int64)o;
case TypeCode.UInt64: return (UInt16)(UInt64)o;
}
throw new InvalidOperationException("Invalid enum");
}
internal static Int32 ExplicitCastEnumToInt32(object o) {
Debug.Assert(o is Enum);
switch (((Enum)o).GetTypeCode()) {
case TypeCode.Byte: return (Int32)(Byte)o;
case TypeCode.SByte: return (Int32)(SByte)o;
case TypeCode.Int16: return (Int32)(Int16)o;
case TypeCode.UInt16: return (Int32)(UInt16)o;
case TypeCode.Int32: return (Int32)(Int32)o;
case TypeCode.UInt32: return (Int32)(UInt32)o;
case TypeCode.Int64: return (Int32)(Int64)o;
case TypeCode.UInt64: return (Int32)(UInt64)o;
}
throw new InvalidOperationException("Invalid enum");
}
internal static UInt32 ExplicitCastEnumToUInt32(object o) {
Debug.Assert(o is Enum);
switch (((Enum)o).GetTypeCode()) {
case TypeCode.Byte: return (UInt32)(Byte)o;
case TypeCode.SByte: return (UInt32)(SByte)o;
case TypeCode.Int16: return (UInt32)(Int16)o;
case TypeCode.UInt16: return (UInt32)(UInt16)o;
case TypeCode.Int32: return (UInt32)(Int32)o;
case TypeCode.UInt32: return (UInt32)(UInt32)o;
case TypeCode.Int64: return (UInt32)(Int64)o;
case TypeCode.UInt64: return (UInt32)(UInt64)o;
}
throw new InvalidOperationException("Invalid enum");
}
internal static Int64 ExplicitCastEnumToInt64(object o) {
Debug.Assert(o is Enum);
switch (((Enum)o).GetTypeCode()) {
case TypeCode.Byte: return (Int64)(Byte)o;
case TypeCode.SByte: return (Int64)(SByte)o;
case TypeCode.Int16: return (Int64)(Int16)o;
case TypeCode.UInt16: return (Int64)(UInt16)o;
case TypeCode.Int32: return (Int64)(Int32)o;
case TypeCode.UInt32: return (Int64)(UInt32)o;
case TypeCode.Int64: return (Int64)(Int64)o;
case TypeCode.UInt64: return (Int64)(UInt64)o;
}
throw new InvalidOperationException("Invalid enum");
}
internal static UInt64 ExplicitCastEnumToUInt64(object o) {
Debug.Assert(o is Enum);
switch (((Enum)o).GetTypeCode()) {
case TypeCode.Byte: return (UInt64)(Byte)o;
case TypeCode.SByte: return (UInt64)(SByte)o;
case TypeCode.Int16: return (UInt64)(Int16)o;
case TypeCode.UInt16: return (UInt64)(UInt16)o;
case TypeCode.Int32: return (UInt64)(Int32)o;
case TypeCode.UInt32: return (UInt64)(UInt32)o;
case TypeCode.Int64: return (UInt64)(Int64)o;
case TypeCode.UInt64: return (UInt64)(UInt64)o;
}
throw new InvalidOperationException("Invalid enum");
}
// *** END GENERATED CODE ***
#endregion
#region Generated Type Cache
// *** BEGIN GENERATED CODE ***
// generated by function: generate_type_cache from: generate_casts.py
internal static readonly Type BooleanType = typeof(Boolean);
internal static readonly Type ByteType = typeof(Byte);
internal static readonly Type CharType = typeof(Char);
internal static readonly Type DecimalType = typeof(Decimal);
internal static readonly Type DoubleType = typeof(Double);
internal static readonly Type Int16Type = typeof(Int16);
internal static readonly Type Int32Type = typeof(Int32);
internal static readonly Type Int64Type = typeof(Int64);
internal static readonly Type ObjectType = typeof(Object);
internal static readonly Type SByteType = typeof(SByte);
internal static readonly Type SingleType = typeof(Single);
internal static readonly Type UInt16Type = typeof(UInt16);
internal static readonly Type UInt32Type = typeof(UInt32);
internal static readonly Type UInt64Type = typeof(UInt64);
internal static readonly Type NullableBooleanType = typeof(Nullable<Boolean>);
internal static readonly Type NullableByteType = typeof(Nullable<Byte>);
internal static readonly Type NullableCharType = typeof(Nullable<Char>);
internal static readonly Type NullableDecimalType = typeof(Nullable<Decimal>);
internal static readonly Type NullableDoubleType = typeof(Nullable<Double>);
internal static readonly Type NullableInt16Type = typeof(Nullable<Int16>);
internal static readonly Type NullableInt32Type = typeof(Nullable<Int32>);
internal static readonly Type NullableInt64Type = typeof(Nullable<Int64>);
internal static readonly Type NullableSByteType = typeof(Nullable<SByte>);
internal static readonly Type NullableSingleType = typeof(Nullable<Single>);
internal static readonly Type NullableUInt16Type = typeof(Nullable<UInt16>);
internal static readonly Type NullableUInt32Type = typeof(Nullable<UInt32>);
internal static readonly Type NullableUInt64Type = typeof(Nullable<UInt64>);
// *** END GENERATED CODE ***
#endregion
internal static readonly Type NullableType = typeof(Nullable<>);
}
}
| 47.494069 | 98 | 0.491239 | [
"MIT"
] | rifraf/IronRuby_Framework_4.7.2 | Runtime/Microsoft.Dynamic/Runtime/Cast.Generated.cs | 80,075 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Async;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.Async
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.AddAwait), Shared]
internal class CSharpAddAwaitCodeFixProvider : AbstractAddAsyncAwaitCodeFixProvider
{
/// <summary>
/// Because this call is not awaited, execution of the current method continues before the call is completed.
/// </summary>
private const string CS4014 = nameof(CS4014);
/// <summary>
/// Since this is an async method, the return expression must be of type 'blah' rather than 'baz'
/// </summary>
private const string CS4016 = nameof(CS4016);
/// <summary>
/// cannot implicitly convert from 'X' to 'Y'.
/// </summary>
private const string CS0029 = nameof(CS0029);
public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(CS0029, CS4014, CS4016);
protected override string GetDescription(Diagnostic diagnostic, SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken) =>
CSharpFeaturesResources.Insert_await;
protected override Task<SyntaxNode> GetNewRoot(
SyntaxNode root,
SyntaxNode oldNode,
SemanticModel semanticModel,
Diagnostic diagnostic,
Document document,
CancellationToken cancellationToken)
{
var expression = oldNode as ExpressionSyntax;
if (expression == null)
{
return SpecializedTasks.Default<SyntaxNode>();
}
switch (diagnostic.Id)
{
case CS4014:
return Task.FromResult(root.ReplaceNode(oldNode, ConvertToAwaitExpression(expression)));
case CS4016:
if (!DoesExpressionReturnTask(expression, semanticModel))
{
return SpecializedTasks.Default<SyntaxNode>();
}
return Task.FromResult(root.ReplaceNode(oldNode, ConvertToAwaitExpression(expression)));
case CS0029:
if (!DoesExpressionReturnGenericTaskWhoseArgumentsMatchLeftSide(expression, semanticModel, document.Project, cancellationToken))
{
return SpecializedTasks.Default<SyntaxNode>();
}
return Task.FromResult(root.ReplaceNode(oldNode, ConvertToAwaitExpression(expression)));
default:
return SpecializedTasks.Default<SyntaxNode>();
}
}
private static bool DoesExpressionReturnTask(ExpressionSyntax expression, SemanticModel semanticModel)
{
INamedTypeSymbol taskType = null;
if (!TryGetTaskType(semanticModel, out taskType))
{
return false;
}
INamedTypeSymbol returnType = null;
return TryGetExpressionType(expression, semanticModel, out returnType) &&
semanticModel.Compilation.ClassifyConversion(taskType, returnType).Exists;
}
private static bool DoesExpressionReturnGenericTaskWhoseArgumentsMatchLeftSide(ExpressionSyntax expression, SemanticModel semanticModel, Project project, CancellationToken cancellationToken)
{
if (!IsInAsyncFunction(expression))
{
return false;
}
INamedTypeSymbol taskType = null;
INamedTypeSymbol rightSideType = null;
if (!TryGetTaskType(semanticModel, out taskType) ||
!TryGetExpressionType(expression, semanticModel, out rightSideType))
{
return false;
}
var compilation = semanticModel.Compilation;
if (!compilation.ClassifyConversion(taskType, rightSideType).Exists)
{
return false;
}
if (!rightSideType.IsGenericType)
{
return false;
}
var typeArguments = rightSideType.TypeArguments;
var typeInferer = project.LanguageServices.GetService<ITypeInferenceService>();
var inferredTypes = typeInferer.InferTypes(semanticModel, expression, cancellationToken);
return typeArguments.Any(ta => inferredTypes.Any(it => compilation.ClassifyConversion(it, ta).Exists));
}
private static bool IsInAsyncFunction(ExpressionSyntax expression)
{
foreach (var node in expression.Ancestors())
{
switch (node.Kind())
{
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.AnonymousMethodExpression:
return (node as AnonymousFunctionExpressionSyntax)?.AsyncKeyword.IsMissing == false;
case SyntaxKind.MethodDeclaration:
return (node as MethodDeclarationSyntax)?.Modifiers.Any(SyntaxKind.AsyncKeyword) == true;
default:
continue;
}
}
return false;
}
private static SyntaxNode ConvertToAwaitExpression(ExpressionSyntax expression)
{
if ((expression is BinaryExpressionSyntax || expression is ConditionalExpressionSyntax) && expression.HasTrailingTrivia)
{
var expWithTrailing = expression.WithoutLeadingTrivia();
var span = expWithTrailing.GetLocation().GetLineSpan().Span;
if (span.Start.Line == span.End.Line && !expWithTrailing.DescendantTrivia().Any(trivia => trivia.IsKind(SyntaxKind.SingleLineCommentTrivia)))
{
return SyntaxFactory.AwaitExpression(SyntaxFactory.ParenthesizedExpression(expWithTrailing))
.WithLeadingTrivia(expression.GetLeadingTrivia())
.WithAdditionalAnnotations(Formatter.Annotation);
}
}
return SyntaxFactory.AwaitExpression(expression.WithoutTrivia().Parenthesize())
.WithTriviaFrom(expression)
.WithAdditionalAnnotations(Simplifier.Annotation, Formatter.Annotation);
}
}
}
| 42.622754 | 198 | 0.62349 | [
"Apache-2.0"
] | Unknown6656/roslyn | src/Features/CSharp/Portable/CodeFixes/Async/CSharpAddAwaitCodeFixProvider.cs | 7,118 | C# |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* 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.Web;
using ASC.Core;
using ASC.CRM.Core;
using ASC.Web.Core.Client.HttpHandlers;
using ASC.Web.Studio;
namespace ASC.Web.CRM.Controls.Settings
{
public partial class VoipCommon : BaseUserControl
{
public static string Location
{
get { return PathProvider.GetFileStaticRelativePath("Settings/VoIPSettings/VoipCommon.ascx"); }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!VoipNumberData.Allowed || !CRMSecurity.IsAdmin)
{
Response.Redirect(PathProvider.StartURL() + "Settings.aspx");
}
Page.RegisterBodyScripts("~/js/uploader/jquery.fileupload.js");
Page.RegisterBodyScripts(PathProvider.GetFileStaticRelativePath("voip.common.js"));
Page.RegisterClientScript(new VoipCommonData());
}
}
public class VoipCommonData : ClientScript
{
protected override string BaseNamespace
{
get { return "ASC.Resources.Master.Voip"; }
}
protected override string GetCacheHash()
{
return CoreContext.TenantManager.GetCurrentTenant().TenantId + VoipNumberData.Allowed.ToString();
}
protected override IEnumerable<KeyValuePair<string, object>> GetClientVariables(HttpContext context)
{
yield return RegisterObject(new { enabled = VoipNumberData.Allowed });
}
}
} | 32.626866 | 110 | 0.655078 | [
"Apache-2.0"
] | jeanluctritsch/CommunityServer | web/studio/ASC.Web.Studio/Products/CRM/Controls/Settings/VoipSettings/VoipCommon.ascx.cs | 2,186 | C# |
namespace CoffeeCard.Models.DataTransferObjects
{
/// <summary>
/// Simple response class with a string message
/// </summary>
/// <example>
/// {
/// "message": "Successful completion"
/// }
/// </example>
public class MessageResponseDto
{
/// <summary>
/// Message with API response
/// </summary>
/// <value>Response</value>
/// <example>Successful completion</example>
public string Message { get; set; }
}
} | 25.45 | 52 | 0.546169 | [
"MIT"
] | AnalogIO/Analog_Core | coffeecard/CoffeeCard.Models/DataTransferObjects/MessageResponseDto.cs | 511 | C# |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Talent.V4.Snippets
{
// [START jobs_v4_generated_TenantService_CreateTenant_async_flattened_resourceNames]
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Talent.V4;
using System.Threading.Tasks;
public sealed partial class GeneratedTenantServiceClientSnippets
{
/// <summary>Snippet for CreateTenantAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task CreateTenantResourceNamesAsync()
{
// Create client
TenantServiceClient tenantServiceClient = await TenantServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName parent = ProjectName.FromProject("[PROJECT]");
Tenant tenant = new Tenant();
// Make the request
Tenant response = await tenantServiceClient.CreateTenantAsync(parent, tenant);
}
}
// [END jobs_v4_generated_TenantService_CreateTenant_async_flattened_resourceNames]
}
| 40.613636 | 94 | 0.70845 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.Talent.V4/Google.Cloud.Talent.V4.GeneratedSnippets/TenantServiceClient.CreateTenantResourceNamesAsyncSnippet.g.cs | 1,787 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace AspNetCore.Security.JwsDetached.Example
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureKestrel(options => options.AllowSynchronousIO = true);
webBuilder.UseStartup<Startup>();
});
}
}
| 29.136364 | 94 | 0.602184 | [
"MIT"
] | nigma143/AspNetCore.Security.JwsDetached | AspNetCore.Security.JwsDetached.Example/Program.cs | 641 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using FootballBookmaker.Data;
using FootballBookmaker.Models;
namespace FootballBookmaker.Web.Controllers
{
public class TeamApiController : ApiController
{
private DataContext db = new DataContext();
// GET: api/TeamApi
public IQueryable<Team> GetTeams()
{
return db.Teams;
}
// GET: api/TeamApi/5
[ResponseType(typeof(Team))]
public IHttpActionResult GetTeam(int id)
{
Team team = db.Teams.Find(id);
if (team == null)
{
return NotFound();
}
return Ok(team);
}
// PUT: api/TeamApi/5
[ResponseType(typeof(void))]
public IHttpActionResult PutTeam(int id, Team team)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != team.Id)
{
return BadRequest();
}
db.Entry(team).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!TeamExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/TeamApi
[ResponseType(typeof(Team))]
public IHttpActionResult PostTeam(Team team)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Teams.Add(team);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = team.Id }, team);
}
// DELETE: api/TeamApi/5
[ResponseType(typeof(Team))]
public IHttpActionResult DeleteTeam(int id)
{
Team team = db.Teams.Find(id);
if (team == null)
{
return NotFound();
}
db.Teams.Remove(team);
db.SaveChanges();
return Ok(team);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool TeamExists(int id)
{
return db.Teams.Count(e => e.Id == id) > 0;
}
}
} | 23.621849 | 76 | 0.481679 | [
"MIT"
] | NikolayKostov-IvayloKenov/2014-05-SoftUniConf | PreparedSolution/FootballBookmaker.Web/Controllers/TeamApiController.cs | 2,813 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore;
namespace swapiclient
{
/// <summary>
/// Program
/// </summary>
public class Program
{
/// <summary>
/// Main
/// </summary>
/// <param name="args"></param>
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
/// <summary>
/// Create the web host builder.
/// </summary>
/// <param name="args"></param>
/// <returns>IWebHostBuilder</returns>
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
| 24.733333 | 76 | 0.540431 | [
"MIT"
] | donPabloNow/Chuck-SWAPI | src/swapiclient/Program.cs | 742 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Obecné informace o sestavení se řídí přes následující
// sadu atributů. Změnou hodnot těchto atributů se upraví informace
// přidružené k sestavení.
[assembly: AssemblyTitle("Pokladna")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Pokladna")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Nastavení ComVisible na false způsobí neviditelnost typů v tomto sestavení
// pro komponenty modelu COM. Pokud potřebujete přístup k typu v tomto sestavení
// modelu COM, nastavte atribut ComVisible daného typu na hodnotu True.
[assembly: ComVisible(false)]
// Následující GUID se používá pro ID knihovny typů, pokud je tento projekt vystavený pro COM.
[assembly: Guid("98af273e-c101-42cd-8b57-31dc4f2d5bf7")]
// Informace o verzi sestavení se skládá z těchto čtyř hodnot:
//
// Hlavní verze
// Podverze
// Číslo sestavení
// Revize
//
// Můžete zadat všechny hodnoty nebo nastavit výchozí číslo buildu a revize
// pomocí zástupného znaku * takto:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | 37.555556 | 94 | 0.755917 | [
"MIT"
] | N3pr0Hack3r/Pokladna | Pokladna/Properties/AssemblyInfo.cs | 1,411 | 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("TeknikServis")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TeknikServis")]
[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("25ecf84f-b36a-42fe-b599-afa831abb969")]
// 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")]
| 37.756757 | 84 | 0.745168 | [
"MIT"
] | eyupgevenim/TeknikServis | TeknikServis/Properties/AssemblyInfo.cs | 1,400 | C# |
using System.Threading.Tasks;
using Fractum;
using Fractum.WebSocket.EventModels;
namespace Fractum.WebSocket.Hooks
{
internal sealed class UserUpdateHook : IEventHook<EventModelBase>
{
public Task RunAsync(EventModelBase args, GatewayCache cache, GatewaySession session)
{
var eventArgs = (UserUpdateEventModel) args;
if (cache.TryGetUser(eventArgs.Id, out var user))
{
var clone = user?.Clone();
if (user != null)
{
user.DiscrimValue = eventArgs.Discrim;
user.Username = eventArgs.Username;
user.AvatarRaw = eventArgs.AvatarRaw;
}
cache.Client.InvokeUserUpdated(new Cacheable<User>(clone as User), user);
}
return Task.CompletedTask;
}
}
} | 29.433333 | 93 | 0.571914 | [
"MIT"
] | trinitrot0luene/Fractum | src/Fractum/WebSocket/Hooks/UserUpdateHook.cs | 885 | C# |
namespace MSIXtractApplication
{
partial class FormMain
{
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormMain));
this.SuspendLayout();
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(0, 0);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "FormMain";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.Text = "MSIXtract";
this.Load += new System.EventHandler(this.FormMain_Load);
this.ResumeLayout(false);
}
#endregion
}
}
| 33.87037 | 140 | 0.576271 | [
"MIT"
] | eddyuk/MSIXtract | MSIXtractApplication/FormMain.Designer.cs | 1,831 | C# |
using RaftCore.Models;
using TinyFp;
namespace RaftCore.Adapters
{
public interface IMessageSender
{
Unit Start(int nodeId);
Unit Stop();
Unit SendMessage(Message message);
}
}
| 17.461538 | 43 | 0.612335 | [
"MIT"
] | FrancoMelandri/raft | src/core/Adapters/IMessageSender.cs | 229 | C# |
/*
* 2015 Sizing Servers Lab, affiliated with IT bachelor degree NMCT
* University College of West-Flanders, Department GKG (www.sizingservers.be, www.nmct.be, www.howest.be/en)
*
* Author(s):
* Dieter Vandroemme
*/
using System;
using System.Drawing;
namespace Lupus_Titanium {
public class CaptureUserActionKVPControl : CaptureKeyValuePairControl {
public UserAction UserAction { get; private set; }
public CaptureUserActionKVPControl(UserAction userAction) {
UserAction = userAction;
UserAction.OnLabelChanged += UserAction_OnLabelChanged;
UserAction.OnRequestCountChanged += UserAction_OnRequestCountChanged;
BackColor = Color.FromArgb(192, 192, 255);
SetKey();
SetValue();
}
private void UserAction_OnLabelChanged(object sender, EventArgs e) { SetKey(); }
private void UserAction_OnRequestCountChanged(object sender, EventArgs e) {
if (SynchronizationContextWrapper.SynchronizationContext != null)
SynchronizationContextWrapper.SynchronizationContext.Send((state) => SetValue(), null);
}
private void SetKey() { Key = (UserAction.Label == string.Empty) ? "Ungrouped requests" : UserAction.Label; }
private void SetValue() { Value = UserAction.Requests.Count.ToString(); }
}
}
| 41.205882 | 118 | 0.668808 | [
"MIT"
] | sizingservers/Lupus-Titanium | Lupus-Titanium/Controls and dialogs/CaptureUserActionKVPControl.cs | 1,403 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("OmloxBackend")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OmloxBackend")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly
// für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("4bbe0da8-480b-409b-a9c0-443aacb9075f")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden,
// indem Sie "*" wie unten gezeigt eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 40.756757 | 106 | 0.764589 | [
"MIT"
] | TINF20C/Team_3_OMLOX_als_PC-Dienst | SOURCECODE/OmloxBackend/OmloxBackend/Properties/AssemblyInfo.cs | 1,523 | 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 elasticbeanstalk-2010-12-01.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.ElasticBeanstalk.Model
{
/// <summary>
/// Container for the parameters to the CreateApplicationVersion operation.
/// Creates an application version for the specified application.
///
/// <note>Once you create an application version with a specified Amazon S3 bucket and
/// key location, you cannot change that Amazon S3 location. If you change the Amazon
/// S3 location, you receive an exception when you attempt to launch an environment from
/// the application version. </note>
/// </summary>
public partial class CreateApplicationVersionRequest : AmazonElasticBeanstalkRequest
{
private string _applicationName;
private bool? _autoCreateApplication;
private string _description;
private S3Location _sourceBundle;
private string _versionLabel;
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public CreateApplicationVersionRequest() { }
/// <summary>
/// Instantiates CreateApplicationVersionRequest with the parameterized properties
/// </summary>
/// <param name="applicationName"> The name of the application. If no application is found with this name, and <code>AutoCreateApplication</code> is <code>false</code>, returns an <code>InvalidParameterValue</code> error. </param>
/// <param name="versionLabel">A label identifying this version. Constraint: Must be unique per application. If an application version already exists with this label for the specified application, AWS Elastic Beanstalk returns an <code>InvalidParameterValue</code> error. </param>
public CreateApplicationVersionRequest(string applicationName, string versionLabel)
{
_applicationName = applicationName;
_versionLabel = versionLabel;
}
/// <summary>
/// Gets and sets the property ApplicationName.
/// <para>
/// The name of the application. If no application is found with this name, and <code>AutoCreateApplication</code>
/// is <code>false</code>, returns an <code>InvalidParameterValue</code> error.
/// </para>
/// </summary>
public string ApplicationName
{
get { return this._applicationName; }
set { this._applicationName = value; }
}
// Check to see if ApplicationName property is set
internal bool IsSetApplicationName()
{
return this._applicationName != null;
}
/// <summary>
/// Gets and sets the property AutoCreateApplication.
/// <para>
/// Determines how the system behaves if the specified application for this version does
/// not already exist:
/// </para>
/// <enumValues> <value name="true">
/// <para>
/// <code>true</code>: Automatically creates the specified application for this version
/// if it does not already exist.
/// </para>
/// </value> <value name="false">
/// <para>
/// <code>false</code>: Returns an <code>InvalidParameterValue</code> if the specified
/// application for this version does not already exist.
/// </para>
/// </value> </enumValues> <ul> <li> <code>true</code> : Automatically creates the specified
/// application for this release if it does not already exist. </li> <li> <code>false</code>
/// : Throws an <code>InvalidParameterValue</code> if the specified application for this
/// release does not already exist. </li> </ul>
/// <para>
/// Default: <code>false</code>
/// </para>
///
/// <para>
/// Valid Values: <code>true</code> | <code>false</code>
/// </para>
/// </summary>
public bool AutoCreateApplication
{
get { return this._autoCreateApplication.GetValueOrDefault(); }
set { this._autoCreateApplication = value; }
}
// Check to see if AutoCreateApplication property is set
internal bool IsSetAutoCreateApplication()
{
return this._autoCreateApplication.HasValue;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// Describes this version.
/// </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 SourceBundle.
/// <para>
/// The Amazon S3 bucket and key that identify the location of the source bundle for
/// this version.
/// </para>
///
/// <para>
/// If data found at the Amazon S3 location exceeds the maximum allowed source bundle
/// size, AWS Elastic Beanstalk returns an <code>InvalidParameterValue</code> error. The
/// maximum size allowed is 512 MB.
/// </para>
///
/// <para>
/// Default: If not specified, AWS Elastic Beanstalk uses a sample application. If only
/// partially specified (for example, a bucket is provided but not the key) or if no data
/// is found at the Amazon S3 location, AWS Elastic Beanstalk returns an <code>InvalidParameterCombination</code>
/// error.
/// </para>
/// </summary>
public S3Location SourceBundle
{
get { return this._sourceBundle; }
set { this._sourceBundle = value; }
}
// Check to see if SourceBundle property is set
internal bool IsSetSourceBundle()
{
return this._sourceBundle != null;
}
/// <summary>
/// Gets and sets the property VersionLabel.
/// <para>
/// A label identifying this version.
/// </para>
///
/// <para>
/// Constraint: Must be unique per application. If an application version already exists
/// with this label for the specified application, AWS Elastic Beanstalk returns an <code>InvalidParameterValue</code>
/// error.
/// </para>
/// </summary>
public string VersionLabel
{
get { return this._versionLabel; }
set { this._versionLabel = value; }
}
// Check to see if VersionLabel property is set
internal bool IsSetVersionLabel()
{
return this._versionLabel != null;
}
}
} | 39.329949 | 288 | 0.614094 | [
"Apache-2.0"
] | jasoncwik/aws-sdk-net | sdk/src/Services/ElasticBeanstalk/Generated/Model/CreateApplicationVersionRequest.cs | 7,748 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="EntityProperty.cs" company="Rare Crowds Inc">
// Copyright 2012-2013 Rare Crowds, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace DataAccessLayer
{
/// <summary>
/// Name-Value pair abstraction for an Entity Property
/// </summary>
public class EntityProperty
{
/// <summary>Map for conversion from object to PropertyValue.</summary>
private static readonly Dictionary<Type, Func<object, PropertyValue>> ObjectConversionMap =
new Dictionary<Type, Func<object, PropertyValue>>
{
{ typeof(string), x => new PropertyValue((string)x) },
{ typeof(int), x => new PropertyValue((int)x) },
{ typeof(long), x => new PropertyValue((long)x) },
{ typeof(double), x => new PropertyValue((double)x) },
{ typeof(decimal), x => new PropertyValue((decimal)x) },
{ typeof(bool), x => new PropertyValue((bool)x) },
{ typeof(DateTime), x => new PropertyValue((DateTime)x) },
{ typeof(EntityId), x => new PropertyValue((EntityId)x) },
{ typeof(Guid), x => new PropertyValue((Guid)x) },
{ typeof(byte[]), x => new PropertyValue((byte[])x) },
};
/// <summary>
/// Initializes a new instance of the <see cref="EntityProperty"/> class.
/// </summary>
public EntityProperty()
{
}
/// <summary>Initializes a new instance of the <see cref="EntityProperty"/> class.</summary>
/// <param name="prop">The property to copy this instance from.</param>
public EntityProperty(EntityProperty prop)
{
this.Name = prop.Name;
this.Value = prop.Value;
this.IsBlobRef = prop.IsBlobRef;
this.Filter = prop.Filter;
}
/// <summary>Initializes a new instance of the <see cref="EntityProperty"/> class.</summary>
/// <param name="propertyName">The property name.</param>
/// <param name="propertyValue">The PropertyValue.</param>
public EntityProperty(string propertyName, PropertyValue propertyValue) :
this(propertyName, propertyValue, PropertyFilter.Default)
{
}
/// <summary>Initializes a new instance of the <see cref="EntityProperty"/> class.</summary>
/// <param name="propertyName">The property name.</param>
/// <param name="propertyValue">The PropertyValue.</param>
/// <param name="filter">The PropertyFilter enum value.</param>
public EntityProperty(string propertyName, PropertyValue propertyValue, PropertyFilter filter)
{
this.Name = propertyName;
this.Value = propertyValue;
this.IsBlobRef = false;
this.Filter = filter;
}
/// <summary>Gets or sets external (partner) name of a property.</summary>
public string Name { get; set; }
/// <summary>Gets or sets value of a property.</summary>
public PropertyValue Value { get; set; }
/// <summary>Gets or sets a value indicating whether the property is a blob reference.</summary>
public bool IsBlobRef { get; set; }
/// <summary>Gets a value indicating whether the property should be treated as a default property.</summary>
public bool IsDefaultProperty
{
get { return this.Filter == PropertyFilter.Default; }
}
/// <summary>Gets a value indicating whether the property should be treated as a system property.</summary>
public bool IsSystemProperty
{
get { return this.Filter == PropertyFilter.System; }
}
/// <summary>Gets a value indicating whether the property should be treated as an extended property.</summary>
public bool IsExtendedProperty
{
get { return this.Filter == PropertyFilter.Extended; }
}
/// <summary>Gets or sets the PropertyFilter value (e.g. - Default, Extended, or System property)</summary>
public PropertyFilter Filter { get; set; }
////
// Copy Constructors
// These will create an un-named (Name = string.Empty) EntityProperty with
// a Value based on the given type. You should only use this if you need to defer
// providing the name. For instance, they are used implicitly when assigning values to
// IEntity members where the Property setter will provide the name.
////
/// <summary>Copy construct un-named EntityProperty from string.</summary>
/// <param name="value">The value as string.</param>
/// <returns>An un-named EntityProperty.</returns>
[SuppressMessage("Microsoft.Usage", "CA2225", Justification = "Not a public API.")]
public static implicit operator EntityProperty(string value)
{
return new EntityProperty { Name = string.Empty, Value = value };
}
/// <summary>Copy construct un-named EntityProperty from Int32.</summary>
/// <param name="value">The value as Int32.</param>
/// <returns>An un-named EntityProperty.</returns>
[SuppressMessage("Microsoft.Usage", "CA2225", Justification = "Not a public API.")]
public static implicit operator EntityProperty(int value)
{
return new EntityProperty { Name = string.Empty, Value = value };
}
/// <summary>Copy construct un-named EntityProperty from Int64.</summary>
/// <param name="value">The value as Int64.</param>
/// <returns>An un-named EntityProperty.</returns>
[SuppressMessage("Microsoft.Usage", "CA2225", Justification = "Not a public API.")]
public static implicit operator EntityProperty(long value)
{
return new EntityProperty { Name = string.Empty, Value = value };
}
/// <summary>Copy construct un-named EntityProperty from double.</summary>
/// <param name="value">The value as double.</param>
/// <returns>An un-named EntityProperty.</returns>
[SuppressMessage("Microsoft.Usage", "CA2225", Justification = "Not a public API.")]
public static implicit operator EntityProperty(double value)
{
return new EntityProperty { Name = string.Empty, Value = value };
}
/// <summary>Copy construct un-named EntityProperty from decimal.</summary>
/// <param name="value">The value as decimal.</param>
/// <returns>An un-named EntityProperty.</returns>
[SuppressMessage("Microsoft.Usage", "CA2225", Justification = "Not a public API.")]
public static implicit operator EntityProperty(decimal value)
{
return new EntityProperty { Name = string.Empty, Value = value };
}
/// <summary>Copy construct un-named EntityProperty from bool.</summary>
/// <param name="value">The value as bool.</param>
/// <returns>An un-named EntityProperty.</returns>
[SuppressMessage("Microsoft.Usage", "CA2225", Justification = "Not a public API.")]
public static implicit operator EntityProperty(bool value)
{
return new EntityProperty { Name = string.Empty, Value = value };
}
/// <summary>Copy construct un-named EntityProperty from Date.</summary>
/// <param name="value">The value as Date.</param>
/// <returns>An un-named EntityProperty.</returns>
[SuppressMessage("Microsoft.Usage", "CA2225", Justification = "Not a public API.")]
public static implicit operator EntityProperty(DateTime value)
{
return new EntityProperty { Name = string.Empty, Value = value };
}
/// <summary>Copy construct un-named EntityProperty from Guid.</summary>
/// <param name="value">The value as Guid.</param>
/// <returns>An un-named EntityProperty.</returns>
[SuppressMessage("Microsoft.Usage", "CA2225", Justification = "Not a public API.")]
public static implicit operator EntityProperty(Guid value)
{
return new EntityProperty { Name = string.Empty, Value = value };
}
/// <summary>Copy construct un-named EntityProperty from EntityId.</summary>
/// <param name="value">The value as EntityId.</param>
/// <returns>An un-named EntityProperty.</returns>
[SuppressMessage("Microsoft.Usage", "CA2225", Justification = "Not a public API.")]
public static implicit operator EntityProperty(EntityId value)
{
return new EntityProperty { Name = string.Empty, Value = value };
}
/// <summary>Copy construct un-named EntityProperty from Binary.</summary>
/// <param name="value">The value as Binary.</param>
/// <returns>An un-named EntityProperty.</returns>
[SuppressMessage("Microsoft.Usage", "CA2225", Justification = "Not a public API.")]
public static implicit operator EntityProperty(byte[] value)
{
return new EntityProperty { Name = string.Empty, Value = value };
}
////
// Cast operators
// Implement the same cast operators as the contained PropertyValue object.
// This allows us to extract the value straight forwardly.
////
/// <summary>Cast value to native string type.</summary>
/// <param name="property">The property.</param>
/// <returns>The property value as native string.</returns>
/// <exception cref="ArgumentException">If requested type does not match defined type.</exception>
[SuppressMessage("Microsoft.Usage", "CA2225", Justification = "Not a public API.")]
public static implicit operator string(EntityProperty property)
{
return CheckAndGetValueAs<string>(property);
}
/// <summary>Cast value to native int type.</summary>
/// <param name="property">The property.</param>
/// <returns>The property value as native int.</returns>
/// <exception cref="ArgumentException">If requested type does not match defined type.</exception>
[SuppressMessage("Microsoft.Usage", "CA2225", Justification = "Not a public API.")]
public static implicit operator int(EntityProperty property)
{
return CheckAndGetValueAs<int>(property);
}
/// <summary>Cast value to native long type.</summary>
/// <param name="property">The property.</param>
/// <returns>The property value as native long.</returns>
/// <exception cref="ArgumentException">If requested type does not match defined type.</exception>
[SuppressMessage("Microsoft.Usage", "CA2225", Justification = "Not a public API.")]
public static implicit operator long(EntityProperty property)
{
return CheckAndGetValueAs<long>(property);
}
/// <summary>Cast value to native double type.</summary>
/// <param name="property">The property.</param>
/// <returns>The property value as native double.</returns>
/// <exception cref="ArgumentException">If requested type does not match defined type.</exception>
[SuppressMessage("Microsoft.Usage", "CA2225", Justification = "Not a public API.")]
public static implicit operator double(EntityProperty property)
{
return CheckAndGetValueAs<double>(property);
}
/// <summary>Cast value to native decimal type.</summary>
/// <param name="property">The property.</param>
/// <returns>The property value as native decimal.</returns>
/// <exception cref="ArgumentException">If requested type does not match defined type.</exception>
[SuppressMessage("Microsoft.Usage", "CA2225", Justification = "Not a public API.")]
public static implicit operator decimal(EntityProperty property)
{
return CheckAndGetValueAs<decimal>(property);
}
/// <summary>Cast value to native DateTime type.</summary>
/// <param name="property">The property.</param>
/// <returns>The property value as native DateTime.</returns>
/// <exception cref="ArgumentException">If requested type does not match defined type.</exception>
[SuppressMessage("Microsoft.Usage", "CA2225", Justification = "Not a public API.")]
public static implicit operator DateTime(EntityProperty property)
{
return CheckAndGetValueAs<DateTime>(property);
}
/// <summary>Cast value to native bool type.</summary>
/// <param name="property">The property.</param>
/// <returns>The property value as native bool.</returns>
/// <exception cref="ArgumentException">If requested type does not match defined type.</exception>
[SuppressMessage("Microsoft.Usage", "CA2225", Justification = "Not a public API.")]
public static implicit operator bool(EntityProperty property)
{
return CheckAndGetValueAs<bool>(property);
}
/// <summary>Cast value to native Guid type.</summary>
/// <param name="property">The property.</param>
/// <returns>The property value as native Guid.</returns>
/// <exception cref="ArgumentException">If requested type does not match defined type.</exception>
[SuppressMessage("Microsoft.Usage", "CA2225", Justification = "Not a public API.")]
public static implicit operator Guid(EntityProperty property)
{
return CheckAndGetValueAs<Guid>(property);
}
/// <summary>Cast value to EntityId type. PropertyType of valeu must be PropertyType.Guid</summary>
/// <param name="property">The property.</param>
/// <returns>The property value as EntityId.</returns>
/// <exception cref="ArgumentException">If requested type does not match defined type.</exception>
[SuppressMessage("Microsoft.Usage", "CA2225", Justification = "Not a public API.")]
public static implicit operator EntityId(EntityProperty property)
{
return CheckAndGetValueAs<EntityId>(property);
}
/// <summary>Cast value to native byte[] type.</summary>
/// <param name="property">The property.</param>
/// <returns>The property value as native byte[].</returns>
/// <exception cref="ArgumentException">If requested type does not match defined type.</exception>
[SuppressMessage("Microsoft.Usage", "CA2225", Justification = "Not a public API.")]
public static implicit operator byte[](EntityProperty property)
{
return CheckAndGetValueAs<byte[]>(property);
}
////
// Begin Equality Operators
////
/// <summary>Equality operator override.</summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>True if equal.</returns>
public static bool operator ==(EntityProperty left, EntityProperty right)
{
return Equals(left, right);
}
/// <summary>Inequality operator override.</summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>True if not equal.</returns>
public static bool operator !=(EntityProperty left, EntityProperty right)
{
return !Equals(left, right);
}
/// <summary>Equals method override.</summary>
/// <param name="other">The other EntityProperty object being equated.</param>
/// <returns>True if equal.</returns>
public bool Equals(EntityProperty other)
{
// Degenerate cases
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
// Test based on member name and value
return Equals(other.Value, this.Value) && Equals(other.Name, this.Name);
}
/// <summary>Equals method override for generic object.</summary>
/// <param name="obj">The other object being equated.</param>
/// <returns>True if equal.</returns>
public override bool Equals(object obj)
{
// Degenerate cases
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() == typeof(EntityProperty))
{
// Defer to typed Equals
return this.Equals((EntityProperty)obj);
}
// Allow comparison to an object that has a PropertyValue constructor
// available. Compare on the basis of value only, not name.
return Equals(TryConvertToPropertyValue(obj), this.Value);
}
/// <summary>Hash function for EntityProperty type.</summary>
/// <returns>A hash code based on the member values.</returns>
public override int GetHashCode()
{
unchecked
{
// (* 397 is just an arbitrary distribution function)
return ((this.Name != null ? this.Name.GetHashCode() : 0) * 397) ^ (this.Value != null ? this.Value.GetHashCode() : 0);
}
}
////
// End Equality Operators
////
/// <summary>ToString override.</summary>
/// <returns>String serialized representation of value.</returns>
public override string ToString()
{
return this.Value.ToString();
}
/// <summary>Get the underlying value as type T. Delegate null handling to PropertyValue</summary>
/// <typeparam name="T">The type to attempt to get.</typeparam>
/// <param name="property">The EntityProperty object.</param>
/// <returns>A value of type T if successful.</returns>
/// <exception cref="ArgumentException">Throws if coercion is not possible.</exception>
private static T CheckAndGetValueAs<T>(EntityProperty property)
{
// Defer null handling to PropertyValue
return PropertyValue.CheckAndGetValueAs<T>(property != null ? property.Value : null);
}
/// <summary>Convert an object to a PropertyValue if possible.</summary>
/// <param name="obj">The object to convert.</param>
/// <returns>The property value or null.</returns>
[SuppressMessage("Microsoft.Design", "CA1031", Justification = "Try pattern.")]
private static PropertyValue TryConvertToPropertyValue(object obj)
{
if (obj == null)
{
return null;
}
try
{
return ObjectConversionMap[obj.GetType()](obj);
}
catch (Exception)
{
return null;
}
}
}
}
| 45.798186 | 135 | 0.601376 | [
"Apache-2.0"
] | chinnurtb/OpenAdStack | DataAccessCommon/DataAccessLayer/EntityProperty.cs | 20,197 | C# |
namespace GetFile
{
class Program
{
static void Main()
{
string urlAddress = "http://2016.eicar.org/download/eicar.com";
System.Net.WebClient client = new System.Net.WebClient();
client.DownloadFile(urlAddress, @"eicar.com");
}
}
}
| 23.384615 | 75 | 0.5625 | [
"Unlicense"
] | AlexJPawlak/PSBits | WinDefend/getfile.cs | 304 | C# |
using System;
using Microsoft.AspNetCore.Builder;
namespace LimitsMiddleware.Extensions
{
public static partial class ApplicationBuilderExtensions
{
/// <summary>
/// Sets a minimum delay in miliseconds before sending the response.
/// </summary>
/// <param name="app">The IApplicationBuilder instance.</param>
/// <param name="minDelay">
/// The minimum delay to wait before sending the response.
/// </param>
/// <param name="loggerName">(Optional) The name of the logger log messages are written to.</param>
/// <returns>The IApplicationBuilder instance.</returns>
public static IApplicationBuilder MinResponseDelay(this IApplicationBuilder app, int minDelay, string loggerName = null)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
return MinResponseDelay(app, () => minDelay, loggerName);
}
/// <summary>
/// Sets a minimum delay before sending the response.
/// </summary>
/// <param name="app">The IApplicationBuilder instance.</param>
/// <param name="getMinDelay">
/// A delegate to retrieve the maximum number of bytes per second to be transferred.
/// Allows you to supply different values at runtime. Use 0 or a negative number to specify infinite bandwidth.
/// </param>
/// <param name="loggerName">(Optional) The name of the logger log messages are written to.</param>
/// <returns>The IApplicationBuilder instance.</returns>
public static IApplicationBuilder MinResponseDelay(this IApplicationBuilder app, Func<int> getMinDelay, string loggerName = null)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (getMinDelay == null)
{
throw new ArgumentNullException(nameof(getMinDelay));
}
app.Use(Limits.MinResponseDelay(getMinDelay, loggerName));
return app;
}
/// <summary>
/// Sets a minimum delay before sending the response.
/// </summary>
/// <param name="app">The IApplicationBuilder instance.</param>
/// <param name="getMinDelay">
/// A delegate to retrieve the minimum delay before calling the next stage in the pipeline. Note:
/// the delegate should return quickly.
/// </param>
/// <param name="loggerName">(Optional) The name of the logger log messages are written to.</param>
/// <returns>The IApplicationBuilder instance.</returns>
public static IApplicationBuilder MinResponseDelay(this IApplicationBuilder app, Func<TimeSpan> getMinDelay, string loggerName = null)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (getMinDelay == null)
{
throw new ArgumentNullException(nameof(getMinDelay));
}
app.Use(Limits.MinResponseDelay(getMinDelay, loggerName));
return app;
}
/// <summary>
/// Sets a minimum delay before sending the response.
/// </summary>
/// <param name="app">The IApplicationBuilder instance.</param>
/// <param name="getMinDelay">
/// A delegate to retrieve the minimum delay before calling the next stage in the pipeline. Note:
/// the delegate should return quickly.
/// </param>
/// <param name="loggerName">(Optional) The name of the logger log messages are written to.</param>
/// <returns>The IApplicationBuilder instance.</returns>
public static IApplicationBuilder MinResponseDelay(this IApplicationBuilder app, Func<RequestContext, TimeSpan> getMinDelay, string loggerName = null)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (getMinDelay == null)
{
throw new ArgumentNullException(nameof(getMinDelay));
}
app.Use(Limits.MinResponseDelay(getMinDelay, loggerName));
return app;
}
}
}
| 42.242718 | 158 | 0.593197 | [
"MIT"
] | JosephWoodward/LimitsMiddleware.aspnetcore | src/LimitsMiddleware.AspNetCore/Extensions/ApplicationBuilderExtensions.MinResponseDelay.cs | 4,353 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Beetle;
using System.Runtime.Remoting;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Net;
using System.Net.Sockets;
namespace ChatRoom.Server
{
class Program
{
static TcpServer mServer = new TcpServer();
static Program mHandler;
static void Main(string[] args)
{
Console.WriteLine(Beetle.LICENSE.GetLICENSE());
mHandler = new Program();
Beetle.Controllers.Controller.Register(mHandler);
Beetle.TcpUtils.Setup("beetle");
try
{
mServer.ChannelConnected += OnConnect;
mServer.ChannelDisposed += OnDisposed;
mServer.Open(9001);
Console.WriteLine("server start");
}
catch (Exception e_)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e_.Message);
}
Console.Read();
}
static void OnConnect(object sender, ChannelEventArgs e)
{
TcpServer.SetKeepAliveValues(e.Channel.Socket, 20000, 5000);
e.Channel.ChannelError += OnError;
e.Channel.SetPackage<Logic.HeadSizePage>();
e.Channel.Package.ReceiveMessage = OnReceive;
e.Channel.BeginReceive();
Console.WriteLine("{0} Connected!", e.Channel.EndPoint);
}
static void OnReceive(Beetle.PacketRecieveMessagerArgs e)
{
Beetle.Controllers.Controller.Invoke(e.Channel, e.Message);
}
static void OnError(object sender, ChannelErrorEventArgs e)
{
Console.WriteLine("error:{0}", e.Exception.Message);
}
static void OnDisposed(object sender, ChannelEventArgs e)
{
Console.WriteLine("{0}{1} disposed!", e.Channel.Name, e.Channel.EndPoint);
Logic.UnRegister ur = new Logic.UnRegister();
ur.User.Name = e.Channel.Name;
ur.User.IP = e.Channel.EndPoint.ToString();
foreach (IChannel item in mServer.GetOnlines())
{
if (item != e.Channel)
item.Send(ur);
}
}
public void _Register(IChannel channel, Logic.Register e)
{
channel.Name = e.Name;
Logic.RegisterResponse response = new Logic.RegisterResponse();
channel.Send(response);
Logic.OnRegister onreg = new Logic.OnRegister();
onreg.User = new Logic.UserInfo { Name = e.Name, IP = channel.EndPoint.ToString() };
foreach (IChannel item in mServer.GetOnlines())
{
if (item != channel)
item.Send(onreg);
}
Console.WriteLine("{0} login from {1}", e.Name, channel.EndPoint);
}
public void _Say(IChannel channel, Logic.Say e)
{
e.User.Name = channel.Name;
e.User.IP = channel.EndPoint.ToString();
foreach (IChannel item in mServer.GetOnlines())
{
if (item != channel)
item.Send(e);
}
Console.WriteLine("{0} say", e.User.Name);
}
public void _List(IChannel channel, Logic.ListUsers e)
{
Logic.ListUsersResponse response = new Logic.ListUsersResponse();
foreach (IChannel item in mServer.GetOnlines())
{
if (item != channel)
{
response.Users.Add(new Logic.UserInfo { Name = item.Name, IP = item.EndPoint.ToString() });
}
}
channel.Send(response);
}
}
}
| 33.347826 | 111 | 0.550196 | [
"MIT"
] | corefan/IKendeLib | BeetleDemo/Examples/ChatRoom/ChatRoom.Server/ChatRoom.Server/Program.cs | 3,837 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Management.Automation;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Model;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Properties;
namespace Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS
{
[Cmdlet(VerbsCommon.Remove, PublicIPNoun), OutputType(typeof(IPersistentVM))]
public class RemoveAzurePublicIPCommand : VirtualMachineConfigurationCmdletBase
{
[Parameter(Position = 1, HelpMessage = "The Public IP Name.")]
[ValidateNotNullOrEmpty]
public string PublicIPName { get; set; }
protected override void ProcessRecord()
{
base.ProcessRecord();
var networkConfiguration = GetNetworkConfiguration();
if (networkConfiguration == null)
{
throw new ArgumentOutOfRangeException(Resources.NetworkConfigurationNotFoundOnPersistentVM);
}
if (string.IsNullOrEmpty(this.PublicIPName))
{
networkConfiguration.PublicIPs = null;
}
else if (networkConfiguration.PublicIPs != null)
{
networkConfiguration.PublicIPs.RemoveAll(
e => string.Equals(e.Name, this.PublicIPName, StringComparison.OrdinalIgnoreCase));
}
WriteObject(VM, true);
}
}
}
| 40.981132 | 109 | 0.615562 | [
"MIT"
] | Andrean/azure-powershell | src/ServiceManagement/Compute/Commands.ServiceManagement/IaaS/Network/RemoveAzurePublicIP.cs | 2,122 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Extensions.FileProviders;
using ApacheOrcDotNet.Infrastructure;
namespace ApacheOrcDotNet.Test.TestHelpers
{
public class DataFileHelper : IDisposable
{
readonly Stream _dataStream;
public DataFileHelper(string dataFileName)
{
var embeddedFileName = $"Data.{dataFileName}";
var fileProvider = new EmbeddedFileProvider(typeof(DataFileHelper).GetTypeInfo().Assembly);
var fileInfo = fileProvider.GetFileInfo(embeddedFileName);
if (!fileInfo.Exists)
throw new ArgumentException("Requested data file doesn't exist");
_dataStream = fileInfo.CreateReadStream();
}
public DataFileHelper(Stream inputStream)
{
_dataStream = inputStream;
}
public void Dispose()
{
_dataStream.Dispose();
}
public long Length => _dataStream.Length;
public byte[] Read(long fileOffset, int length)
{
var buffer = new byte[length];
_dataStream.Seek(fileOffset, SeekOrigin.Begin);
var readLen = _dataStream.Read(buffer, 0, length);
if (readLen != length)
throw new InvalidOperationException("Read returned less data than requested");
return buffer;
}
public Stream GetStreamSegment(long fileOffset, ulong length)
{
_dataStream.Seek(fileOffset, SeekOrigin.Begin);
return new StreamSegment(_dataStream, (long)length, true);
}
public Stream GetStream()
{
return _dataStream;
}
}
}
| 24.836066 | 94 | 0.741914 | [
"MIT"
] | ddrinka/ApacheOrcDotNet | test/ApacheOrcDotNet.Test/TestHelpers/DataFileHelper.cs | 1,517 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using WmiFramework.Assistant.Components;
using WmiFramework.Assistant.Models;
namespace WmiFramework.Assistant.UserInterface
{
public partial class FormExplorer : Form
{
private WmiHelper wmiHelper;
private UIContext uiContext;
public FormExplorer(UIContext uiContext)
{
InitializeComponent();
TopLevel = false;
Dock = DockStyle.Fill;
wmiHelper = new WmiHelper();
this.uiContext = uiContext;
Visible = true;
}
private void FormExplorer_Load(object sender, EventArgs e)
{
uiContext.ShowLoading();
ThreadPool.QueueUserWorkItem(obj =>
{
foreach (var item in wmiHelper.GetNamespacesSet())
{
Invoke(new Action(() => { listBoxNamespaces.Items.Add(item); }));
}
uiContext.HideLoading();
});
}
private void listBoxNamespaces_SelectedIndexChanged(object sender, EventArgs e)
{
uiContext.ShowLoading();
listBoxClasses.Items.Clear();
ThreadPool.QueueUserWorkItem(obj =>
{
string scope = Invoke(new Func<object>(() => listBoxNamespaces.SelectedItem)) as string;
foreach (var item in wmiHelper.GetClassSet(scope))
{
Invoke(new Action(() => { listBoxClasses.Items.Add(item); }));
}
uiContext.HideLoading();
});
}
private void listBoxClasses_SelectedIndexChanged(object sender, EventArgs e)
{
listViewProperties.Items.Clear();
//textBoxNamespaces.Text = listBoxNamespaces.SelectedItem as string;
//textBoxClasses.Text = listBoxClasses.SelectedItem as string;
var wmiClasses = wmiHelper.GetClass(listBoxNamespaces.SelectedItem as string, listBoxClasses.SelectedItem as string);
textBoxNamespaces.Text = wmiClasses.Namespace;
textBoxClasses.Text = wmiClasses.Name;
textBoxDescription.Text = wmiClasses.Description.Replace("\n", "\r\n");
listViewProperties.Items.AddRange(wmiClasses.Properties.Select(c => new ListViewItem(new string[] { "属性", c.Name, c.Description }) { Tag = c }).ToArray());
listViewProperties.Items.AddRange(wmiClasses.Methods.Select(c => new ListViewItem(new string[] { "方法", c.Name, c.Description }) { Tag = c }).ToArray());
}
private void listViewProperties_MouseLeave(object sender, EventArgs e)
{
toolTip.Hide(listViewProperties);
}
private void listViewProperties_MouseMove(object sender, MouseEventArgs e)
{
var item = listViewProperties.GetItemAt(e.X, e.Y);
if (item == null)
return;
var sb = new StringBuilder();
if (item.Tag is Property property)
{
sb.AppendFormat("属性名:{0}\r\n", property.Name);
sb.AppendFormat("描述:{0}", property.Description);
}
else if (item.Tag is Method method)
{
sb.AppendFormat("方法名:{0}\r\n", method.Name);
sb.AppendFormat("描述:{0}", method.Description);
}
else
return;
toolTip.Show(sb.ToString(), listViewProperties, e.X, e.Y + 20);
}
private void listViewProperties_DoubleClick(object sender, EventArgs e)
{
var item = listViewProperties.SelectedItems.Count > 0 ? listViewProperties.SelectedItems[0] : null;
if (item.Tag is Property property)
{
using (var form = new FormProperty(property))
form.ShowDialog();
}
else if (item.Tag is Method method)
{
using (var form = new FormMethod(method))
form.ShowDialog();
}
}
private void buttonQuery_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(listBoxNamespaces.Text) || string.IsNullOrEmpty(listBoxClasses.Text))
{
MessageBox.Show("请先选择类", "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
uiContext.SwitchForm(typeof(FormQuery).Name, listBoxNamespaces.Text, $"select * from {listBoxClasses.Text}");
}
private void buttonCodeBuilder_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(listBoxNamespaces.Text) || string.IsNullOrEmpty(listBoxClasses.Text))
{
MessageBox.Show("请先选择类", "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
uiContext.SwitchForm(typeof(FormCodeBuilder).Name, listBoxNamespaces.Text, listBoxClasses.Text);
}
}
}
| 37.158273 | 167 | 0.583349 | [
"Apache-2.0"
] | gugu2234/WmiFramework | WmiFramework.Assistant/UserInterface/FormExplorer.cs | 5,239 | C# |
using org.mariuszgromada.math.mxparser;
using org.mariuszgromada.math.mxparser.mathcollection;
using org.mariuszgromada.math.mxparser.regressiontesting;
using System;
namespace mxparser.runtests {
class RunTestsWorking {
static void Main(string[] args) {
/*
mXparser.disableUlpRounding();
String expStr = "sum(n, 0, 10, if ( if( sin(n*pi/2) > 0, 1, 2) >= 2, 4, 2) )";
Expression ee = new Expression(expStr);
ee.setVerboseMode();
double a = ee.calculate();
mXparser.consolePrintln(a);
mXparser.consolePrintln(MathFunctions.ulp(6.28318530717959));
mXparser.consolePrintln(MathFunctions.ulpDecimalDigitsBefore(6.28318530717959));
mXparser.consolePrintln(MathFunctions.round(6.28318530717959, 13));
*/
Expression e = new Expression("Name==Me && Age>18 || City== NewYork");
mXparser.consolePrintTokens(e.getCopyOfInitialTokens());
}
}
}
| 35.16 | 83 | 0.7281 | [
"BSD-2-Clause"
] | ARLM-Attic/mxparser | CURRENT/c-sharp/exe-lib-tests/Run-Tests-Working/RunTestsWorking.cs | 881 | C# |
using System;
using System.Reflection;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.InteropExtension;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Rhino;
using Rhino.Geometry;
using Rhino.FileIO;
using Rhino.DocObjects;
using RhinoInside.Revit.UI;
#if REVIT_2018
using Autodesk.Revit.DB.Visual;
#else
using Autodesk.Revit.Utility;
#endif
namespace RhinoInside.Revit.Samples
{
[Transaction(TransactionMode.Manual), Regeneration(RegenerationOption.Manual)]
public class Sample8 : RhinoCommand
{
public static void CreateUI(RibbonPanel ribbonPanel)
{
var buttonData = NewPushButtonData<Sample8, NeedsActiveDocument<Availability>>("Sample 8");
if (ribbonPanel.AddItem(buttonData) is PushButton pushButton)
{
pushButton.ToolTip = "Imports geometry from 3dm file to a Revit model or family";
pushButton.Image = ImageBuilder.BuildImage("8");
pushButton.LargeImage = ImageBuilder.BuildLargeImage("8");
pushButton.SetContextualHelp(new ContextualHelp(ContextualHelpType.Url, "https://github.com/mcneel/rhino.inside-revit/tree/master#sample-8"));
}
}
static string ByteArrayToString(byte[] data)
{
var hex = new StringBuilder(data.Length * 2);
for (int i = 0; i < data.Length; i++)
hex.Append(data[i].ToString("X2"));
return hex.ToString();
}
public static Dictionary<string, Autodesk.Revit.DB.Material> GetMaterialsByName(Document doc)
{
var collector = new FilteredElementCollector(doc);
return collector.OfClass(typeof(Autodesk.Revit.DB.Material)).OfType<Autodesk.Revit.DB.Material>().
GroupBy(x => x.Name).
ToDictionary(x => x.Key, x => x.First());
}
static string GenericAssetName(Autodesk.Revit.ApplicationServices.LanguageType language)
{
switch (language)
{
case Autodesk.Revit.ApplicationServices.LanguageType.English_USA: return "Generic";
case Autodesk.Revit.ApplicationServices.LanguageType.German: return "Generisch";
case Autodesk.Revit.ApplicationServices.LanguageType.Spanish: return "Genérico";
case Autodesk.Revit.ApplicationServices.LanguageType.French: return "Générique";
case Autodesk.Revit.ApplicationServices.LanguageType.Italian: return "Generico";
case Autodesk.Revit.ApplicationServices.LanguageType.Dutch: return "Allgemeine";
case Autodesk.Revit.ApplicationServices.LanguageType.Chinese_Simplified: return "常规";
case Autodesk.Revit.ApplicationServices.LanguageType.Chinese_Traditional: return "常規";
case Autodesk.Revit.ApplicationServices.LanguageType.Japanese: return "一般";
case Autodesk.Revit.ApplicationServices.LanguageType.Korean: return "일반";
case Autodesk.Revit.ApplicationServices.LanguageType.Russian: return "общий";
case Autodesk.Revit.ApplicationServices.LanguageType.Czech: return "Obecný";
case Autodesk.Revit.ApplicationServices.LanguageType.Polish: return "Rodzajowy";
case Autodesk.Revit.ApplicationServices.LanguageType.Hungarian: return "Generikus";
case Autodesk.Revit.ApplicationServices.LanguageType.Brazilian_Portuguese: return "Genérico";
#if REVIT_2018
case Autodesk.Revit.ApplicationServices.LanguageType.English_GB: return "Generic";
#endif
}
return null;
}
static string GenericAssetName() => GenericAssetName(Revit.ActiveUIApplication.Application.Language) ?? "Generic";
public static AppearanceAssetElement GetGenericAppearanceAssetElement(Document doc)
{
var applicationLanguage = Revit.ActiveUIApplication.Application.Language;
var languages = Enumerable.Repeat(applicationLanguage, 1).
Concat
(
Enum.GetValues(typeof(Autodesk.Revit.ApplicationServices.LanguageType)).
Cast<Autodesk.Revit.ApplicationServices.LanguageType>().
Where(lang => lang != applicationLanguage && lang != Autodesk.Revit.ApplicationServices.LanguageType.Unknown)
);
foreach (var lang in languages)
{
if (AppearanceAssetElement.GetAppearanceAssetElementByName(doc, GenericAssetName(lang)) is AppearanceAssetElement assetElement)
return assetElement;
}
return null;
}
static ElementId ToHost(Rhino.Render.RenderMaterial mat, Document doc, string name)
{
var appearanceAssetId = ElementId.InvalidElementId;
#if REVIT_2019
if (AppearanceAssetElement.GetAppearanceAssetElementByName(doc, name) is AppearanceAssetElement appearanceAssetElement)
appearanceAssetId = appearanceAssetElement.Id;
else
{
appearanceAssetElement = GetGenericAppearanceAssetElement(doc);
if (appearanceAssetElement is null)
{
var assets = Revit.ActiveUIApplication.Application.GetAssets(AssetType.Appearance);
foreach (var asset in assets)
{
if (asset.Name == GenericAssetName())
{
appearanceAssetElement = AppearanceAssetElement.Create(doc, name, asset);
appearanceAssetId = appearanceAssetElement.Id;
break;
}
}
}
else
{
appearanceAssetElement = appearanceAssetElement.Duplicate(name);
appearanceAssetId = appearanceAssetElement.Id;
}
if (appearanceAssetId != ElementId.InvalidElementId)
{
using (var editScope = new AppearanceAssetEditScope(doc))
{
var editableAsset = editScope.Start(appearanceAssetId);
//var category = editableAsset.FindByName("category") as AssetPropertyString;
//category.Value = $":{mat.Category.FirstCharUpper()}";
var description = editableAsset.FindByName("description") as AssetPropertyString;
description.Value = mat.Notes ?? string.Empty;
var keyword = editableAsset.FindByName("keyword") as AssetPropertyString;
{
string tags = string.Empty;
foreach (var tag in (mat.Tags ?? string.Empty).Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
tags += $":{tag.Replace(':', ';')}";
keyword.Value = tags;
}
if (mat.SmellsLikeMetal || mat.SmellsLikeTexturedMetal)
{
var generic_self_illum_luminance = editableAsset.FindByName(Generic.GenericIsMetal) as AssetPropertyBoolean;
generic_self_illum_luminance.Value = true;
}
if (mat.Fields.TryGetValue(Rhino.Render.RenderMaterial.BasicMaterialParameterNames.Diffuse, out Rhino.Display.Color4f diffuse))
{
var generic_diffuse = editableAsset.FindByName(Generic.GenericDiffuse) as AssetPropertyDoubleArray4d;
generic_diffuse.SetValueAsDoubles(new double[] { diffuse.R, diffuse.G, diffuse.B, diffuse.A });
}
if (mat.Fields.TryGetValue(Rhino.Render.RenderMaterial.BasicMaterialParameterNames.Transparency, out double transparency))
{
var generic_transparency = editableAsset.FindByName(Generic.GenericTransparency) as AssetPropertyDouble;
generic_transparency.Value = transparency;
if (mat.Fields.TryGetValue(Rhino.Render.RenderMaterial.BasicMaterialParameterNames.TransparencyColor, out Rhino.Display.Color4f transparencyColor))
{
diffuse = diffuse.BlendTo((float) transparency, transparencyColor);
var generic_diffuse = editableAsset.FindByName(Generic.GenericDiffuse) as AssetPropertyDoubleArray4d;
generic_diffuse.SetValueAsDoubles(new double[] { diffuse.R, diffuse.G, diffuse.B, diffuse.A });
}
}
if (mat.Fields.TryGetValue(Rhino.Render.RenderMaterial.BasicMaterialParameterNames.Ior, out double ior))
{
var generic_refraction_index = editableAsset.FindByName(Generic.GenericRefractionIndex) as AssetPropertyDouble;
generic_refraction_index.Value = ior;
}
if (mat.Fields.TryGetValue(Rhino.Render.RenderMaterial.BasicMaterialParameterNames.Shine, out double shine))
{
if (mat.Fields.TryGetValue(Rhino.Render.RenderMaterial.BasicMaterialParameterNames.Specular, out Rhino.Display.Color4f specularColor))
{
var generic_reflectivity_at_0deg = editableAsset.FindByName(Generic.GenericReflectivityAt0deg) as AssetPropertyDouble;
generic_reflectivity_at_0deg.Value = shine * specularColor.L;
}
}
if (mat.Fields.TryGetValue(Rhino.Render.RenderMaterial.BasicMaterialParameterNames.Reflectivity, out double reflectivity))
{
if (mat.Fields.TryGetValue(Rhino.Render.RenderMaterial.BasicMaterialParameterNames.ReflectivityColor, out Rhino.Display.Color4f reflectivityColor))
{
var generic_reflectivity_at_90deg = editableAsset.FindByName(Generic.GenericReflectivityAt90deg) as AssetPropertyDouble;
generic_reflectivity_at_90deg.Value = reflectivity * reflectivityColor.L;
if (mat.Fields.TryGetValue("fresnel-enabled", out bool fresnel_enabled) && !fresnel_enabled)
{
diffuse = diffuse.BlendTo((float) reflectivity, reflectivityColor);
var generic_diffuse = editableAsset.FindByName(Generic.GenericDiffuse) as AssetPropertyDoubleArray4d;
generic_diffuse.SetValueAsDoubles(new double[] { diffuse.R, diffuse.G, diffuse.B, diffuse.A });
}
}
}
if (mat.Fields.TryGetValue("polish-amount", out double polish_amount))
{
var generic_glossiness = editableAsset.FindByName(Generic.GenericGlossiness) as AssetPropertyDouble;
generic_glossiness.Value = polish_amount;
}
if (mat.Fields.TryGetValue(Rhino.Render.RenderMaterial.BasicMaterialParameterNames.Emission, out Rhino.Display.Color4f emission))
{
var generic_self_illum_filter_map = editableAsset.FindByName(Generic.GenericSelfIllumFilterMap) as AssetPropertyDoubleArray4d;
generic_self_illum_filter_map.SetValueAsDoubles(new double[] { emission.R, emission.G, emission.B, emission.A });
}
if (mat.Fields.TryGetValue(Rhino.Render.RenderMaterial.BasicMaterialParameterNames.DisableLighting, out bool self_illum))
{
var generic_self_illum_luminance = editableAsset.FindByName(Generic.GenericSelfIllumLuminance) as AssetPropertyDouble;
generic_self_illum_luminance.Value = self_illum ? 200000 : 0.0;
}
editScope.Commit(false);
}
}
}
#endif
return appearanceAssetId;
}
static ElementId ToHost(Rhino.DocObjects.Material mat, Document doc, Dictionary<string, Autodesk.Revit.DB.Material> materials)
{
var id = ElementId.InvalidElementId;
if(mat.HasName)
{
var matName = mat.Name;
if (materials.TryGetValue(matName, out var material)) id = material.Id;
else
{
id = Autodesk.Revit.DB.Material.Create(doc, matName);
var newMaterial = doc.GetElement(id) as Autodesk.Revit.DB.Material;
newMaterial.Color = mat.PreviewColor.ToHost();
newMaterial.Shininess = (int) Math.Round(mat.Shine / Rhino.DocObjects.Material.MaxShine * 128.0);
newMaterial.Smoothness = (int) Math.Round(mat.Reflectivity * 100.0);
newMaterial.Transparency = (int) Math.Round(mat.Transparency * 100.0);
newMaterial.AppearanceAssetId = ToHost(mat.RenderMaterial, doc, matName);
materials.Add(matName, newMaterial);
}
}
return id;
}
static IList<GeometryObject> ImportObject(File3dm model, GeometryBase geometry, ObjectAttributes attributes, Document doc, Dictionary<string, Autodesk.Revit.DB.Material> materials, double scaleFactor)
{
var layer = model.AllLayers.FindIndex(attributes.LayerIndex);
if (layer?.IsVisible ?? false)
{
using (var ctx = Convert.Context.Push())
{
switch (attributes.MaterialSource)
{
case ObjectMaterialSource.MaterialFromObject:
{
var modelMaterial = attributes.MaterialIndex < 0 ? Rhino.DocObjects.Material.DefaultMaterial : model.AllMaterials.FindIndex(attributes.MaterialIndex);
ctx.MaterialId = ToHost(modelMaterial, doc, materials);
break;
}
case ObjectMaterialSource.MaterialFromLayer:
{
var modelLayer = model.AllLayers.FindIndex(attributes.LayerIndex);
var modelMaterial = modelLayer.RenderMaterialIndex < 0 ? Rhino.DocObjects.Material.DefaultMaterial : model.AllMaterials.FindIndex(modelLayer.RenderMaterialIndex);
ctx.MaterialId = ToHost(modelMaterial, doc, materials);
break;
}
}
if (geometry is InstanceReferenceGeometry instance)
{
if (model.AllInstanceDefinitions.FindId(instance.ParentIdefId) is InstanceDefinitionGeometry definition)
{
var definitionId = definition.Id.ToString();
var library = DirectShapeLibrary.GetDirectShapeLibrary(doc);
if (!library.Contains(definitionId))
{
var objectIds = definition.GetObjectIds();
var GNodes = objectIds.
Select(x => model.Objects.FindId(x)).
Cast<File3dmObject>().
SelectMany(x => ImportObject(model, x.Geometry, x.Attributes, doc, materials, scaleFactor));
library.AddDefinition(definitionId, GNodes.ToArray());
}
var xform = instance.Xform.ChangeUnits(scaleFactor);
return DirectShape.CreateGeometryInstance(doc, definitionId, xform.ToHost());
}
}
else return geometry.ToHostMultiple(scaleFactor).ToList();
}
}
return new GeometryObject[0];
}
public static Result Import3DMFile(string filePath, Document doc, BuiltInCategory builtInCategory)
{
try
{
DirectShapeLibrary.GetDirectShapeLibrary(doc).Reset();
using (var model = File3dm.Read(filePath))
{
var scaleFactor = RhinoMath.UnitScale(model.Settings.ModelUnitSystem, Revit.ModelUnitSystem);
using (var trans = new Transaction(doc, "Import 3D Model"))
{
if (trans.Start() == TransactionStatus.Started)
{
var categoryId = new ElementId(builtInCategory);
var materials = GetMaterialsByName(doc);
var type = DirectShapeType.Create(doc, Path.GetFileName(filePath), categoryId);
foreach (var obj in model.Objects.Where(x => !x.Attributes.IsInstanceDefinitionObject && x.Attributes.Space == ActiveSpace.ModelSpace))
{
if (!obj.Attributes.Visible)
continue;
var geometryList = ImportObject(model, obj.Geometry, obj.Attributes, doc, materials, scaleFactor).ToArray();
if (geometryList == null)
continue;
try { type.AppendShape(geometryList); }
catch (Autodesk.Revit.Exceptions.ArgumentException) { }
}
var ds = DirectShape.CreateElement(doc, type.Category.Id);
ds.SetTypeId(type.Id);
var library = DirectShapeLibrary.GetDirectShapeLibrary(doc);
if (!library.ContainsType(type.UniqueId))
library.AddDefinitionType(type.UniqueId, type.Id);
ds.SetShape(DirectShape.CreateGeometryInstance(doc, type.UniqueId, Autodesk.Revit.DB.Transform.Identity));
if (trans.Commit() == TransactionStatus.Committed)
{
var elements = new ElementId[] { ds.Id };
Revit.ActiveUIDocument.Selection.SetElementIds(elements);
Revit.ActiveUIDocument.ShowElements(elements);
return Result.Succeeded;
}
}
}
}
}
finally
{
DirectShapeLibrary.GetDirectShapeLibrary(doc).Reset();
}
return Result.Failed;
}
public override Result Execute(ExternalCommandData data, ref string message, ElementSet elements)
{
if(!DirectShape.IsSupportedDocument(data.Application.ActiveUIDocument.Document))
{
message = "Active document can't support DirectShape functionality.";
return Result.Failed;
}
using
(
var openFileDialog = new OpenFileDialog()
{
Filter = "Rhino 3D models (*.3dm)|*.3dm",
FilterIndex = 1,
RestoreDirectory = true
}
)
{
switch (openFileDialog.ShowDialog(Revit.MainWindowHandle))
{
case DialogResult.OK:
return Import3DMFile
(
openFileDialog.FileName,
data.Application.ActiveUIDocument.Document,
CommandGrasshopperBake.ActiveBuiltInCategory
);
case DialogResult.Cancel: return Result.Cancelled;
}
}
return Result.Failed;
}
}
}
| 42.700957 | 204 | 0.650513 | [
"MIT"
] | JTMBarry/rhino.inside-revit | src/RhinoInside.Revit/Samples/Sample8.cs | 17,875 | C# |
namespace AngleSharp.Xml
{
using AngleSharp.Dom;
using System;
using System.Collections.Generic;
/// <summary>
/// Represents the list of all Xml entities.
/// </summary>
public sealed class XmlEntityProvider : IEntityProvider
{
#region Fields
private readonly Dictionary<String, String> _entities = new Dictionary<String, String>
{
{ "amp;", "&" },
{ "lt;", "<" },
{ "gt;", ">" },
{ "apos;", "'" },
{ "quot;", "\"" },
};
#endregion
#region Instance
/// <summary>
/// Gets the instance to resolve entities.
/// </summary>
public static readonly IEntityProvider Resolver = new XmlEntityProvider();
#endregion
#region ctor
private XmlEntityProvider()
{
}
#endregion
#region Methods
/// <summary>
/// Gets a symbol specified by its entity name.
/// </summary>
/// <param name="name">The name of the entity in the XML code.</param>
/// <returns>The string with the symbol or null.</returns>
public String GetSymbol(String name)
{
var symbol = String.Empty;
if (!String.IsNullOrEmpty(name))
{
_entities.TryGetValue(name, out symbol);
}
return symbol;
}
#endregion
}
}
| 22.765625 | 94 | 0.507893 | [
"MIT"
] | AngleSharp/AngleSharp.Xml | src/AngleSharp.Xml/XmlEntityProvider.cs | 1,457 | C# |
using System.Runtime.Serialization;
namespace I8Beef.Ecobee.Protocol.Objects
{
[DataContract]
public class LimitSetting
{
/// <summary>
/// The value of the limit to set. For temperatures the value is expressed as degrees
/// Fahrenheit, multipled by 10. For humidity values are expressed as a percentage
/// from 5 to 95. See here for more information.
/// </summary>
[DataMember(Name = "limit")]
public int Limit { get; set; }
/// <summary>
/// Boolean value representing whether or not alerts/reminders are enabled for this
/// notification type or not.
/// </summary>
[DataMember(Name = "enabled")]
public bool Enabled { get; set; }
/// <summary>
/// The type of notification. Possible values are: lowTemp, highTemp, lowHumidity,
/// highHumidity, auxHeat, auxOutdoor
/// </summary>
[DataMember(Name = "type")]
public string Type { get; set; }
/// <summary>
/// Boolean value representing whether or not alerts/reminders should be sent to the
/// technician/contractor associated with the thermostat.
/// </summary>
[DataMember(Name = "remindTechnician")]
public bool RemindTechnician { get; set; }
}
}
| 35.078947 | 94 | 0.603901 | [
"MIT"
] | k-rol/EcobeeLib | src/I8Beef.Ecobee/Protocol/Objects/LimitSetting.cs | 1,335 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: MethodCollectionPage.cs.tt
namespace Microsoft.Graph
{
/// <summary>
/// The type ReportRootGetSkypeForBusinessParticipantActivityCountsCollectionPage.
/// </summary>
public partial class ReportRootGetSkypeForBusinessParticipantActivityCountsCollectionPage : CollectionPage<SkypeForBusinessParticipantActivityCounts>, IReportRootGetSkypeForBusinessParticipantActivityCountsCollectionPage
{
/// <summary>
/// Gets the next page <see cref="IReportRootGetSkypeForBusinessParticipantActivityCountsRequest"/> instance.
/// </summary>
public IReportRootGetSkypeForBusinessParticipantActivityCountsRequest NextPageRequest { get; private set; }
/// <summary>
/// Initializes the NextPageRequest property.
/// </summary>
public void InitializeNextPageRequest(IBaseClient client, string nextPageLinkString)
{
if (!string.IsNullOrEmpty(nextPageLinkString))
{
this.NextPageRequest = new ReportRootGetSkypeForBusinessParticipantActivityCountsRequest(
nextPageLinkString,
client,
null);
}
}
}
}
| 44.405405 | 224 | 0.628728 | [
"MIT"
] | GeertVL/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/requests/ReportRootGetSkypeForBusinessParticipantActivityCountsCollectionPage.cs | 1,643 | C# |
using System.Data.Entity;
namespace TM.Data
{
public class DbContextFactory<TContext> : IDbContextFactory<TContext>
where TContext : DbContext, new()
{
public TContext CreateDbContext()
{
return new TContext();
}
}
} | 19.923077 | 72 | 0.644788 | [
"MIT"
] | ssh-git/training-manager | src/TM.Data/DbContextFactory.cs | 259 | C# |
/**
* Autogenerated by Thrift Compiler (0.13.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Thrift.Collections;
using Thrift.Protocol;
using Thrift.Protocol.Entities;
using Thrift.Protocol.Utilities;
namespace SparkSqlClient.generated
{
internal partial class TRow : TBase
{
public List<TColumnValue> ColVals { get; set; }
public TRow()
{
}
public TRow(List<TColumnValue> colVals) : this()
{
this.ColVals = colVals;
}
public async Task ReadAsync(TProtocol iprot, CancellationToken cancellationToken)
{
iprot.IncrementRecursionDepth();
try
{
bool isset_colVals = false;
TField field;
await iprot.ReadStructBeginAsync(cancellationToken);
while (true)
{
field = await iprot.ReadFieldBeginAsync(cancellationToken);
if (field.Type == TType.Stop)
{
break;
}
switch (field.ID)
{
case 1:
if (field.Type == TType.List)
{
{
TList _list23 = await iprot.ReadListBeginAsync(cancellationToken);
ColVals = new List<TColumnValue>(_list23.Count);
for(int _i24 = 0; _i24 < _list23.Count; ++_i24)
{
TColumnValue _elem25;
_elem25 = new TColumnValue();
await _elem25.ReadAsync(iprot, cancellationToken);
ColVals.Add(_elem25);
}
await iprot.ReadListEndAsync(cancellationToken);
}
isset_colVals = true;
}
else
{
await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken);
}
break;
default:
await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken);
break;
}
await iprot.ReadFieldEndAsync(cancellationToken);
}
await iprot.ReadStructEndAsync(cancellationToken);
if (!isset_colVals)
{
throw new TProtocolException(TProtocolException.INVALID_DATA);
}
}
finally
{
iprot.DecrementRecursionDepth();
}
}
public async Task WriteAsync(TProtocol oprot, CancellationToken cancellationToken)
{
oprot.IncrementRecursionDepth();
try
{
var struc = new TStruct("TRow");
await oprot.WriteStructBeginAsync(struc, cancellationToken);
var field = new TField();
field.Name = "colVals";
field.Type = TType.List;
field.ID = 1;
await oprot.WriteFieldBeginAsync(field, cancellationToken);
{
await oprot.WriteListBeginAsync(new TList(TType.Struct, ColVals.Count), cancellationToken);
foreach (TColumnValue _iter26 in ColVals)
{
await _iter26.WriteAsync(oprot, cancellationToken);
}
await oprot.WriteListEndAsync(cancellationToken);
}
await oprot.WriteFieldEndAsync(cancellationToken);
await oprot.WriteFieldStopAsync(cancellationToken);
await oprot.WriteStructEndAsync(cancellationToken);
}
finally
{
oprot.DecrementRecursionDepth();
}
}
public override bool Equals(object that)
{
var other = that as TRow;
if (other == null) return false;
if (ReferenceEquals(this, other)) return true;
return TCollections.Equals(ColVals, other.ColVals);
}
public override int GetHashCode() {
int hashcode = 157;
unchecked {
hashcode = (hashcode * 397) + TCollections.GetHashCode(ColVals);
}
return hashcode;
}
public override string ToString()
{
var sb = new StringBuilder("TRow(");
sb.Append(", ColVals: ");
sb.Append(ColVals);
sb.Append(")");
return sb.ToString();
}
}
}
| 34.34 | 111 | 0.465929 | [
"MIT"
] | clearbank/SparkSqlClient | src/SparkSqlClient/generated/TRow.cs | 5,151 | C# |
namespace TeleSharp.TL
{
public abstract class TLAbsInputMedia : TLObject
{
}
}
| 13.142857 | 52 | 0.673913 | [
"MIT"
] | cobra91/TelegramCSharpForward | TeleSharp.TL/TL/TLAbsInputMedia.cs | 92 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Host;
namespace ShaderTools.CodeAnalysis.Host.Mef
{
internal class MefLanguageServices : HostLanguageServices
{
private readonly MefWorkspaceServices _workspaceServices;
private readonly string _language;
private readonly ImmutableArray<Lazy<ILanguageService, LanguageServiceMetadata>> _services;
private ImmutableDictionary<Type, Lazy<ILanguageService, LanguageServiceMetadata>> _serviceMap
= ImmutableDictionary<Type, Lazy<ILanguageService, LanguageServiceMetadata>>.Empty;
public MefLanguageServices(
MefWorkspaceServices workspaceServices,
string language)
{
_workspaceServices = workspaceServices;
_language = language;
var hostServices = workspaceServices.HostExportProvider;
_services = hostServices.GetExports<ILanguageService, LanguageServiceMetadata>()
.Concat(hostServices.GetExports<ILanguageServiceFactory, LanguageServiceMetadata>()
.Select(lz => new Lazy<ILanguageService, LanguageServiceMetadata>(() => lz.Value.CreateLanguageService(this), lz.Metadata)))
.Where(lz => lz.Metadata.Language == language).ToImmutableArray();
}
public override HostWorkspaceServices WorkspaceServices => _workspaceServices;
public override string Language => _language;
public bool HasServices
{
get { return _services.Length > 0; }
}
public override TLanguageService GetService<TLanguageService>()
{
if (TryGetService(typeof(TLanguageService), out var service))
{
return (TLanguageService) service.Value;
}
else
{
return default(TLanguageService);
}
}
internal bool TryGetService(Type serviceType, out Lazy<ILanguageService, LanguageServiceMetadata> service)
{
if (!_serviceMap.TryGetValue(serviceType, out service))
{
service = ImmutableInterlocked.GetOrAdd(ref _serviceMap, serviceType, svctype =>
{
// PERF: Hoist AssemblyQualifiedName out of inner lambda to avoid repeated string allocations.
var assemblyQualifiedName = svctype.AssemblyQualifiedName;
return PickLanguageService(_services.Where(lz => lz.Metadata.ServiceType == assemblyQualifiedName));
});
}
return service != default(Lazy<ILanguageService, LanguageServiceMetadata>);
}
private Lazy<ILanguageService, LanguageServiceMetadata> PickLanguageService(IEnumerable<Lazy<ILanguageService, LanguageServiceMetadata>> services)
{
return services.SingleOrDefault();
}
}
}
| 41 | 165 | 0.637398 | [
"Apache-2.0"
] | BigHeadGift/HLSL | src/ShaderTools.CodeAnalysis.Workspaces/Workspace/Host/Mef/MefLanguageServices.cs | 3,003 | C# |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using PureCloudPlatform.Client.V2.Client;
namespace PureCloudPlatform.Client.V2.Model
{
/// <summary>
/// SessionLastEvent
/// </summary>
[DataContract]
public partial class SessionLastEvent : IEquatable<SessionLastEvent>
{
/// <summary>
/// Initializes a new instance of the <see cref="SessionLastEvent" /> class.
/// </summary>
/// <param name="EventName">The name of the event..</param>
/// <param name="CreatedDate">Timestamp indicating when the event was published. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z.</param>
public SessionLastEvent(string EventName = null, DateTime? CreatedDate = null)
{
this.EventName = EventName;
this.CreatedDate = CreatedDate;
}
/// <summary>
/// The globally unique identifier for the object.
/// </summary>
/// <value>The globally unique identifier for the object.</value>
[DataMember(Name="id", EmitDefaultValue=false)]
public string Id { get; private set; }
/// <summary>
/// The name of the event.
/// </summary>
/// <value>The name of the event.</value>
[DataMember(Name="eventName", EmitDefaultValue=false)]
public string EventName { get; set; }
/// <summary>
/// Timestamp indicating when the event was published. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z
/// </summary>
/// <value>Timestamp indicating when the event was published. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z</value>
[DataMember(Name="createdDate", EmitDefaultValue=false)]
public DateTime? CreatedDate { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class SessionLastEvent {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" EventName: ").Append(EventName).Append("\n");
sb.Append(" CreatedDate: ").Append(CreatedDate).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
Formatting = Formatting.Indented
});
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as SessionLastEvent);
}
/// <summary>
/// Returns true if SessionLastEvent instances are equal
/// </summary>
/// <param name="other">Instance of SessionLastEvent to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(SessionLastEvent other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return true &&
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.EventName == other.EventName ||
this.EventName != null &&
this.EventName.Equals(other.EventName)
) &&
(
this.CreatedDate == other.CreatedDate ||
this.CreatedDate != null &&
this.CreatedDate.Equals(other.CreatedDate)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.EventName != null)
hash = hash * 59 + this.EventName.GetHashCode();
if (this.CreatedDate != null)
hash = hash * 59 + this.CreatedDate.GetHashCode();
return hash;
}
}
}
}
| 32.542857 | 185 | 0.518174 | [
"MIT"
] | F-V-L/platform-client-sdk-dotnet | build/src/PureCloudPlatform.Client.V2/Model/SessionLastEvent.cs | 5,695 | C# |
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System.Collections.Generic;
using System.IO;
using System.Text;
using Xunit;
using YamlDotNet.Core;
using YamlDotNet.RepresentationModel;
namespace YamlDotNet.Test.RepresentationModel
{
#if !PORTABLE && !NETCOREAPP1_0
public class BinarySerlializationTests
{
[Fact]
public void YamlNodeGraphsAreBinarySerializeable()
{
var stream = new YamlStream();
stream.Load(Yaml.StreamFrom("fail-backreference.yaml"));
var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
var memoryStream = new MemoryStream();
formatter.Serialize(memoryStream, stream.Documents[0].RootNode);
memoryStream.Position = 0;
var result = (YamlNode)formatter.Deserialize(memoryStream);
Assert.Equal(stream.Documents[0].RootNode, result);
}
}
#endif
}
| 41.307692 | 98 | 0.706238 | [
"MIT"
] | ForNeVeR/YamlDotNet | YamlDotNet.Test/RepresentationModel/BinarySerlializationTests.cs | 2,150 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Variables
{
class Program
{
static void Main(string[] args)
{
/*
int x;
int y;
x = 7;
y = x + 3;
Console.WriteLine(y);
Console.ReadLine();
*/
Console.WriteLine("What is your name?");
Console.Write("Type your first name: ");
string myFirstName;
myFirstName = Console.ReadLine();
string myLastName;
Console.Write("Type your last name: ");
myLastName = Console.ReadLine();
Console.WriteLine("Hello," + myFirstName + " " + myLastName);
Console.ReadLine();
}
}
}
| 20.634146 | 73 | 0.498818 | [
"MIT"
] | rjohar1/CSharpBeginners | Variables/Variables/Program.cs | 848 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace MigrationsExample.Migrations
{
public partial class NavigationProperties : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "DungeonName",
table: "DungeonRun");
migrationBuilder.DropColumn(
name: "HeroClass",
table: "DungeonRun");
migrationBuilder.AddColumn<int>(
name: "DungeonId",
table: "DungeonRun",
type: "INTEGER",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "HeroId",
table: "DungeonRun",
type: "INTEGER",
nullable: false,
defaultValue: 0);
migrationBuilder.CreateTable(
name: "Dungeon",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Name = table.Column<string>(type: "TEXT", nullable: false),
NumberOfRooms = table.Column<int>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Dungeon", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Hero",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Name = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Hero", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_DungeonRun_DungeonId",
table: "DungeonRun",
column: "DungeonId");
migrationBuilder.CreateIndex(
name: "IX_DungeonRun_HeroId",
table: "DungeonRun",
column: "HeroId");
migrationBuilder.AddForeignKey(
name: "FK_DungeonRun_Dungeon_DungeonId",
table: "DungeonRun",
column: "DungeonId",
principalTable: "Dungeon",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_DungeonRun_Hero_HeroId",
table: "DungeonRun",
column: "HeroId",
principalTable: "Hero",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_DungeonRun_Dungeon_DungeonId",
table: "DungeonRun");
migrationBuilder.DropForeignKey(
name: "FK_DungeonRun_Hero_HeroId",
table: "DungeonRun");
migrationBuilder.DropTable(
name: "Dungeon");
migrationBuilder.DropTable(
name: "Hero");
migrationBuilder.DropIndex(
name: "IX_DungeonRun_DungeonId",
table: "DungeonRun");
migrationBuilder.DropIndex(
name: "IX_DungeonRun_HeroId",
table: "DungeonRun");
migrationBuilder.DropColumn(
name: "DungeonId",
table: "DungeonRun");
migrationBuilder.DropColumn(
name: "HeroId",
table: "DungeonRun");
migrationBuilder.AddColumn<string>(
name: "DungeonName",
table: "DungeonRun",
type: "TEXT",
nullable: false,
defaultValue: "");
migrationBuilder.AddColumn<string>(
name: "HeroClass",
table: "DungeonRun",
type: "TEXT",
nullable: false,
defaultValue: "");
}
}
}
| 32.740741 | 87 | 0.484163 | [
"MIT"
] | V0ldek/Sorcery-CSharp-Notebooks | 06-EntityFramework/MigrationsExample/Migrations/20220511055704_NavigationProperties.cs | 4,422 | C# |
using UnityEngine;
using UnityEngine.EventSystems;
namespace UFZ.UI
{
// Works but can be improved, maybe
// https://docs.unity3d.com/ScriptReference/EventSystems.IDragHandler.html
public class PanelDragBehavior : MonoBehaviour, IBeginDragHandler, IDragHandler
{
public Transform DragObject;
private Vector3 lastPointerPos;
public void Start()
{
if (DragObject == null)
DragObject = transform;
}
public void OnBeginDrag(PointerEventData eventData)
{
// Init pointer position
lastPointerPos = Core.HasDevice("Flystick")
? transform.InverseTransformPoint(FindObjectOfType<WandInputModule>().cursor.position)
: UFZ.Core.Position();
}
public void OnDrag(PointerEventData eventData)
{
Vector3 currentPointerPos;
currentPointerPos = Core.HasDevice("Flystick")
? transform.InverseTransformPoint(FindObjectOfType<WandInputModule>().cursor.position)
: Core.Position();
var deltaPointerPos = currentPointerPos - lastPointerPos;
DragObject.localPosition += deltaPointerPos;
lastPointerPos = currentPointerPos;
// Take movement of UI into account for last pointer position
if (Core.HasDevice("Flystick"))
lastPointerPos -= deltaPointerPos;
}
}
}
| 34.833333 | 102 | 0.627478 | [
"MIT"
] | bilke/unity | UI/Scripts/PanelDragBehavior.cs | 1,465 | C# |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
namespace Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json
{
public sealed class SingleConverter : JsonConverter<float>
{
internal override JsonNode ToJson(float value) => new JsonNumber(value.ToString());
internal override float FromJson(JsonNode node) => (float)node;
}
} | 52.769231 | 97 | 0.523324 | [
"MIT"
] | Agazoth/azure-powershell | src/ApplicationInsights/ApplicationInsights.Autorest/generated/runtime/Conversions/Instances/SingleConverter.cs | 676 | C# |
// 練習モード用コントロール
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace TrainingFXChart
{
public partial class PracticeModeControl : UserControl
{
// 新規|決済, 日時, 売|買, 数量, 約定価格, 損益
List<Tuple<string, string, string, string, string, string>> _orderlog = new List<Tuple<string, string, string, string, string, string>>();
string _orderlogfile;
int _intervalseconds;
/// <summary>
/// 練習モードの終了を通知する
/// </summary>
public Action SendPracticeModeFinish;
/// <summary>
/// 他のコントロールに、指定したインデックス番号をセットする
/// </summary>
public Action<int> SetCurrentIndex;
/// <summary>
/// ChartCanvasが今表示している一番右のローソクを取得する
/// </summary>
public Func<double[]> GetCandle;
public PracticeModeControl()
{
InitializeComponent();
AddNewOrderTableRow(); // 新規注文用の空の行
}
public void Setting(SettingDialog sd)
{
_orderlogfile = sd.OrderLogFile;
_intervalseconds = sd.IntervalSeconds * 1000;
timer1.Interval = _intervalseconds;
}
/// <summary>
/// 練習モード開始時に、その時表示されている一番右のローソクのインデックスがセットされ
/// 以降はIncButton押下する度に+1される
/// </summary>
public int IdxCurrent
{
set; get;
}
/// <summary>
/// 現在の注文状況を取得する
/// </summary>
public Tuple<string, double>[] GetOrder() // 売|買 注文価格
{
List<Tuple<string, double>> result = new List<Tuple<string, double>>();
for (int i = 0; i < OrderTable.Rows.Count; i++)
{
string ordertype = OrderTable.Rows[i].Cells["Order"].Value.ToString();
double ordervalue;
if (!double.TryParse(OrderTable.Rows[i].Cells["OrderValue"].Value.ToString(), out ordervalue))
ordervalue = -1;
result.Add(new Tuple<string, double>(ordertype, ordervalue));
}
return result.ToArray();
}
/// <summary>
/// 現在の建玉と、その決済注文状況を取得する
/// </summary>
public Tuple<string, double, double, double>[] GetPosition() // 売|買 建玉 利確 損切
{
List<Tuple<string, double, double, double>> result = new List<Tuple<string, double, double, double>>();
for (int i = 0; i < PositionTable.Rows.Count; i++)
{
string postype = PositionTable.Rows[i].Cells["Position"].Value.ToString();
double posvalue;
if (!double.TryParse(PositionTable.Rows[i].Cells["Value"].Value.ToString(), out posvalue))
posvalue = -1;
double rikaku;
if (!double.TryParse(PositionTable.Rows[i].Cells["OrderSashineValue"].Value.ToString(), out rikaku))
rikaku = -1;
double sonkiri;
if (!double.TryParse(PositionTable.Rows[i].Cells["OrderGyakuSashineValue"].Value.ToString(), out sonkiri))
sonkiri = -1;
result.Add(new Tuple<string, double, double, double>(postype, posvalue, rikaku, sonkiri));
}
return result.ToArray();
}
/// <summary>
/// キャンバスに表示されている足を1本分進め、注文の処理も行う。
/// </summary>
private void IncButton_Click(object sender, EventArgs e)
{
// キャンバスの足を1本進める
double[] oldCandle = GetCandle();
SetCurrentIndex(IdxCurrent += 1);
double[] currentcandle = GetCandle();
// これ以上進めないので、現在の建玉を全決済してモード終了
if (oldCandle[0] == currentcandle[0])
{
for (int i = PositionTable.Rows.Count - 1; i >= 0; i--)
{
PositionTable.Rows[i].Cells["Value"].Value = currentcandle[Const.IDXCL];
PositionTable.Rows[i].Cells["DateTime"].Value = FormatDate(currentcandle[Const.IDXDATE]);
LogAdd("決済", i);
PositionTable.Rows.RemoveAt(i);
}
CloseButton_Click(this, e);
}
//
// 新規注文
//
int cnt = OrderTable.RowCount - 1; // 空行分-1
for (int i = cnt - 1; i >= 0; i--)
{
double ordervalue = 0;
if (!double.TryParse(OrderTable.Rows[i].Cells["OrderValue"].Value.ToString(), out ordervalue)) continue;
double ordernum = 0;
if (!double.TryParse(OrderTable.Rows[i].Cells["OrderNumber"].Value.ToString(), out ordernum)) continue;
// 買えるかな?
if (OrderTable.Rows[i].Cells["Order"].Value.ToString() == "買")
{
if (ordervalue >= currentcandle[Const.IDXLW])
NewOrder(i, "買", ordernum, ordervalue > currentcandle[Const.IDXOP] ? currentcandle[Const.IDXOP] : ordervalue, currentcandle);
}
// 売れるかな?
else
{
if (ordervalue <= currentcandle[Const.IDXHI])
NewOrder(i, "売", ordernum, ordervalue < currentcandle[Const.IDXOP] ? currentcandle[Const.IDXOP] : ordervalue, currentcandle);
}
}
//
// 決済注文
//
cnt = PositionTable.RowCount;
for (int i = cnt - 1; i >= 0; i--)
{
double value = double.Parse(PositionTable.Rows[i].Cells["Value"].Value.ToString());
double number= double.Parse(PositionTable.Rows[i].Cells["Number"].Value.ToString()) * 10000;
double ordervalue = 0;
// 買いポジが...
if (PositionTable.Rows[i].Cells["Position"].Value.ToString() == "買")
{
// 狩られるか?
if (double.TryParse(PositionTable.Rows[i].Cells["OrderGyakuSashineValue"].Value.ToString(), out ordervalue))
if (ordervalue >= currentcandle[Const.IDXLW])
{
double yakujo = ordervalue > currentcandle[Const.IDXOP] ? currentcandle[Const.IDXOP] : ordervalue;
RevOrder(i, yakujo, number, yakujo - value, currentcandle);
continue;
}
// 利確できるか?
if (double.TryParse(PositionTable.Rows[i].Cells["OrderSashineValue"].Value.ToString(), out ordervalue))
if (ordervalue <= currentcandle[Const.IDXHI])
{
double yakujo = ordervalue < currentcandle[Const.IDXOP] ? currentcandle[Const.IDXOP] : ordervalue;
RevOrder(i, yakujo, number, yakujo - value, currentcandle);
continue;
}
PositionTable.Rows[i].Cells["SonEki"].Value = ((currentcandle[Const.IDXCL] - value) * number).ToString("F0");
}
// 売りポジが...
else if (PositionTable.Rows[i].Cells["Position"].Value.ToString() == "売")
{
// 狩られるか?
if (double.TryParse(PositionTable.Rows[i].Cells["OrderGyakuSashineValue"].Value.ToString(), out ordervalue))
if (ordervalue <= currentcandle[Const.IDXHI])
{
double yakujo = ordervalue < currentcandle[Const.IDXOP] ? currentcandle[Const.IDXOP] : ordervalue;
RevOrder(i, yakujo, number, value - yakujo, currentcandle);
continue;
}
// 利確できるか?
if (double.TryParse(PositionTable.Rows[i].Cells["OrderSashineValue"].Value.ToString(), out ordervalue))
if (ordervalue >= currentcandle[Const.IDXLW])
{
double yakujo = ordervalue > currentcandle[Const.IDXOP] ? currentcandle[Const.IDXOP] : ordervalue;
RevOrder(i, yakujo, number, value - yakujo, currentcandle);
continue;
}
PositionTable.Rows[i].Cells["SonEki"].Value = ((value - currentcandle[Const.IDXCL]) * number).ToString("F0");
}
}
}
/// <summary>
/// 練習モードを終了する
/// </summary>
private void CloseButton_Click(object sender, EventArgs e)
{
// タイマー止める
checkAutoInc.Checked = false;
Visible = false; // 練習用コントロール非表示
// 注文、建玉テーブルクリア
for (int i = OrderTable.Rows.Count - 1; i >= 0; i--)
OrderTable.Rows.RemoveAt(i);
AddNewOrderTableRow();
for (int i = PositionTable.Rows.Count - 1; i >= 0; i--)
PositionTable.Rows.RemoveAt(i);
// 注文ログを出力
Directory.CreateDirectory(Path.GetDirectoryName(_orderlogfile));
using (StreamWriter sw = new StreamWriter(_orderlogfile, false, Encoding.GetEncoding("shift_jis")))
{
// 新規|決済, 日時, 売|買, 数量, 約定価格, 損益
foreach (Tuple<string, string, string, string, string, string> t in _orderlog)
sw.WriteLine(t.Item1 + "," + t.Item2 + "," + t.Item3 + "," + t.Item4 + "," + t.Item5 + "," + t.Item6);
}
_orderlog.Clear();
SendPracticeModeFinish();
}
#region 注文設定
/// <summary>
/// 決済注文
/// </summary>
private void PositionTable_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex == -1) return;
string sashine = PositionTable.Rows[e.RowIndex].Cells["OrderSashineValue"].Value.ToString();
string gyakusashi = PositionTable.Rows[e.RowIndex].Cells["OrderGyakuSashineValue"].Value.ToString();
RevOrderDialog order = new RevOrderDialog(sashine, gyakusashi);
order.ShowDialog();
switch (order.Order)
{
case Const.ONARI:
PositionTable.Rows[e.RowIndex].Cells["Value"].Value = GetCandle()[Const.IDXCL];
PositionTable.Rows[e.RowIndex].Cells["DateTime"].Value = FormatDate(GetCandle()[Const.IDXDATE]);
LogAdd("決済", e.RowIndex);
PositionTable.Rows.RemoveAt(e.RowIndex);
break;
case Const.OSASHI:
PositionTable.Rows[e.RowIndex].Cells["OrderSashineValue"].Value = order.SashineValue;
PositionTable.Rows[e.RowIndex].Cells["OrderGyakuSashineValue"].Value = order.GyakuSashiValue;
break;
default:
break;
}
}
/// <summary>
/// 新規注文
/// </summary>
private void OrderTable_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex == -1) return;
// 注文が存在するセルをダブルクリックすると、その注文は削除される
var value = OrderTable[0, e.RowIndex].Value;
if (value.ToString() != "")
{
DialogResult result = MessageBox.Show("この注文を削除しますか?", "削除確認", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
OrderTable.Rows.Remove(OrderTable.Rows[e.RowIndex]);
}
return;
}
NewOrderDialog order = new NewOrderDialog();
order.ShowDialog();
if (order.ret != DialogResult.OK) return;
//成行注文は即座に建玉テーブルに反映される
if (order.Order == Const.ONARI)
{
NewOrder(-1, order.Pos, order.Number, GetCandle()[Const.IDXCL], GetCandle());
}
else
{
AddNewOrderTableRow();
OrderTable[0, OrderTable.Rows.Count - 2].Value = order.Pos;
OrderTable[1, OrderTable.Rows.Count - 2].Value = order.Number.ToString();
OrderTable[2, OrderTable.Rows.Count - 2].Value = order.Value.ToString();
}
}
#endregion
private void NewOrder(int ordertablerow, string pos, double ordernum, double ordervalue, double[] currentcandle)
{
PositionTable.Rows.Add();
PositionTable.Rows[PositionTable.Rows.Count - 1].Cells["Position"].Value = pos;
PositionTable.Rows[PositionTable.Rows.Count - 1].Cells["Number"].Value = ordernum;
PositionTable.Rows[PositionTable.Rows.Count - 1].Cells["Value"].Value = ordervalue;
PositionTable.Rows[PositionTable.Rows.Count - 1].Cells["DateTime"].Value = FormatDate(currentcandle[Const.IDXDATE]);
PositionTable.Rows[PositionTable.Rows.Count - 1].Cells["OrderSashineValue"].Value = "";
PositionTable.Rows[PositionTable.Rows.Count - 1].Cells["OrderGyakuSashineValue"].Value = "";
PositionTable.Rows[PositionTable.Rows.Count - 1].Cells["SonEki"].Value = "";
if (ordertablerow != -1)
OrderTable.Rows.RemoveAt(ordertablerow);
LogAdd("新規", PositionTable.Rows.Count - 1);
}
private void RevOrder(int positiontablerow, double yakujovalue, double number, double soneki, double[] currentcandle)
{
PositionTable.Rows[PositionTable.Rows.Count - 1].Cells["Value"].Value = yakujovalue.ToString("F3");
PositionTable.Rows[PositionTable.Rows.Count - 1].Cells["DateTime"].Value = FormatDate(currentcandle[Const.IDXDATE]);
PositionTable.Rows[positiontablerow].Cells["SonEki"].Value = (soneki * number).ToString("F0");
LogAdd("決済", positiontablerow);
PositionTable.Rows.RemoveAt(positiontablerow);
}
private void LogAdd(string ordertype, int index)
{
string pos = PositionTable.Rows[index].Cells["Position"].Value.ToString();
if(ordertype == "決済")
pos = pos == "買" ? "売" : "買";
_orderlog.Add(new Tuple<string, string, string, string, string, string>(
ordertype, //新規 | 決済
PositionTable.Rows[index].Cells["DateTime"].Value.ToString(), // 日時
pos, // 売 | 買
PositionTable.Rows[index].Cells["Number"].Value.ToString(), // 数量
PositionTable.Rows[index].Cells["Value"].Value.ToString(), // 約定価格
ordertype == "新規" ? "" : PositionTable.Rows[index].Cells["SonEki"].Value.ToString() // 損益
));
}
/// <summary>
/// 注文テーブルを1行追加して初期化する。初期化しないとnullのままなので。
/// </summary>
private void AddNewOrderTableRow()
{
OrderTable.Rows.Add();
OrderTable.Rows[OrderTable.Rows.Count - 1].Cells["Order"].Value = "";
OrderTable.Rows[OrderTable.Rows.Count - 1].Cells["OrderNumber"].Value = "";
OrderTable.Rows[OrderTable.Rows.Count - 1].Cells["OrderValue"].Value = "";
}
private string FormatDate(double date)
{
return ((int)(date / 10000000000)).ToString() + "/" +
((int)(date / 100000000 % 100)).ToString() + "/" +
((int)(date / 1000000 % 100)).ToString() + " " +
((int)(date / 10000 % 100)).ToString() + ":" +
((int)(date / 100 % 100)).ToString();
}
private void checkAutoInc_CheckedChanged(object sender, EventArgs e)
{
if(checkAutoInc.Checked)
{
timer1.Interval = _intervalseconds;
timer1.Tick += new EventHandler(IncButton_Click);
timer1.Start();
}
else
{
timer1.Tick -= new EventHandler(IncButton_Click);
timer1.Stop();
}
}
}
}
| 39.57971 | 149 | 0.523435 | [
"MIT"
] | Chiakikun/TrainingFXChart | PracticeModeControl.cs | 17,460 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace eLibrary.ModelForMobile
{
public class Pisac
{
public int Pisac_ID { get; set; }
public string? Ime { get; set; }
public string? Prezime { get; set; }
public DateTime DatumRodjenja { get; set; }
public int Grad_ID { get; set; }
public virtual Grad? Grad { get; set; }
public override string ToString()
{
return $"{Ime} {Prezime}";
}
public string ImePrezime => $"{Ime} {Prezime}";
}
}
| 24.035714 | 55 | 0.607727 | [
"MIT"
] | AlmirJusic/eLibrary | eLibrary/eLibrary.ModelForMobile/Pisac.cs | 675 | 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("GenericsShared")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("JPMorganChase")]
[assembly: AssemblyProduct("GenericsShared")]
[assembly: AssemblyCopyright("Copyright © JPMorganChase 2005")]
[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("4ce54484-73c4-4f90-a7fa-a286a38198f8")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.527778 | 84 | 0.754146 | [
"MIT"
] | jdm7dv/financial | windows/practical-.net-for-financial-markets/CodeExample/Chpt9/RemotingGenerics/GenericsShared/GenericsShared/Properties/AssemblyInfo.cs | 1,390 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShellScript : MonoBehaviour
{
public GameObject parent;
public TankHP tankHP;
public GameObject particle;
// Start is called before the first frame update
void Start()
{
if (parent) tankHP = parent.GetComponent<Moves>().target.GetComponent<TankHP>();
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject && parent)
{
if (collision.gameObject == parent.GetComponent<Moves>().target)
{
tankHP.TakeDamage();
}
if (collision.gameObject != parent)
{
particle.GetComponent<AudioSource>().Play();
particle.transform.parent = null;
particle.GetComponent<ParticleSystem>().Play();
ParticleSystem.MainModule module = particle.GetComponent<ParticleSystem>().main;
GameObject.Destroy(particle, module.duration);
GameObject.Destroy(this.gameObject);
Debug.Log(collision.gameObject);
}
}
}
}
| 27.8 | 96 | 0.591527 | [
"MIT"
] | UriKurae/AssignmentTanks | Tanks/Assets/Assets/Scripts/Tanks/ShellScript.cs | 1,251 | C# |
#if !ZEN_NOT_UNITY3D
using System;
using System.Collections.Generic;
using ModestTree;
using System.Linq;
using UnityEngine;
namespace Zenject
{
public class MonoBehaviourSingletonLazyCreator
{
readonly DiContainer _container;
readonly MonoBehaviourSingletonProviderCreator _owner;
readonly MonoBehaviourSingletonId _id;
Component _instance;
int _referenceCount;
public MonoBehaviourSingletonLazyCreator(
DiContainer container, MonoBehaviourSingletonProviderCreator owner,
MonoBehaviourSingletonId id)
{
Assert.That(id.ConcreteType.DerivesFromOrEqual<Component>());
_container = container;
_owner = owner;
_id = id;
}
GameObject GameObject
{
get
{
return _id.GameObject;
}
}
Type ComponentType
{
get
{
return _id.ConcreteType;
}
}
public void IncRefCount()
{
_referenceCount += 1;
}
public void DecRefCount()
{
_referenceCount -= 1;
if (_referenceCount <= 0)
{
_owner.RemoveCreator(_id);
}
}
public object GetInstance(InjectContext context)
{
Assert.That(ComponentType.DerivesFromOrEqual(context.MemberType));
if (_instance == null)
{
Assert.That(!_container.IsValidating,
"Tried to instantiate a MonoBehaviour with type '{0}' during validation. Object graph: {1}", ComponentType, context.GetObjectGraphString());
// Note that we always want to cache _container instead of using context.Container
// since for singletons, the container they are accessed from should not determine
// the container they are instantiated with
// Transients can do that but not singletons
_instance = GameObject.AddComponent(ComponentType);
Assert.That(_instance != null);
_container.Inject(_instance, new object[0], true, context);
}
return _instance;
}
public IEnumerable<ZenjectResolveException> ValidateBinding(InjectContext context)
{
return _container.ValidateObjectGraph(ComponentType, context);
}
}
}
#endif
| 26.946237 | 160 | 0.577813 | [
"MIT"
] | hinshun/mist-ridge | Assets/Scripts/Vendor/Zenject/Providers/Singleton/MonoBehaviour/MonoBehaviourSingletonLazyCreator.cs | 2,506 | C# |
namespace KS3P.Operators
{
[KSPAddon(KSPAddon.Startup.MainMenu, false)]
public sealed class MainMenuOperator : PostProcessingOperator
{
protected override void Process()
{
KS3P.currentScene = KS3P.Scene.MainMenu;
Patch(false, KS3P.Scene.MainMenu);
}
}
}
| 24.538462 | 65 | 0.630094 | [
"MIT"
] | jrodrigv/KS3P | KS3Code/Operators/MainMenuOperator.cs | 321 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using CommandLine;
namespace CodeGenerator
{
public class Options
{
[Option('p', "path", HelpText = "Base path for processing sources, references and target.")]
public string Path { get; set; }
[Option('s', "source", Separator = ';', HelpText = "Input source files.")]
public IEnumerable<string> Sources { get; set; }
[Option('r', "reference", Separator = ';', HelpText = "Input reference files for building sources.")]
public IEnumerable<string> References { get; set; }
[Option('d', "define", Separator = ';', HelpText = "Defines name as a symbol which is used in compiling.")]
public IEnumerable<string> Defines { get; set; }
[Option('t', "target", HelpText = "Filename of a generated code.")]
public string TargetFile { get; set; }
[Option('n', "namespace", HelpText = "namespace.")]
public string Namespace { get; set; } = "EuNet";
[Option("include", Separator = ';', HelpText = "Source include regular expression filter.")]
public IEnumerable<string> Includes { get; set; }
[Option("exclude", Separator = ';', HelpText = "Source exclude regular expression filter.")]
public IEnumerable<string> Excludes { get; set; }
}
}
| 36.769231 | 115 | 0.638773 | [
"MIT"
] | zestylife/EuNet | src/EuNet.CodeGenerator/Options.cs | 1,436 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Diagnostics;
using System.Management.Automation;
using System.Collections.Generic;
using NuGet.Configuration;
using NuGet.Common;
using NuGet.Protocol;
using NuGet.Protocol.Core.Types;
using System.Threading;
using LinqKit;
using MoreLinq.Extensions;
using NuGet.Versioning;
using System.Data;
using System.Linq;
using System.Net;
using Microsoft.PowerShell.PowerShellGet.RepositorySettings;
using System.Net.Http;
using System.IO;
using System.Threading.Tasks;
using Newtonsoft.Json;
using static System.Environment;
namespace Microsoft.PowerShell.PowerShellGet.Cmdlets
{
/// <summary>
/// The Register-PSResourceRepository cmdlet registers the default repository for PowerShell modules.
/// After a repository is registered, you can reference it from the Find-PSResource, Install-PSResource, and Publish-PSResource cmdlets.
/// The registered repository becomes the default repository in Find-Module and Install-Module.
/// It returns nothing.
/// </summary>
[Cmdlet(VerbsCommon.Find, "PSResource", DefaultParameterSetName = "NameParameterSet", SupportsShouldProcess = true,
HelpUri = "<add>", RemotingCapability = RemotingCapability.None)]
public sealed
class FindPSResource : PSCmdlet
{
// private string PSGalleryRepoName = "PSGallery";
/// <summary>
/// Specifies the desired name for the resource to be searched.
/// </summary>
[Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "NameParameterSet")]
[ValidateNotNullOrEmpty]
public string[] Name
{
get
{ return _name; }
set
{ _name = value; }
}
private string[] _name = new string[0];
/// <summary>
/// Specifies the type of the resource to be searched for.
/// </summary>
[Parameter(ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
[ValidateSet(new string[] { "Module", "Script", "DscResource", "RoleCapability", "Command" })]
public string[] Type
{
get
{ return _type; }
set
{ _type = value; }
}
private string[] _type;
/// <summary>
/// Specifies the version or version range of the package to be searched for
/// </summary>
[Parameter(ParameterSetName = "NameParameterSet")]
[ValidateNotNullOrEmpty]
public string Version
{
get
{ return _version; }
set
{ _version = value; }
}
private string _version;
/// <summary>
/// Specifies to search for prerelease resources.
/// </summary>
[Parameter(ParameterSetName = "NameParameterSet")]
public SwitchParameter Prerelease
{
get
{ return _prerelease; }
set
{ _prerelease = value; }
}
private SwitchParameter _prerelease;
/// <summary>
/// Specifies a user account that has rights to find a resource from a specific repository.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = "NameParameterSet")]
[ValidateNotNullOrEmpty]
public string ModuleName
{
get
{ return _moduleName; }
set
{ _moduleName = value; }
}
private string _moduleName;
/// <summary>
/// Specifies the type of the resource to be searched for.
/// </summary>
[Parameter(ValueFromPipeline = true, ParameterSetName = "NameParameterSet")]
[ValidateNotNull]
public string[] Tags
{
get
{ return _tags; }
set
{ _tags = value; }
}
private string[] _tags;
/// <summary>
/// Specify which repositories to search in.
/// </summary>
[ValidateNotNullOrEmpty]
[Parameter(ValueFromPipeline = true, ParameterSetName = "NameParameterSet")]
public string[] Repository
{
get { return _repository; }
set { _repository = value; }
}
private string[] _repository;
/// <summary>
/// Specifies a user account that has rights to find a resource from a specific repository.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = "NameParameterSet")]
public PSCredential Credential
{
get
{ return _credential; }
set
{ _credential = value; }
}
private PSCredential _credential;
/// <summary>
/// Specifies to return any dependency packages.
/// Currently only used when name param is specified.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = "NameParameterSet")]
public SwitchParameter IncludeDependencies
{
get { return _includeDependencies; }
set { _includeDependencies = value; }
}
private SwitchParameter _includeDependencies;
// This will be a list of all the repository caches
public static readonly List<string> RepoCacheFileName = new List<string>();
// Temporarily store cache in this path for testing purposes
public static readonly string RepositoryCacheDir = Path.Combine(Environment.GetFolderPath(SpecialFolder.LocalApplicationData), "PowerShellGet", "RepositoryCache");
//public static readonly string RepositoryCacheDir = @"%APPDATA%/PowerShellGet/repositorycache";//@"%APPDTA%\NuGet";
//private readonly object p;
// Define the cancellation token.
CancellationTokenSource source;
CancellationToken cancellationToken;
List<string> pkgsLeftToFind;
private const string CursorFileName = "cursor.json";
/// <summary>
/// </summary>
protected override void ProcessRecord()
{
source = new CancellationTokenSource();
cancellationToken = source.Token;
var r = new RespositorySettings();
var listOfRepositories = r.Read(_repository);
var returnedPkgsFound = new List<IEnumerable<IPackageSearchMetadata>>();
pkgsLeftToFind = _name.ToList();
foreach (var repoName in listOfRepositories)
{
WriteDebug(string.Format("Searching in repository '{0}'", repoName.Properties["Name"].Value.ToString()));
// We'll need to use the catalog reader when enumerating through all packages under v3 protocol.
// if using v3 endpoint and there's no exact name specified (ie no name specified or a name with a wildcard is specified)
if (repoName.Properties["Url"].Value.ToString().EndsWith("/v3/index.json") &&
(_name.Length == 0 || _name.Any(n => n.Contains("*"))))//_name.Contains("*"))) /// TEST THIS!!!!!!!
{
this.WriteWarning("This functionality is not yet implemented");
// right now you can use wildcards with an array of names, ie -name "Az*", "PS*", "*Get", will take a hit performance wise, though.
// TODO: add wildcard condition here
//ProcessCatalogReader(repoName.Properties["Name"].Value.ToString(), repoName.Properties["Url"].Value.ToString());
}
// if it can't find the pkg in one repository, it'll look in the next one in the list
// returns any pkgs found, and any pkgs that weren't found
returnedPkgsFound.AddRange(FindPackagesFromSource(repoName.Properties["Name"].Value.ToString(), repoName.Properties["Url"].Value.ToString(), cancellationToken));
// Flatten returned pkgs before displaying output returnedPkgsFound.Flatten().ToList()[0]
var flattenedPkgs = returnedPkgsFound.Flatten();
// flattenedPkgs.ToList();
if (flattenedPkgs.Any() && flattenedPkgs.First() != null)
{
foreach (IPackageSearchMetadata pkg in flattenedPkgs)
{
//WriteObject(pkg);
PSObject pkgAsPSObject = new PSObject();
pkgAsPSObject.Members.Add(new PSNoteProperty("Name", pkg.Identity.Id));
// Version.Version ensures type is System.Version instead of type NuGetVersion
pkgAsPSObject.Members.Add(new PSNoteProperty("Version", pkg.Identity.Version.Version));
pkgAsPSObject.Members.Add(new PSNoteProperty("Repository", repoName.Properties["Name"].Value.ToString()));
pkgAsPSObject.Members.Add(new PSNoteProperty("Description", pkg.Description));
WriteObject(pkgAsPSObject);
}
}
// reset found packages
returnedPkgsFound.Clear();
// if we need to search all repositories, we'll continue, otherwise we'll just return
if (!pkgsLeftToFind.Any())
{
break;
}
} // end of foreach
}
/***
public void ProcessCatalogReader(string repoName, string sourceUrl)
{
// test initalizing a cursor see: https://docs.microsoft.com/en-us/nuget/guides/api/query-for-all-published-packages
// we want all packages published from the beginning of time
// DateTime cursor = DateTime.MinValue;
// Define a lower time bound for leaves to fetch. This exclusive minimum time bound is called the cursor.
//var cursor = DateTime.MinValue; /// come back to this GetCursor();
var cursor = GetCursor(); // come back to this
// Discover the catalog index URL from the service index.
var catalogIndexUrl = GetCatalogIndexUrlAsync(sourceUrl).GetAwaiter().GetResult();
var httpClient = new HttpClient();
// Download the catalog index and deserialize it.
var indexString = httpClient.GetStringAsync(catalogIndexUrl).GetAwaiter().GetResult();
Console.WriteLine($"Fetched catalog index {catalogIndexUrl}.");
var index = JsonConvert.DeserializeObject<CatalogIndex>(indexString);
// Find all pages in the catalog index that meet the time bound.
var pageItems = index
.Items
.Where(x => x.CommitTimestamp > cursor);
var allLeafItems = new List<CatalogLeafItem>();
foreach (var pageItem in pageItems) /// need to process one page at a time
{
// Download the catalog page and deserialize it.
var pageString = httpClient.GetStringAsync(pageItem.Url).GetAwaiter().GetResult();
Console.WriteLine($"Fetched catalog page {pageItem.Url}.");
var page = JsonConvert.DeserializeObject<CatalogPage>(pageString);
// Find all leaves in the catalog page that meet the time bound.
var pageLeafItems = page
.Items
.Where(x => x.CommitTimestamp > cursor);
allLeafItems.AddRange(pageLeafItems);
// local
FindLocalPackagesResourceV2 localResource = new FindLocalPackagesResourceV2(sourceUrl);
LocalPackageSearchResource localResourceSearch = new LocalPackageSearchResource(localResource);
LocalPackageMetadataResource localResourceMetadata = new LocalPackageMetadataResource(localResource);
SearchFilter filter = new SearchFilter(_prerelease);
SourceCacheContext context = new SourceCacheContext();
// url
PackageSource source = new PackageSource(sourceUrl);
if (_credential != null)
{
string password = new NetworkCredential(string.Empty, _credential.Password).Password;
source.Credentials = PackageSourceCredential.FromUserInput(sourceUrl, _credential.UserName, password, true, null);
}
var provider = FactoryExtensionsV3.GetCoreV3(NuGet.Protocol.Core.Types.Repository.Provider);
SourceRepository repository = new SourceRepository(source, provider);
PackageSearchResource resourceSearch = repository.GetResourceAsync<PackageSearchResource>().GetAwaiter().GetResult();
PackageMetadataResource resourceMetadata = repository.GetResourceAsync<PackageMetadataResource>().GetAwaiter().GetResult();
// Process all of the catalog leaf items.
Console.WriteLine($"Processing {allLeafItems.Count} catalog leaves.");
foreach (var leafItem in allLeafItems)
{
_version = leafItem.PackageVersion;
IEnumerable<IPackageSearchMetadata> foundPkgs;
if (sourceUrl.StartsWith("file://"))
{
foundPkgs = FindPackagesFromSourceHelper(sourceUrl, leafItem.PackageId, localResourceSearch, localResourceMetadata, filter, context).FirstOrDefault();
}
else
{
foundPkgs = FindPackagesFromSourceHelper(sourceUrl, leafItem.PackageId, resourceSearch, resourceMetadata, filter, context).FirstOrDefault();
}
// var foundPkgsFlattened = foundPkgs.Flatten();
foreach(var pkg in foundPkgs)
{
// First or default to convert the ienumeraable object into just an IPackageSearchmetadata object
// var pkgToOutput = foundPkgs.FirstOrDefault();//foundPkgs.Cast<IPackageSearchMetadata>();
PSObject pkgAsPSObject = new PSObject();
pkgAsPSObject.Members.Add(new PSNoteProperty("Name", pkg.Identity.Id));
pkgAsPSObject.Members.Add(new PSNoteProperty("Version", pkg.Identity.Version));
pkgAsPSObject.Members.Add(new PSNoteProperty("Repository", repoName));
pkgAsPSObject.Members.Add(new PSNoteProperty("Description", pkg.Description));
WriteObject(pkgAsPSObject);
}
}
}
}
*/
//
public List<IEnumerable<IPackageSearchMetadata>> FindPackagesFromSource(string repoName, string repositoryUrl, CancellationToken cancellationToken)
{
List<IEnumerable<IPackageSearchMetadata>> returnedPkgs = new List<IEnumerable<IPackageSearchMetadata>>();
if (repositoryUrl.StartsWith("file://"))
{
FindLocalPackagesResourceV2 localResource = new FindLocalPackagesResourceV2(repositoryUrl);
LocalPackageSearchResource resourceSearch = new LocalPackageSearchResource(localResource);
LocalPackageMetadataResource resourceMetadata = new LocalPackageMetadataResource(localResource);
SearchFilter filter = new SearchFilter(_prerelease);
SourceCacheContext context = new SourceCacheContext();
if ((_name == null) || (_name.Length == 0))
{
returnedPkgs.AddRange(FindPackagesFromSourceHelper(repoName, repositoryUrl, null, resourceSearch, resourceMetadata, filter, context));
}
foreach (var n in _name)
{
returnedPkgs.AddRange(FindPackagesFromSourceHelper(repoName,repositoryUrl, n, resourceSearch, resourceMetadata, filter, context));
}
}
else
{
PackageSource source = new PackageSource(repositoryUrl);
if (_credential != null)
{
string password = new NetworkCredential(string.Empty, _credential.Password).Password;
source.Credentials = PackageSourceCredential.FromUserInput(repositoryUrl, _credential.UserName, password, true, null);
}
var provider = FactoryExtensionsV3.GetCoreV3(NuGet.Protocol.Core.Types.Repository.Provider);
SourceRepository repository = new SourceRepository(source, provider);
PackageSearchResource resourceSearch = null;
PackageMetadataResource resourceMetadata = null;
try
{
resourceSearch = repository.GetResourceAsync<PackageSearchResource>().GetAwaiter().GetResult();
resourceMetadata = repository.GetResourceAsync<PackageMetadataResource>().GetAwaiter().GetResult();
}
catch (Exception e){
WriteDebug("Error retrieving resource from repository: " + e.Message);
return returnedPkgs;
}
SearchFilter filter = new SearchFilter(_prerelease);
SourceCacheContext context = new SourceCacheContext();
if ((_name == null) || (_name.Length == 0))
{
returnedPkgs.AddRange(FindPackagesFromSourceHelper(repoName, repositoryUrl, null, resourceSearch, resourceMetadata, filter, context));
}
foreach (string n in _name)
{
if (pkgsLeftToFind.Any())
{
var foundPkgs = FindPackagesFromSourceHelper(repoName, repositoryUrl, n, resourceSearch, resourceMetadata, filter, context);
if (foundPkgs.Any() && foundPkgs.First().Count() != 0)
{
returnedPkgs.AddRange(foundPkgs);
// if the repository is not specified or the repository is specified (but it's not '*'), then we can stop continuing to search for the package
if (_repository == null || !_repository[0].Equals("*"))
{
pkgsLeftToFind.Remove(n);
}
}
}
}
}
return returnedPkgs;
}
private IEnumerable<DataRow> FindPackageFromCache(string repositoryName)
{
DataSet cachetables = new CacheSettings().CreateDataTable(repositoryName);
return FindPackageFromCacheHelper(cachetables, repositoryName);
}
private IEnumerable<DataRow> FindPackageFromCacheHelper(DataSet cachetables, string repositoryName)
{
DataTable metadataTable = cachetables.Tables[0];
DataTable tagsTable = cachetables.Tables[1];
DataTable dependenciesTable = cachetables.Tables[2];
DataTable commandsTable = cachetables.Tables[3];
DataTable dscResourceTable = cachetables.Tables[4];
DataTable roleCapabilityTable = cachetables.Tables[5];
DataTable queryTable = new DataTable();
var predicate = PredicateBuilder.New<DataRow>(true);
if ((_tags != null) && (_tags.Length != 0))
{
var tagResults = from t0 in metadataTable.AsEnumerable()
join t1 in tagsTable.AsEnumerable()
on t0.Field<string>("Key") equals t1.Field<string>("Key")
select new PackageMetadataAllTables
{
Key = t0["Key"],
Name = t0["Name"],
Version = t0["Version"],
Type = (string)t0["Type"],
Description = t0["Description"],
Author = t0["Author"],
Copyright = t0["Copyright"],
PublishedDate = t0["PublishedDate"],
InstalledDate = t0["InstalledDate"],
UpdatedDate = t0["UpdatedDate"],
LicenseUri = t0["LicenseUri"],
ProjectUri = t0["ProjectUri"],
IconUri = t0["IconUri"],
PowerShellGetFormatVersion = t0["PowerShellGetFormatVersion"],
ReleaseNotes = t0["ReleaseNotes"],
RepositorySourceLocation = t0["RepositorySourceLocation"],
Repository = t0["Repository"],
IsPrerelease = t0["IsPrerelease"],
Tags = t1["Tags"],
};
DataTable joinedTagsTable = tagResults.ToDataTable();
var tagsPredicate = PredicateBuilder.New<DataRow>(true);
// Build predicate by combining tag searches with 'or'
foreach (string t in _tags)
{
tagsPredicate = tagsPredicate.Or(pkg => pkg.Field<string>("Tags").Equals(t));
}
// final results -- All the appropriate pkgs with these tags
var tagsRowCollection = joinedTagsTable.AsEnumerable().Where(tagsPredicate).Select(p => p);
// Add row collection to final table to be queried
queryTable.Merge(tagsRowCollection.ToDataTable());
}
if (_type != null)
{
if (_type.Contains("Command", StringComparer.OrdinalIgnoreCase))
{
var commandResults = from t0 in metadataTable.AsEnumerable()
join t1 in commandsTable.AsEnumerable()
on t0.Field<string>("Key") equals t1.Field<string>("Key")
select new PackageMetadataAllTables
{
Key = t0["Key"],
Name = t0["Name"],
Version = t0["Version"],
Type = (string)t0["Type"],
Description = t0["Description"],
Author = t0["Author"],
Copyright = t0["Copyright"],
PublishedDate = t0["PublishedDate"],
InstalledDate = t0["InstalledDate"],
UpdatedDate = t0["UpdatedDate"],
LicenseUri = t0["LicenseUri"],
ProjectUri = t0["ProjectUri"],
IconUri = t0["IconUri"],
PowerShellGetFormatVersion = t0["PowerShellGetFormatVersion"],
ReleaseNotes = t0["ReleaseNotes"],
RepositorySourceLocation = t0["RepositorySourceLocation"],
Repository = t0["Repository"],
IsPrerelease = t0["IsPrerelease"],
Commands = t1["Commands"],
};
DataTable joinedCommandTable = commandResults.ToDataTable();
var commandPredicate = PredicateBuilder.New<DataRow>(true);
// Build predicate by combining names of commands searches with 'or'
// if no name is specified, we'll return all (?)
foreach (string n in _name)
{
commandPredicate = commandPredicate.Or(pkg => pkg.Field<string>("Commands").Equals(n));
}
// final results -- All the appropriate pkgs with these tags
var commandsRowCollection = joinedCommandTable.AsEnumerable().Where(commandPredicate).Select(p => p);
// Add row collection to final table to be queried
queryTable.Merge(commandsRowCollection.ToDataTable());
}
if (_type.Contains("DscResource", StringComparer.OrdinalIgnoreCase))
{
var dscResourceResults = from t0 in metadataTable.AsEnumerable()
join t1 in dscResourceTable.AsEnumerable()
on t0.Field<string>("Key") equals t1.Field<string>("Key")
select new PackageMetadataAllTables
{
Key = t0["Key"],
Name = t0["Name"],
Version = t0["Version"],
Type = (string)t0["Type"],
Description = t0["Description"],
Author = t0["Author"],
Copyright = t0["Copyright"],
PublishedDate = t0["PublishedDate"],
InstalledDate = t0["InstalledDate"],
UpdatedDate = t0["UpdatedDate"],
LicenseUri = t0["LicenseUri"],
ProjectUri = t0["ProjectUri"],
IconUri = t0["IconUri"],
PowerShellGetFormatVersion = t0["PowerShellGetFormatVersion"],
ReleaseNotes = t0["ReleaseNotes"],
RepositorySourceLocation = t0["RepositorySourceLocation"],
Repository = t0["Repository"],
IsPrerelease = t0["IsPrerelease"],
DscResources = t1["DscResources"],
};
var dscResourcePredicate = PredicateBuilder.New<DataRow>(true);
DataTable joinedDscResourceTable = dscResourceResults.ToDataTable();
// Build predicate by combining names of commands searches with 'or'
// if no name is specified, we'll return all (?)
foreach (string n in _name)
{
dscResourcePredicate = dscResourcePredicate.Or(pkg => pkg.Field<string>("DscResources").Equals(n));
}
// final results -- All the appropriate pkgs with these tags
var dscResourcesRowCollection = joinedDscResourceTable.AsEnumerable().Where(dscResourcePredicate).Select(p => p);
// Add row collection to final table to be queried
queryTable.Merge(dscResourcesRowCollection.ToDataTable());
}
if (_type.Contains("RoleCapability", StringComparer.OrdinalIgnoreCase))
{
var roleCapabilityResults = from t0 in metadataTable.AsEnumerable()
join t1 in roleCapabilityTable.AsEnumerable()
on t0.Field<string>("Key") equals t1.Field<string>("Key")
select new PackageMetadataAllTables
{
Key = t0["Key"],
Name = t0["Name"],
Version = t0["Version"],
Type = (string)t0["Type"],
Description = t0["Description"],
Author = t0["Author"],
Copyright = t0["Copyright"],
PublishedDate = t0["PublishedDate"],
InstalledDate = t0["InstalledDate"],
UpdatedDate = t0["UpdatedDate"],
LicenseUri = t0["LicenseUri"],
ProjectUri = t0["ProjectUri"],
IconUri = t0["IconUri"],
PowerShellGetFormatVersion = t0["PowerShellGetFormatVersion"],
ReleaseNotes = t0["ReleaseNotes"],
RepositorySourceLocation = t0["RepositorySourceLocation"],
Repository = t0["Repository"],
IsPrerelease = t0["IsPrerelease"],
RoleCapability = t1["RoleCapability"],
};
var roleCapabilityPredicate = PredicateBuilder.New<DataRow>(true);
DataTable joinedRoleCapabilityTable = roleCapabilityResults.ToDataTable();
// Build predicate by combining names of commands searches with 'or'
// if no name is specified, we'll return all (?)
foreach (string n in _name)
{
roleCapabilityPredicate = roleCapabilityPredicate.Or(pkg => pkg.Field<string>("RoleCapability").Equals(n));
}
// final results -- All the appropriate pkgs with these tags
var roleCapabilitiesRowCollection = joinedRoleCapabilityTable.AsEnumerable().Where(roleCapabilityPredicate).Select(p => p);
// Add row collection to final table to be queried
queryTable.Merge(roleCapabilitiesRowCollection.ToDataTable());
}
}
// We'll build the rest of the predicate-- ie the portions of the predicate that do not rely on datatables
predicate = predicate.Or(BuildPredicate(repositoryName));
// we want to uniquely add datarows into the table
// if queryTable is empty, we'll just query upon the metadata table
if (queryTable == null || queryTable.Rows.Count == 0)
{
queryTable = metadataTable;
}
// final results -- All the appropriate pkgs with these tags
var queryTableRowCollection = queryTable.AsEnumerable().Where(predicate).Select(p => p);
// ensure distinct by key
var finalQueryResults = queryTableRowCollection.AsEnumerable().DistinctBy(pkg => pkg.Field<string>("Key"));
// Add row collection to final table to be queried
// queryTable.Merge(distinctQueryTableRowCollection.ToDataTable());
/// ignore-- testing.
//if ((queryTable == null) || (queryTable.Rows.Count == 0) && (((_type == null) || (_type.Contains("Module", StringComparer.OrdinalIgnoreCase) || _type.Contains("Script", StringComparer.OrdinalIgnoreCase))) && ((_tags == null) || (_tags.Length == 0))))
//{
// queryTable = metadataTable;
//}
List<IEnumerable<DataRow>> allFoundPkgs = new List<IEnumerable<DataRow>>();
allFoundPkgs.Add(finalQueryResults);
// Need to handle includeDependencies
if (_includeDependencies)
{
foreach (var pkg in finalQueryResults)
{
//allFoundPkgs.Add(DependencyFinder(finalQueryResults, dependenciesTable));
}
}
IEnumerable<DataRow> flattenedFoundPkgs = (IEnumerable<DataRow>)allFoundPkgs.Flatten();
// (IEnumerable<DataRow>)
return flattenedFoundPkgs;
}
/*********************** come back to this
private IEnumerable<DataRow> DependencyFinder(IEnumerable<DataRow> finalQueryResults, DataTable dependenciesTable )
{
List<IEnumerable<PackageMetadataAllTables>> foundDependencies = new List<IEnumerable<IPackageSearchMetadata>>();
var queryResultsDT = finalQueryResults.ToDataTable();
//var dependencyResults = from t0 in metadataTable.AsEnumerable()
var dependencyResults = from t0 in queryResultsDT.AsEnumerable()
join t1 in dependenciesTable.AsEnumerable()
on t0.Field<string>("Key") equals t1.Field<string>("Key")
select new PackageMetadataAllTables
{
Key = t0["Key"],
Name = t0["Name"],
Version = t0["Version"],
Type = (string)t0["Type"],
Description = t0["Description"],
Author = t0["Author"],
Copyright = t0["Copyright"],
PublishedDate = t0["PublishedDate"],
InstalledDate = t0["InstalledDate"],
UpdatedDate = t0["UpdatedDate"],
LicenseUri = t0["LicenseUri"],
ProjectUri = t0["ProjectUri"],
IconUri = t0["IconUri"],
PowerShellGetFormatVersion = t0["PowerShellGetFormatVersion"],
ReleaseNotes = t0["ReleaseNotes"],
RepositorySourceLocation = t0["RepositorySourceLocation"],
Repository = t0["Repository"],
IsPrerelease = t0["IsPrerelease"],
Dependencies = (Dependency)t1["Dependencies"],
};
var dependencyPredicate = PredicateBuilder.New<DataRow>(true);
DataTable joinedDependencyTable = dependencyResults.ToDataTable();
// Build predicate by combining names of dependencies searches with 'or'
// public string Name { get; set; }
// public string MinimumVersion { get; set; }
// public string MaximumVersion { get; set; }
// for each pkg that was found, check to see if it has a dep
foreach (var pkg in dependencyResults)
{
// because it's an ienumerable, we need to pull out the pkg itself to access its properties, but there is only a 'default' option
if (!string.IsNullOrEmpty(pkg.Dependencies.Name))
{
// you could just add the data row
foundDependencies.Add((IEnumerable<PackageMetadataAllTables>) pkg);
}
// and then check to make sure dep name/version exists within the cache (via the metadata table)
// call helper recursively
// (IEnumerable<DataRow> finalQueryResults, DataTable dependenciesTable )
DependencyFinder(pkg, dependencyResults, dependenciesTable)
var roleCapabilityPredicate = PredicateBuilder.New<DataRow>(true);
DataTable joinedRoleCapabilityTable = roleCapabilityResults.ToDataTable();
// Build predicate by combining names of commands searches with 'or'
// if no name is specified, we'll return all (?)
foreach (string n in _name)
{
roleCapabilityPredicate = roleCapabilityPredicate.Or(pkg => pkg.Field<string>("RoleCapability").Equals(n));
}
// final results -- All the appropriate pkgs with these tags
var roleCapabilitiesRowCollection = joinedRoleCapabilityTable.AsEnumerable().Where(roleCapabilityPredicate).Select(p => p);
// Add row collection to final table to be queried
queryTable.Merge(roleCapabilitiesRowCollection.ToDataTable());
}
// final results -- All the
var dependencies = joinedDependencyTable.AsEnumerable().Where(dependencyPredicate).Select(p => p);
return
}
***************/
private ExpressionStarter<DataRow> BuildPredicate(string repository)
{
//NuGetVersion nugetVersion0;
var predicate = PredicateBuilder.New<DataRow>(true);
if (_type != null)
{
var typePredicate = PredicateBuilder.New<DataRow>(true);
if (_type.Contains("Script", StringComparer.OrdinalIgnoreCase))
{
typePredicate = typePredicate.Or(pkg => pkg.Field<string>("Type").Equals("Script"));
}
if (_type.Contains("Module", StringComparer.OrdinalIgnoreCase))
{
typePredicate = typePredicate.Or(pkg => pkg.Field<string>("Type").Equals("Module"));
}
predicate.And(typePredicate);
}
ExpressionStarter<DataRow> starter2 = PredicateBuilder.New<DataRow>(true);
if (_moduleName != null)
{
predicate = predicate.And(pkg => pkg.Field<string>("Name").Equals(_moduleName));
}
if ((_type == null) || ((_type.Length == 0) || !(_type.Contains("Module", StringComparer.OrdinalIgnoreCase) || _type.Contains("Script", StringComparer.OrdinalIgnoreCase))))
{
var typeNamePredicate = PredicateBuilder.New<DataRow>(true);
foreach (string name in _name)
{
//// ?
typeNamePredicate = typeNamePredicate.Or(pkg => pkg.Field<string>("Type").Equals("Script"));
}
}
// cache will only contain the latest stable and latest prerelease of each package
if (_version != null)
{
NuGetVersion nugetVersion;
//VersionRange versionRange = VersionRange.Parse(version);
if (NuGetVersion.TryParse(_version, out nugetVersion))
{
predicate = predicate.And(pkg => pkg.Field<string>("Version").Equals(nugetVersion));
}
}
if (!_prerelease)
{
predicate = predicate.And(pkg => pkg.Field<string>("IsPrerelease").Equals("false")); // consider checking if it IS prerelease
}
return predicate;
}
private List<IEnumerable<IPackageSearchMetadata>> FindPackagesFromSourceHelper(string repoName, string repositoryUrl, string name, PackageSearchResource pkgSearchResource, PackageMetadataResource pkgMetadataResource, SearchFilter searchFilter, SourceCacheContext srcContext)
{
List<IEnumerable<IPackageSearchMetadata>> foundPackages = new List<IEnumerable<IPackageSearchMetadata>>();
List<IEnumerable<IPackageSearchMetadata>> filteredFoundPkgs = new List<IEnumerable<IPackageSearchMetadata>>();
List<IEnumerable<IPackageSearchMetadata>> scriptPkgsNotNeeded = new List<IEnumerable<IPackageSearchMetadata>>();
char[] delimiter = new char[] { ' ', ',' };
// If module name is specified, use that as the name for the pkg to search for
if (_moduleName != null)
{
// may need to take 1
foundPackages.Add(pkgMetadataResource.GetMetadataAsync(_moduleName, _prerelease, false, srcContext, NullLogger.Instance, cancellationToken).GetAwaiter().GetResult());
//foundPackages = pkgMetadataResource.GetMetadataAsync(_moduleName, _prerelease, false, srcContext, NullLogger.Instance, cancellationToken).GetAwaiter().GetResult();
}
else if (name != null)
{
// If a resource name is specified, search for that particular pkg name
if (!name.Contains("*"))
{
IEnumerable<IPackageSearchMetadata> retrievedPkgs = null;
try
{
retrievedPkgs = pkgMetadataResource.GetMetadataAsync(name, _prerelease, false, srcContext, NullLogger.Instance, cancellationToken).GetAwaiter().GetResult();
}
catch { }
if (retrievedPkgs == null || retrievedPkgs.Count() == 0)
{
this.WriteVerbose(string.Format("'{0}' could not be found in repository '{1}'", name, repoName));
return foundPackages;
}
else
{
foundPackages.Add(retrievedPkgs);
}
}
// search for range of pkg names
else
{
// TODO: follow up on this
//foundPackages.Add(pkgSearchResource.SearchAsync(name, searchFilter, 0, 6000, NullLogger.Instance, cancellationToken).GetAwaiter().GetResult());
name = name.Equals("*") ? "" : name; // can't use * in v3 protocol
var wildcardPkgs = pkgSearchResource.SearchAsync(name, searchFilter, 0, 6000, NullLogger.Instance, cancellationToken).GetAwaiter().GetResult();
// If not searching for *all* packages
if (!name.Equals("") && !name[0].Equals('*'))
{
char[] wildcardDelimiter = new char[] { '*' };
var tokenizedName = name.Split(wildcardDelimiter, StringSplitOptions.RemoveEmptyEntries);
//var startsWithWildcard = name[0].Equals('*') ? true : false;
//var endsWithWildcard = name[name.Length-1].Equals('*') ? true : false;
// 1) *owershellge*
if (name.StartsWith("*") && name.EndsWith("*"))
{
// filter results
foundPackages.Add(wildcardPkgs.Where(p => p.Identity.Id.Contains(tokenizedName[0])));
if (foundPackages.Flatten().Any())
{
pkgsLeftToFind.Remove(name);
}
// .Where(p => versionRange.Satisfies(p.Identity.Version))
// .OrderByDescending(p => p.Identity.Version, VersionComparer.VersionRelease));
}
// 2) *erShellGet
else if (name.StartsWith("*"))
{
// filter results
foundPackages.Add(wildcardPkgs.Where(p => p.Identity.Id.EndsWith(tokenizedName[0])));
if (foundPackages.Flatten().Any())
{
pkgsLeftToFind.Remove(name);
}
}
// if 1) PowerShellG*
else if (name.EndsWith("*"))
{
// filter results
foundPackages.Add(wildcardPkgs.Where(p => p.Identity.Id.StartsWith(tokenizedName[0])));
if (foundPackages.Flatten().Any())
{
pkgsLeftToFind.Remove(name);
}
}
// 3) Power*Get
else if (tokenizedName.Length == 2)
{
// filter results
foundPackages.Add(wildcardPkgs.Where(p => p.Identity.Id.StartsWith(tokenizedName[0]) && p.Identity.Id.EndsWith(tokenizedName[1])));
if (foundPackages.Flatten().Any())
{
pkgsLeftToFind.Remove("*");
}
}
}
else
{
foundPackages.Add(wildcardPkgs);
pkgsLeftToFind.Remove("*");
}
}
}
else
{
/* can probably get rid of this */
foundPackages.Add(pkgSearchResource.SearchAsync("", searchFilter, 0, 6000, NullLogger.Instance, cancellationToken).GetAwaiter().GetResult());
//foundPackages = pkgSearchResource.SearchAsync("", searchFilter, 0, 6000, NullLogger.Instance, cancellationToken).GetAwaiter().GetResult();
}
//use either ModuleName or Name (whichever not null) to prevent id error
var nameVal = name == null ? _moduleName : name;
// Check version first to narrow down the number of pkgs before potentially searching through tags
if (_version != null && nameVal != null)
{
if (_version.Equals("*"))
{
// ensure that the latst version is returned first (the ordering of versions differ)
if(_moduleName != null)
{
// perform checks for PSModule before adding to filteredFoundPackages
filteredFoundPkgs.Add(pkgMetadataResource.GetMetadataAsync(nameVal, _prerelease, false, srcContext, NullLogger.Instance, cancellationToken).GetAwaiter().GetResult()
.Where(p => p.Tags.Split(delimiter, StringSplitOptions.RemoveEmptyEntries).Contains("PSModule"))
.OrderByDescending(p => p.Identity.Version, VersionComparer.VersionRelease));
scriptPkgsNotNeeded.Add(pkgMetadataResource.GetMetadataAsync(nameVal, _prerelease, false, srcContext, NullLogger.Instance, cancellationToken).GetAwaiter().GetResult()
.Where(p => p.Tags.Split(delimiter, StringSplitOptions.RemoveEmptyEntries).Contains("PSScript"))
.OrderByDescending(p => p.Identity.Version, VersionComparer.VersionRelease));
scriptPkgsNotNeeded.RemoveAll(p => true);
}
else
{ //name != null
filteredFoundPkgs.Add(pkgMetadataResource.GetMetadataAsync(nameVal, _prerelease, false, srcContext, NullLogger.Instance, cancellationToken).GetAwaiter().GetResult().OrderByDescending(p => p.Identity.Version, VersionComparer.VersionRelease));
}
}
else
{
// try to parse into a singular NuGet version
NuGetVersion specificVersion;
NuGetVersion.TryParse(_version, out specificVersion);
foundPackages.RemoveAll(p => true);
VersionRange versionRange = null;
//todo: fix! when the Version is inputted as "[2.0]" it doesnt get parsed by TryParse() returns null
if (specificVersion != null)
{
// exact version
versionRange = new VersionRange(specificVersion, true, specificVersion, true, null, null);
}
else
{
// maybe try catch this
// check if version range
versionRange = VersionRange.Parse(_version);
}
// Search for packages within a version range
// ensure that the latst version is returned first (the ordering of versions differ
// test wth Find-PSResource 'Carbon' -Version '[,2.4.0)'
foundPackages.Add(pkgMetadataResource.GetMetadataAsync(nameVal, _prerelease, false, srcContext, NullLogger.Instance, cancellationToken).GetAwaiter().GetResult()
.Where(p => versionRange.Satisfies(p.Identity.Version))
.OrderByDescending(p => p.Identity.Version, VersionComparer.VersionRelease));
// TODO: TEST AFTER CHANGES
// choose the most recent version -- it's not doing this right now
//int toRemove = foundPackages.First().Count() - 1;
//var singlePkg = (System.Linq.Enumerable.SkipLast(foundPackages.FirstOrDefault(), toRemove));
var pkgList = foundPackages.FirstOrDefault();
var singlePkg = Enumerable.Repeat(pkgList.FirstOrDefault(), 1);
if(singlePkg != null)
{
if(_moduleName != null)
{
var tags = singlePkg.First().Tags.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
if(tags.Contains("PSModule"))
{
filteredFoundPkgs.Add(singlePkg);
}
}
else if(_name != null)
{
filteredFoundPkgs.Add(singlePkg);
}
}
}
}
else // version is null
{
// if version is null, but there we want to return multiple packages (muliple names), skip over this step of removing all but the lastest package/version:
if ((name != null && !name.Contains("*")) || _moduleName != null)
{
// choose the most recent version -- it's not doing this right now
int toRemove = foundPackages.First().Count() - 1;
//to prevent NullException
if(toRemove >= 0)
{
var pkgList = foundPackages.FirstOrDefault();
var singlePkg = Enumerable.Repeat(pkgList.FirstOrDefault(), 1);
//if it was a ModuleName then check if the Tag is PSModule and only add then
var tags = singlePkg.First().Tags.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
if(_moduleName != null){
if(tags.Contains("PSModule")){
filteredFoundPkgs.Add(singlePkg);
}
}
else
{ // _name != null
filteredFoundPkgs.Add(singlePkg);
}
}
}
else
{ //if name not null,but name contains * and version is null
filteredFoundPkgs = foundPackages;
}
}
// TAGS
/// should move this to the last thing that gets filtered
var flattenedPkgs = filteredFoundPkgs.Flatten().ToList();
if (_tags != null)
{
// clear filteredfoundPkgs because we'll just be adding back the pkgs we we
filteredFoundPkgs.RemoveAll(p => true);
var pkgsFilteredByTags = new List<IPackageSearchMetadata>();
foreach (IPackageSearchMetadata p in flattenedPkgs)
{
// Enumerable.ElementAt(0)
var tagArray = p.Tags.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
foreach (string t in _tags)
{
// if the pkg contains one of the tags we're searching for
if (tagArray.Contains(t, StringComparer.OrdinalIgnoreCase))
{
pkgsFilteredByTags.Add(p);
}
}
}
// make sure just adding one pkg if not * versions
if (_version != "*")
{
filteredFoundPkgs.Add(pkgsFilteredByTags.DistinctBy(p => p.Identity.Id));
}
else
{
// if we want all version, make sure there's only one package id/version in the returned list.
filteredFoundPkgs.Add(pkgsFilteredByTags.DistinctBy(p => p.Identity.Version));
}
}
// optimizes searcching by
if ((_type != null || !filteredFoundPkgs.Flatten().Any()) && pkgsLeftToFind.Any() && !_name.Contains("*"))
{
//if ((_type.Contains("Module") || _type.Contains("Script")) && !_type.Contains("DscResource") && !_type.Contains("Command") && !_type.Contains("RoleCapability"))
if (_type == null || _type.Contains("DscResource") || _type.Contains("Command") || _type.Contains("RoleCapability"))
{
if (!filteredFoundPkgs.Flatten().Any())
{
filteredFoundPkgs.Add(pkgSearchResource.SearchAsync("", searchFilter, 0, 6000, NullLogger.Instance, cancellationToken).GetAwaiter().GetResult());
}
var tempList = (FilterPkgsByResourceType(filteredFoundPkgs));
filteredFoundPkgs.RemoveAll(p => true);
filteredFoundPkgs.Add(tempList);
}
}
// else type == null
// Search for dependencies
if (_includeDependencies && filteredFoundPkgs.Any())
{
List<IEnumerable<IPackageSearchMetadata>> foundDependencies = new List<IEnumerable<IPackageSearchMetadata>>();
// need to parse the depenency and version and such
var filteredFoundPkgsFlattened = filteredFoundPkgs.Flatten();
foreach (IPackageSearchMetadata pkg in filteredFoundPkgsFlattened)
{
// need to improve this later
// this function recursively finds all dependencies
// change into an ieunumerable (helpful for the finddependenciesfromsource function)
foundDependencies.AddRange(FindDependenciesFromSource(Enumerable.Repeat(pkg, 1), pkgMetadataResource, srcContext));
}
filteredFoundPkgs.AddRange(foundDependencies);
}
// return foundPackages;
return filteredFoundPkgs;
}
private List<IEnumerable<IPackageSearchMetadata>> FindDependenciesFromSource(IEnumerable<IPackageSearchMetadata> pkg, PackageMetadataResource pkgMetadataResource, SourceCacheContext srcContext)
{
/// dependency resolver
///
/// this function will be recursively called
///
/// call the findpackages from source helper (potentially generalize this so it's finding packages from source or cache)
///
List<IEnumerable<IPackageSearchMetadata>> foundDependencies = new List<IEnumerable<IPackageSearchMetadata>>();
// 1) check the dependencies of this pkg
// 2) for each dependency group, search for the appropriate name and version
// a dependency group are all the dependencies for a particular framework
// first or default because we need this pkg to be an ienumerable (so we don't need to be doing strange object conversions)
foreach (var dependencyGroup in pkg.FirstOrDefault().DependencySets)
{
//dependencyGroup.TargetFramework
//dependencyGroup.
foreach (var pkgDependency in dependencyGroup.Packages)
{
// 2.1) check that the appropriate pkg dependencies exist
// returns all versions from a single package id.
var dependencies = pkgMetadataResource.GetMetadataAsync(pkgDependency.Id, _prerelease, true, srcContext, NullLogger.Instance, cancellationToken).GetAwaiter().GetResult();
// then 2.2) check if the appropriate verion range exists (if version exists, then add it to the list to return)
VersionRange versionRange = null;
// to ensure a null OriginalString isn't being parsed which will result in an error being thrown and caught
// if OriginalString is null, versionRange will remain null and default version will be installed.
if(pkgDependency.VersionRange.OriginalString != null){
try
{
versionRange = VersionRange.Parse(pkgDependency.VersionRange.OriginalString);
}
catch
{
Console.WriteLine("Error parsing version range");
}
}
// choose the most recent version
int toRemove = dependencies.Count() - 1;
// if no version/version range is specified the we just return the latest version
var depPkgToReturn = (versionRange == null ?
dependencies.FirstOrDefault() :
dependencies.Where(v => versionRange.Satisfies(v.Identity.Version)).FirstOrDefault());
// using the repeat function to convert the IPackageSearchMetadata object into an enumerable.
foundDependencies.Add(Enumerable.Repeat(depPkgToReturn, 1));
// 3) search for any dependencies the pkg has
foundDependencies.AddRange(FindDependenciesFromSource(Enumerable.Repeat(depPkgToReturn, 1), pkgMetadataResource, srcContext));
}
}
// flatten after returning
return foundDependencies;
}
private List<IPackageSearchMetadata> FilterPkgsByResourceType(List<IEnumerable<IPackageSearchMetadata>> filteredFoundPkgs)
{
char[] delimiter = new char[] { ' ', ',' };
// If there are any packages that were filtered by tags, we'll continue to filter on those packages, otherwise, we'll filter on all the packages returned from the search
var flattenedPkgs = filteredFoundPkgs.Flatten();
var pkgsFilteredByResource = new List<IPackageSearchMetadata>();
// if the type is null, we'll set it to check for everything except modules and scripts, since those types were already checked.
_type = _type == null ? new string[] { "DscResource", "RoleCapability", "Command" } : _type;
string[] pkgsToFind = new string[5];
pkgsLeftToFind.CopyTo(pkgsToFind);
foreach (IPackageSearchMetadata pkg in flattenedPkgs)
{
// Enumerable.ElementAt(0)
var tagArray = pkg.Tags.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
// check modules and scripts here ??
foreach (var tag in tagArray)
{
// iterate through type array
foreach (var resourceType in _type)
{
switch (resourceType)
{
case "Module":
if (tag.Equals("PSModule"))
{
pkgsFilteredByResource.Add(pkg);
}
break;
case "Script":
if (tag.Equals("PSScript"))
{
pkgsFilteredByResource.Add(pkg);
}
break;
case "Command":
if (tag.StartsWith("PSCommand_"))
{
foreach (var resourceName in pkgsToFind)
{
if (tag.Equals("PSCommand_" + resourceName, StringComparison.OrdinalIgnoreCase))
{
pkgsFilteredByResource.Add(pkg);
pkgsLeftToFind.Remove(resourceName);
}
}
}
break;
case "DscResource":
if (tag.StartsWith("PSDscResource_"))
{
foreach (var resourceName in pkgsToFind)
{
if (tag.Equals("PSDscResource_" + resourceName, StringComparison.OrdinalIgnoreCase))
{
pkgsFilteredByResource.Add(pkg);
pkgsLeftToFind.Remove(resourceName);
}
}
}
break;
case "RoleCapability":
if (tag.StartsWith("PSRoleCapability_"))
{
foreach (var resourceName in pkgsToFind)
{
if (tag.Equals("PSRoleCapability_" + resourceName, StringComparison.OrdinalIgnoreCase))
{
pkgsFilteredByResource.Add(pkg);
pkgsLeftToFind.Remove(resourceName);
}
}
}
break;
}
}
}
}
return pkgsFilteredByResource.DistinctBy(p => p.Identity.Id).ToList();
}
/***
private static async Task<Uri> GetCatalogIndexUrlAsync(string sourceUrl)
{
// This code uses the NuGet client SDK, which are the libraries used internally by the official
// NuGet client.
var sourceRepository = NuGet.Protocol.Core.Types.Repository.Factory.GetCoreV3(sourceUrl);
var serviceIndex = await sourceRepository.GetResourceAsync<ServiceIndexResourceV3>();
var catalogIndexUrl = serviceIndex.GetServiceEntryUri("Catalog/3.0.0");
return catalogIndexUrl;
}
*/
/// Modified this
private static DateTime GetCursor()
{
/*
try
{
var cursorString = File.ReadAllText(CursorFileName);
var cursor = JsonConvert.DeserializeObject<FileCursor>(cursorString);
var cursorValue = cursor.GetAsync().GetAwaiter().GetResult().GetValueOrDefault();
DateTime cursorValueDateTime = DateTime.MinValue;
if (cursorValue != null)
{
cursorValueDateTime = cursorValue.DateTime;
}
Console.WriteLine($"Read cursor value: {cursorValueDateTime}.");
return cursorValueDateTime;
}
catch (FileNotFoundException)
{
*/
var value = DateTime.MinValue;
Console.WriteLine($"No cursor found. Defaulting to {value}.");
return value;
// }
}
/***
private static void ProcessCatalogLeaf(CatalogLeafItem leaf)
{
// Here, you can do whatever you want with each catalog item. If you want the full metadata about
// the catalog leaf, you can use the leafItem.Url property to fetch the full leaf document. In this case,
// we'll just keep it simple and output the details about the leaf that are included in the catalog page.
// example: Console.WriteLine($"{leaf.CommitTimeStamp}: {leaf.Id} {leaf.Version} (type is {leaf.Type})");
Console.WriteLine($"{leaf.CommitTimestamp}: {leaf.PackageId} {leaf.PackageVersion} (type is {leaf.Type})");
}
private static void SetCursor(DateTime value)
{
Console.WriteLine($"Writing cursor value: {value}.");
var cursorString = JsonConvert.SerializeObject(new Cursor { Value = value });
File.WriteAllText(CursorFileName, cursorString);
}
*/
}
public class Cursor
{
[JsonProperty("value")]
public DateTime Value { get; set; }
}
}
| 45.188806 | 282 | 0.514168 | [
"MIT"
] | SteveL-MSFT/PowerShellGet | src/FindPSResource.cs | 67,017 | C# |
// Copyright (c) TotalSoft.
// This source code is licensed under the MIT license.
using System;
namespace NBB.Messaging.Abstractions
{
public interface ITopicRegistry
{
string GetTopicForMessageType(Type messageType, bool includePrefix = true);
string GetTopicForName(string topicName, bool includePrefix = true);
string GetTopicPrefix();
}
}
| 26.466667 | 84 | 0.692695 | [
"MIT"
] | VCuzmin/nbb | src/Messaging/NBB.Messaging.Abstractions/ITopicRegistry.cs | 399 | C# |
using Microsoft.Azure.Management.ApiManagement.ArmTemplates.Common.Constants;
using Microsoft.Azure.Management.ApiManagement.ArmTemplates.Common.TemplateModels;
using Microsoft.Azure.Management.ApiManagement.ArmTemplates.Creator.Models;
namespace Microsoft.Azure.Management.ApiManagement.ArmTemplates.Custom.Creator.TemplateCreators
{
public class DiagnosticTemplateCreator
{
public DiagnosticTemplateResource CreateAPIDiagnosticTemplateResource(APIConfig api, string[] dependsOn)
{
// create diagnostic resource with properties
DiagnosticTemplateResource diagnosticTemplateResource = new DiagnosticTemplateResource()
{
Name = $"[concat(parameters('{ParameterNames.ApimServiceName}'), '/{api.name}/{api.diagnostic.name}')]",
Type = ResourceTypeConstants.APIDiagnostic,
ApiVersion = GlobalConstants.ApiVersion,
Properties = new DiagnosticTemplateProperties()
{
alwaysLog = api.diagnostic.alwaysLog,
sampling = api.diagnostic.sampling,
frontend = api.diagnostic.frontend,
backend = api.diagnostic.backend,
enableHttpCorrelationHeaders = api.diagnostic.enableHttpCorrelationHeaders
},
DependsOn = dependsOn
};
// reference the provided logger if loggerId is provided
if (api.diagnostic.loggerId != null)
{
diagnosticTemplateResource.Properties.loggerId = $"[resourceId('Microsoft.ApiManagement/service/loggers', parameters('{ParameterNames.ApimServiceName}'), parameters('{Common.Constants.GlobalConstants.ParameterNames.LoggerName}'))]";
}
return diagnosticTemplateResource;
}
}
}
| 51.472222 | 248 | 0.665947 | [
"MIT"
] | ajaysoni-cap/azure-api-management-devops-resource-kit | src/ArmTemplates.Custom/Creator/TemplateCreators/DiagnosticTemplateCreator.cs | 1,855 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AVLTree
{
interface IFirstLastList
{
}
}
| 13.923077 | 33 | 0.740331 | [
"MIT"
] | tonkatawe/Data-structure | 07. Data-Structures-AVL-Trees-AA-Trees/AVLTree/IFirstLastList.cs | 183 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.