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 |
---|---|---|---|---|---|---|---|---|
#region Copyright notice and license
// Copyright 2019 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Net.Compression;
namespace Grpc.Net.Client.Internal
{
internal static class GrpcProtocolHelpers
{
public static byte[] ParseBinaryHeader(string base64)
{
string decodable;
switch (base64.Length % 4)
{
case 0:
// base64 has the required padding
decodable = base64;
break;
case 2:
// 2 chars padding
decodable = base64 + "==";
break;
case 3:
// 3 chars padding
decodable = base64 + "=";
break;
default:
// length%4 == 1 should be illegal
throw new FormatException("Invalid base64 header value");
}
return Convert.FromBase64String(decodable);
}
public static Metadata BuildMetadata(HttpResponseHeaders responseHeaders)
{
var headers = new Metadata();
foreach (var header in responseHeaders)
{
// ASP.NET Core includes pseudo headers in the set of request headers
// whereas, they are not in gRPC implementations. We will filter them
// out when we construct the list of headers on the context.
if (header.Key.StartsWith(':'))
{
continue;
}
// Exclude grpc related headers
if (header.Key.StartsWith("grpc-", StringComparison.OrdinalIgnoreCase))
{
continue;
}
foreach (var value in header.Value)
{
if (header.Key.EndsWith(Metadata.BinaryHeaderSuffix, StringComparison.OrdinalIgnoreCase))
{
headers.Add(header.Key, ParseBinaryHeader(value));
}
else
{
headers.Add(header.Key, value);
}
}
}
return headers;
}
private const int MillisecondsPerSecond = 1000;
/* round an integer up to the next value with three significant figures */
private static long TimeoutRoundUpToThreeSignificantFigures(long x)
{
if (x < 1000) return x;
if (x < 10000) return RoundUp(x, 10);
if (x < 100000) return RoundUp(x, 100);
if (x < 1000000) return RoundUp(x, 1000);
if (x < 10000000) return RoundUp(x, 10000);
if (x < 100000000) return RoundUp(x, 100000);
if (x < 1000000000) return RoundUp(x, 1000000);
return RoundUp(x, 10000000);
static long RoundUp(long x, long divisor)
{
return (x / divisor + Convert.ToInt32(x % divisor != 0)) * divisor;
}
}
private static string FormatTimeout(long value, char ext)
{
return value.ToString(CultureInfo.InvariantCulture) + ext;
}
private static string EncodeTimeoutSeconds(long sec)
{
if (sec % 3600 == 0)
{
return FormatTimeout(sec / 3600, 'H');
}
else if (sec % 60 == 0)
{
return FormatTimeout(sec / 60, 'M');
}
else
{
return FormatTimeout(sec, 'S');
}
}
private static string EncodeTimeoutMilliseconds(long x)
{
x = TimeoutRoundUpToThreeSignificantFigures(x);
if (x < MillisecondsPerSecond)
{
return FormatTimeout(x, 'm');
}
else
{
if (x % MillisecondsPerSecond == 0)
{
return EncodeTimeoutSeconds(x / MillisecondsPerSecond);
}
else
{
return FormatTimeout(x, 'm');
}
}
}
public static string EncodeTimeout(long timeout)
{
if (timeout <= 0)
{
return "1n";
}
else if (timeout < 1000 * MillisecondsPerSecond)
{
return EncodeTimeoutMilliseconds(timeout);
}
else
{
return EncodeTimeoutSeconds(timeout / MillisecondsPerSecond + Convert.ToInt32(timeout % MillisecondsPerSecond != 0));
}
}
internal static string GetRequestEncoding(HttpRequestHeaders headers)
{
if (headers.TryGetValues(GrpcProtocolConstants.MessageEncodingHeader, out var encodingValues))
{
return encodingValues.First();
}
else
{
return GrpcProtocolConstants.IdentityGrpcEncoding;
}
}
internal static string GetGrpcEncoding(HttpResponseMessage response)
{
string grpcEncoding;
if (response.Headers.TryGetValues(GrpcProtocolConstants.MessageEncodingHeader, out var values))
{
grpcEncoding = values.First();
}
else
{
grpcEncoding = GrpcProtocolConstants.IdentityGrpcEncoding;
}
return grpcEncoding;
}
internal static string GetMessageAcceptEncoding(Dictionary<string, ICompressionProvider> compressionProviders)
{
if (compressionProviders == GrpcProtocolConstants.DefaultCompressionProviders)
{
return GrpcProtocolConstants.DefaultMessageAcceptEncodingValue;
}
return GrpcProtocolConstants.IdentityGrpcEncoding + "," + string.Join(',', compressionProviders.Select(p => p.Key));
}
internal static bool CanWriteCompressed(WriteOptions? writeOptions)
{
if (writeOptions == null)
{
return true;
}
var canCompress = (writeOptions.Flags & WriteFlags.NoCompress) != WriteFlags.NoCompress;
return canCompress;
}
internal static AuthInterceptorContext CreateAuthInterceptorContext(Uri baseAddress, IMethod method)
{
var authority = baseAddress.Authority;
if (baseAddress.Scheme == Uri.UriSchemeHttps && authority.EndsWith(":443", StringComparison.Ordinal))
{
// The service URL can be used by auth libraries to construct the "aud" fields of the JWT token,
// so not producing serviceUrl compatible with other gRPC implementations can lead to auth failures.
// For https and the default port 443, the port suffix should be stripped.
// https://github.com/grpc/grpc/blob/39e982a263e5c48a650990743ed398c1c76db1ac/src/core/lib/security/transport/client_auth_filter.cc#L205
authority = authority.Substring(0, authority.Length - 4);
}
var serviceUrl = baseAddress.Scheme + "://" + authority + baseAddress.AbsolutePath;
if (!serviceUrl.EndsWith("/", StringComparison.Ordinal))
{
serviceUrl += "/";
}
serviceUrl += method.ServiceName;
return new AuthInterceptorContext(serviceUrl, method.Name);
}
internal async static Task ReadCredentialMetadata(
DefaultCallCredentialsConfigurator configurator,
GrpcChannel channel,
HttpRequestMessage message,
IMethod method,
CallCredentials credentials)
{
credentials.InternalPopulateConfiguration(configurator, null);
if (configurator.Interceptor != null)
{
var authInterceptorContext = GrpcProtocolHelpers.CreateAuthInterceptorContext(channel.Address, method);
var metadata = new Metadata();
await configurator.Interceptor(authInterceptorContext, metadata).ConfigureAwait(false);
foreach (var entry in metadata)
{
AddHeader(message.Headers, entry);
}
}
if (configurator.Credentials != null)
{
// Copy credentials locally. ReadCredentialMetadata will update it.
var callCredentials = configurator.Credentials;
foreach (var c in callCredentials)
{
configurator.Reset();
await ReadCredentialMetadata(configurator, channel, message, method, c).ConfigureAwait(false);
}
}
}
public static void AddHeader(HttpRequestHeaders headers, Metadata.Entry entry)
{
var value = entry.IsBinary ? Convert.ToBase64String(entry.ValueBytes) : entry.Value;
headers.TryAddWithoutValidation(entry.Key, value);
}
public static string? GetHeaderValue(HttpHeaders? headers, string name)
{
if (headers == null)
{
return null;
}
if (!headers.TryGetValues(name, out var values))
{
return null;
}
// HttpHeaders appears to always return an array, but fallback to converting values to one just in case
var valuesArray = values as string[] ?? values.ToArray();
switch (valuesArray.Length)
{
case 0:
return null;
case 1:
return valuesArray[0];
default:
throw new InvalidOperationException($"Multiple {name} headers.");
}
}
public static Status GetResponseStatus(HttpResponseMessage httpResponse)
{
Status? status;
try
{
if (!TryGetStatusCore(httpResponse.TrailingHeaders, out status))
{
status = new Status(StatusCode.Cancelled, "No grpc-status found on response.");
}
}
catch (Exception ex)
{
// Handle error from parsing badly formed status
status = new Status(StatusCode.Cancelled, ex.Message);
}
return status.Value;
}
public static bool TryGetStatusCore(HttpResponseHeaders headers, [NotNullWhen(true)]out Status? status)
{
var grpcStatus = GrpcProtocolHelpers.GetHeaderValue(headers, GrpcProtocolConstants.StatusTrailer);
// grpc-status is a required trailer
if (grpcStatus == null)
{
status = null;
return false;
}
int statusValue;
if (!int.TryParse(grpcStatus, out statusValue))
{
throw new InvalidOperationException("Unexpected grpc-status value: " + grpcStatus);
}
// grpc-message is optional
// Always read the gRPC message from the same headers collection as the status
var grpcMessage = GrpcProtocolHelpers.GetHeaderValue(headers, GrpcProtocolConstants.MessageTrailer);
if (!string.IsNullOrEmpty(grpcMessage))
{
// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#responses
// The value portion of Status-Message is conceptually a Unicode string description of the error,
// physically encoded as UTF-8 followed by percent-encoding.
grpcMessage = Uri.UnescapeDataString(grpcMessage);
}
status = new Status((StatusCode)statusValue, grpcMessage);
return true;
}
}
}
| 35.821229 | 152 | 0.549595 | [
"Apache-2.0"
] | HaoK/grpc-dotnet | src/Grpc.Net.Client/Internal/GrpcProtocolHelpers.cs | 12,826 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SMS.Api.Domain;
namespace SMS.Api.Controllers
{
/// <summary>
/// Controller for SMS model.
/// </summary>
[Produces("application/json")]
[Route("api/[controller]")]
public class SMSController : Controller
{
/// <summary>
/// Private member of service for \rel SMS model
/// </summary>
private readonly ISMSService _smsService;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="smsService">Service for SMS model</param>
public SMSController(ISMSService smsService)
{
_smsService = smsService;
}
/// <summary>
/// Method that implements GET Http request.
/// </summary>
/// <returns>SMS list in JSON format</returns>
[HttpGet]
public async Task<IActionResult> Get()
{
var sms = await _smsService.GetAllReadyToSent();
return Json(sms);
}
/// <summary>
/// Method that implements POST Http request.
/// </summary>
/// <param name="request">Data for new object</param>
/// <returns>response: Created</returns>
[HttpPost("")]
public async Task<IActionResult> Post([FromBody]CreateSMS request)
{
await _smsService.AddNewAsync(request.Message, request.PhoneNumber, new DateTime(1000,10,10));
return Created("api/SMS", null);
}
/// <summary>
/// Method that implements DELETE Http request.
/// </summary>
/// <param name="id">Id of sms'</param>
/// <returns>response: NoContent</returns>
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(string id)
{
await _smsService.RemoveAsync(Guid.Parse(id));
return NoContent();
}
}
/// <summary>
/// Class needed for POST request. Contains data about new object.
/// </summary>
public class CreateSMS
{
/// <summary>
/// Text message for sms.
/// </summary>
public string Message { get; set; }
/// <summary>
/// Recipient's phone number.
/// </summary>
public string PhoneNumber { get; set; }
}
} | 28.928571 | 106 | 0.564198 | [
"MIT"
] | dyjakstefan/SMS-API | SMS-API/Controllers/SMSController.cs | 2,432 | C# |
namespace P09.PrintPartOfASCIITable
{
using System;
class Program
{
static void Main()
{
int firstLine = int.Parse(Console.ReadLine());
int secondLine = int.Parse(Console.ReadLine());
for (int i = firstLine; i <= secondLine; i++)
{
Console.Write((char)i + " ");
}
}
}
} | 21.555556 | 59 | 0.479381 | [
"MIT"
] | DIMITRINALU/SoftUni-Projects | C#Fundamentals/02. DataTypes/P09.PrintPartOfASCIITable/Program.cs | 390 | C# |
using ExaLearn.Dal.Database;
using ExaLearn.Dal.Entities;
using ExaLearn.Dal.Interfaces;
using Microsoft.EntityFrameworkCore;
using Shared.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace ExaLearn.Dal.Repositories
{
public class QuestionRepository : GenericRepository<Question>, IQuestionRepository
{
public QuestionRepository(ExaLearnDbContext appDbContext) : base(appDbContext)
{
}
public async Task<List<Question>> GetByExpressionAsync(Expression<Func<Question, bool>> expression, int take)
{
var questions = _appDbContext.Questions
.Where(expression)
.Include(x => x.Answers)
.OrderBy(g => Guid.NewGuid())
.Take(take);
return await questions.ToListAsync();
}
public async Task<List<Question>> GetGrammarQuestionsAsync(LevelType levelType)
{
Expression<Func<Question, bool>> takeGrammerQuestions = q => q.QuestionType == QuestionType.Grammar
&& q.LevelType == levelType
&& q.IsArchive != true;
return await GetByExpressionAsync(takeGrammerQuestions, 10);
}
public async Task<List<Question>> GetAuditionQuestionsAsync(LevelType levelType)
{
var url = _appDbContext.Questions
.Where(q => q.QuestionType == QuestionType.Audition
&& q.LevelType == levelType
&& q.IsArchive != true)
.Select(x => x.FileUrl)
.OrderBy(x => Guid.NewGuid())
.FirstOrDefault();
Expression<Func<Question, bool>> takeAuditionQuestions = q => q.QuestionType == QuestionType.Audition && q.LevelType == levelType && q.FileUrl == url;
return await GetByExpressionAsync(takeAuditionQuestions, 10);
}
public async Task<List<Question>> GetTopicsAsync()
{
Expression<Func<Question, bool>> takeEssayTopic = q => q.QuestionType == QuestionType.Topic;
return await GetByExpressionAsync(takeEssayTopic, 2);
}
public async Task<List<Question>> GetByExpressionAsync(Expression<Func<Question, bool>> expression)
{
var questions = _appDbContext.Questions
.Where(expression)
.Include(x => x.Answers)
.OrderBy(g => g.Id);
return await questions.ToListAsync();
}
public async Task<Question> GetQuestionByIdAsync(int id)
{
var question = _appDbContext.Questions
.Where(x => x.Id == id)
.Include(x => x.Answers)
.FirstAsync();
return await question;
}
}
} | 35.848101 | 162 | 0.606638 | [
"MIT"
] | ExadelSandbox/project | exalearn-api/ExaLearn.Dal/Repositories/QuestionRepository.cs | 2,834 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Metadata.Conventions;
using Microsoft.Data.Entity.Metadata.Conventions.Internal;
using Microsoft.Data.Entity.Metadata.Internal;
using Moq;
using Xunit;
namespace Microsoft.Data.Entity.Tests.Metadata.Conventions
{
public class ConventionDispatcherTest
{
[Fact]
public void OnEntityTypeAdded_calls_apply_on_conventions_in_order()
{
var conventions = new ConventionSet();
InternalEntityTypeBuilder entityTypeBuilder = null;
var convention = new Mock<IEntityTypeConvention>();
convention.Setup(c => c.Apply(It.IsAny<InternalEntityTypeBuilder>())).Returns<InternalEntityTypeBuilder>(b =>
{
Assert.NotNull(b);
entityTypeBuilder = new InternalEntityTypeBuilder(b.Metadata, b.ModelBuilder);
return entityTypeBuilder;
});
conventions.EntityTypeAddedConventions.Add(convention.Object);
var nullConvention = new Mock<IEntityTypeConvention>();
nullConvention.Setup(c => c.Apply(It.IsAny<InternalEntityTypeBuilder>())).Returns<InternalEntityTypeBuilder>(b =>
{
Assert.Same(entityTypeBuilder, b);
return null;
});
conventions.EntityTypeAddedConventions.Add(nullConvention.Object);
var extraConvention = new Mock<IEntityTypeConvention>();
extraConvention.Setup(c => c.Apply(It.IsAny<InternalEntityTypeBuilder>())).Returns<InternalEntityTypeBuilder>(b =>
{
Assert.False(true);
return null;
});
conventions.EntityTypeAddedConventions.Add(extraConvention.Object);
var builder = new InternalModelBuilder(new Model(), conventions);
Assert.Null(builder.Entity(typeof(Order), ConfigurationSource.Convention));
Assert.NotNull(entityTypeBuilder);
}
[Fact]
public void OnPropertyAdded_calls_apply_on_conventions_in_order()
{
var conventions = new ConventionSet();
InternalPropertyBuilder propertyBuilder = null;
var convention = new Mock<IPropertyConvention>();
convention.Setup(c => c.Apply(It.IsAny<InternalPropertyBuilder>())).Returns<InternalPropertyBuilder>(b =>
{
Assert.NotNull(b);
propertyBuilder = new InternalPropertyBuilder(b.Metadata, b.ModelBuilder, ConfigurationSource.Convention);
return propertyBuilder;
});
conventions.PropertyAddedConventions.Add(convention.Object);
var nullConvention = new Mock<IPropertyConvention>();
nullConvention.Setup(c => c.Apply(It.IsAny<InternalPropertyBuilder>())).Returns<InternalPropertyBuilder>(b =>
{
Assert.Same(propertyBuilder, b);
return null;
});
conventions.PropertyAddedConventions.Add(nullConvention.Object);
var extraConvention = new Mock<IPropertyConvention>();
extraConvention.Setup(c => c.Apply(It.IsAny<InternalPropertyBuilder>())).Returns<InternalPropertyBuilder>(b =>
{
Assert.False(true);
return null;
});
conventions.PropertyAddedConventions.Add(extraConvention.Object);
var builder = new InternalModelBuilder(new Model(), conventions);
var entityBuilder = builder.Entity(typeof(Order), ConfigurationSource.Convention);
var explicitKeyBuilder = entityBuilder.Property(typeof(int), "OrderId", ConfigurationSource.Convention);
Assert.Null(explicitKeyBuilder);
Assert.NotNull(propertyBuilder);
}
[Fact]
public void OnForeignKeyAdded_calls_apply_on_conventions_in_order()
{
var conventions = new ConventionSet();
InternalRelationshipBuilder relationsipBuilder = null;
var convention = new Mock<IForeignKeyConvention>();
convention.Setup(c => c.Apply(It.IsAny<InternalRelationshipBuilder>())).Returns<InternalRelationshipBuilder>(b =>
{
Assert.NotNull(b);
relationsipBuilder = new InternalRelationshipBuilder(b.Metadata, b.ModelBuilder, null);
return relationsipBuilder;
});
conventions.ForeignKeyAddedConventions.Add(convention.Object);
var nullConvention = new Mock<IForeignKeyConvention>();
nullConvention.Setup(c => c.Apply(It.IsAny<InternalRelationshipBuilder>())).Returns<InternalRelationshipBuilder>(b =>
{
Assert.Same(relationsipBuilder, b);
return null;
});
conventions.ForeignKeyAddedConventions.Add(nullConvention.Object);
var extraConvention = new Mock<IForeignKeyConvention>();
extraConvention.Setup(c => c.Apply(It.IsAny<InternalRelationshipBuilder>())).Returns<InternalRelationshipBuilder>(b =>
{
Assert.False(true);
return null;
});
conventions.ForeignKeyAddedConventions.Add(extraConvention.Object);
var builder = new InternalModelBuilder(new Model(), conventions);
var entityBuilder = builder.Entity(typeof(Order), ConfigurationSource.Convention);
entityBuilder.PrimaryKey(new[] { "OrderId" }, ConfigurationSource.Convention);
Assert.Null(entityBuilder.Relationship(typeof(Order), typeof(Order), null, null, ConfigurationSource.Convention));
Assert.NotNull(relationsipBuilder);
}
[Fact]
public void OnKeyAdded_calls_apply_on_conventions_in_order()
{
var conventions = new ConventionSet();
InternalKeyBuilder keyBuilder = null;
var convention = new Mock<IKeyConvention>();
convention.Setup(c => c.Apply(It.IsAny<InternalKeyBuilder>())).Returns<InternalKeyBuilder>(b =>
{
Assert.NotNull(b);
keyBuilder = new InternalKeyBuilder(b.Metadata, b.ModelBuilder);
return keyBuilder;
});
conventions.KeyAddedConventions.Add(convention.Object);
var nullConvention = new Mock<IKeyConvention>();
nullConvention.Setup(c => c.Apply(It.IsAny<InternalKeyBuilder>())).Returns<InternalKeyBuilder>(b =>
{
Assert.Same(keyBuilder, b);
return null;
});
conventions.KeyAddedConventions.Add(nullConvention.Object);
var extraConvention = new Mock<IKeyConvention>();
extraConvention.Setup(c => c.Apply(It.IsAny<InternalKeyBuilder>())).Returns<InternalKeyBuilder>(b =>
{
Assert.False(true);
return null;
});
conventions.KeyAddedConventions.Add(extraConvention.Object);
var builder = new InternalModelBuilder(new Model(), conventions);
var entityBuilder = builder.Entity(typeof(Order), ConfigurationSource.Convention);
var explicitKeyBuilder = entityBuilder.Key(new List<string> { "OrderId" }, ConfigurationSource.Convention);
Assert.Null(explicitKeyBuilder);
Assert.NotNull(keyBuilder);
}
[Fact]
public void OnForeignKeyRemoved_calls_apply_on_conventions_in_order()
{
var conventions = new ConventionSet();
var foreignKeyRemoved = false;
var convention = new Mock<IForeignKeyRemovedConvention>();
convention.Setup(c => c.Apply(It.IsAny<InternalEntityTypeBuilder>(), It.IsAny<ForeignKey>())).Callback(() => foreignKeyRemoved = true);
conventions.ForeignKeyRemovedConventions.Add(convention.Object);
var builder = new InternalModelBuilder(new Model(), conventions);
var entityBuilder = builder.Entity(typeof(Order), ConfigurationSource.Convention);
var foreignKey = new ForeignKey(
new[] { entityBuilder.Property(typeof(int), "FK", ConfigurationSource.Convention).Metadata },
entityBuilder.Key(new[] { entityBuilder.Property(typeof(int), "OrderId", ConfigurationSource.Convention).Metadata }, ConfigurationSource.Convention).Metadata,
entityBuilder.Metadata);
var conventionDispatcher = new ConventionDispatcher(conventions);
conventionDispatcher.OnForeignKeyRemoved(entityBuilder, foreignKey);
Assert.True(foreignKeyRemoved);
}
[Fact]
public void InitializingModel_calls_apply_on_conventions_in_order()
{
var conventions = new ConventionSet();
var nullConventionCalled = false;
InternalModelBuilder modelBuilder = null;
var convention = new Mock<IModelConvention>();
convention.Setup(c => c.Apply(It.IsAny<InternalModelBuilder>())).Returns<InternalModelBuilder>(b =>
{
Assert.NotNull(b);
modelBuilder = new InternalModelBuilder(b.Metadata, new ConventionSet());
return b;
});
conventions.ModelInitializedConventions.Add(convention.Object);
var nullConvention = new Mock<IModelConvention>();
nullConvention.Setup(c => c.Apply(It.IsAny<InternalModelBuilder>())).Returns<InternalModelBuilder>(b =>
{
nullConventionCalled = true;
return null;
});
conventions.ModelInitializedConventions.Add(nullConvention.Object);
var extraConvention = new Mock<IModelConvention>();
extraConvention.Setup(c => c.Apply(It.IsAny<InternalModelBuilder>())).Returns<InternalModelBuilder>(b =>
{
Assert.False(true);
return null;
});
conventions.ModelInitializedConventions.Add(extraConvention.Object);
var builder = new ModelBuilder(conventions);
Assert.NotNull(builder);
Assert.True(nullConventionCalled);
Assert.NotNull(modelBuilder);
}
[Fact]
public void ValidatingModel_calls_apply_on_conventions_in_order()
{
var conventions = new ConventionSet();
var nullConventionCalled = false;
InternalModelBuilder modelBuilder = null;
var convention = new Mock<IModelConvention>();
convention.Setup(c => c.Apply(It.IsAny<InternalModelBuilder>())).Returns<InternalModelBuilder>(b =>
{
Assert.NotNull(b);
modelBuilder = new InternalModelBuilder(b.Metadata, new ConventionSet());
return b;
});
conventions.ModelBuiltConventions.Add(convention.Object);
var nullConvention = new Mock<IModelConvention>();
nullConvention.Setup(c => c.Apply(It.IsAny<InternalModelBuilder>())).Returns<InternalModelBuilder>(b =>
{
nullConventionCalled = true;
return null;
});
conventions.ModelBuiltConventions.Add(nullConvention.Object);
var extraConvention = new Mock<IModelConvention>();
extraConvention.Setup(c => c.Apply(It.IsAny<InternalModelBuilder>())).Returns<InternalModelBuilder>(b =>
{
Assert.False(true);
return null;
});
conventions.ModelBuiltConventions.Add(extraConvention.Object);
var builder = new ModelBuilder(conventions).Validate();
Assert.NotNull(builder);
Assert.True(nullConventionCalled);
Assert.NotNull(modelBuilder);
}
private class Order
{
public int OrderId { get; set; }
}
}
}
| 43.419014 | 174 | 0.617306 | [
"Apache-2.0"
] | suryasnath/csharp | test/EntityFramework.Core.Tests/Metadata/ModelConventions/ConventionDispatcherTest.cs | 12,331 | C# |
using FlightControlApi.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace FlightControlModel.Repos
{
public class SeatRepo : CRUD
{
public SeatRepo(IDbConnection conn, IDbCommand comm) : base(conn, comm)
{
}
public Seat Get(int id)
{
Seat a;
_comm.CommandText = "SELECT * " +
"FROM Seat a " +
"WHERE a.Id = @id;";
_comm.AddParameter("@id", id);
_conn.Open();
try
{
using (IDataReader rdr = _comm.ExecuteReader())
{
rdr.Read();
a = new Seat()
{
Id = Convert.ToInt32(rdr["Id"]),
Num = Convert.ToInt32(rdr["Num"]),
PlaneId = Convert.ToInt32(rdr["PlaneId"]),
SeatClassId = Convert.ToInt32(rdr["SeatClassId"]),
};
}
_conn.Close();
return a;
}
catch (Exception ex)
{
throw ex;
}
finally
{
_comm.Parameters.Clear();
_conn.Close();
}
}
public List<Seat> GetAll()
{
List<int> allSeatsIDs = new List<int>();
List<Seat> allSeats = new List<Seat>();
_comm.CommandText = "SELECT * " +
"FROM Seat ";
_conn.Open();
try
{
using (IDataReader rdr = _comm.ExecuteReader())
{
while (rdr.Read())
{
allSeatsIDs.Add(Convert.ToInt32(rdr["Id"]));
allSeats.Add(new Seat()
{
Id = Convert.ToInt32(rdr["Id"]),
Num = Convert.ToInt32(rdr["Num"]),
PlaneId = Convert.ToInt32(rdr["PlaneId"]),
SeatClassId = Convert.ToInt32(rdr["SeatClassId"]),
});
}
}
_conn.Close();
//foreach (int id in allSeatsIDs)
//{
// allSeats.Add(this.Get(id));
//}
return allSeats;
}
catch (Exception ex)
{
throw ex;
}
finally
{
_conn.Close();
}
}
public int Insert(Seat p)
{
_comm.CommandText = "INSERT INTO Seat " +
"(Num, PlaneId, SeatClassId) " +
"VALUES " +
"(@num, @planeid, @seatclassid);" +
"SELECT SCOPE_IDENTITY();";
_comm.AddParameter("@id", p.Id);
_comm.AddParameter("@num", p.Num);
_comm.AddParameter("@planeid", p.PlaneId);
_comm.AddParameter("@seatclassid", p.SeatClassId);
_conn.Open();
try
{
int recordID = Convert.ToInt32(_comm.ExecuteScalar());
_comm.Parameters.Clear();
_conn.Close();
return recordID;
}
catch (Exception ex)
{
throw ex;
}
finally
{
_comm.Parameters.Clear();
_conn.Close();
}
}
public bool Update(int id, Seat p)
{
_comm.CommandText = "UPDATE Seat " +
"SET Num = @num, PlaneId = @planeid, SeatClassId = @seatclassid" +
"WHERE Id = @id ";
_comm.AddParameter("@id", p.Id);
_comm.AddParameter("@num", p.Num);
_comm.AddParameter("@planeid", p.PlaneId);
_comm.AddParameter("@seatclassid", p.SeatClassId);
_conn.Open();
try
{
_comm.ExecuteNonQuery();
_comm.Parameters.Clear();
_conn.Close();
return true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
_comm.Parameters.Clear();
_conn.Close();
}
}
public bool Delete(int id)
{
_comm.CommandText = "DELETE FROM Seat " +
"WHERE Seat.Id = @id;";
_comm.AddParameter("@id", id);
_conn.Open();
_trans = _conn.BeginTransaction();
_comm.Transaction = _trans;
try
{
_comm.ExecuteNonQuery();
_trans.Commit();
}
catch (Exception ex)
{
_trans.Rollback();
throw ex;
}
finally
{
_comm.Transaction = null;
_comm.Parameters.Clear();
_conn.Close();
}
return true;
}
}
}
| 25.832536 | 98 | 0.377292 | [
"MIT"
] | mZabcic/flightApi | FlightControlModel/Repos/SeatRepo.cs | 5,401 | C# |
/*******************************************************************************
* Copyright 2009-2016 Amazon Services. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
*
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at: http://aws.amazon.com/apache2.0
* 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.
*******************************************************************************
* Prep Details List
* API Version: 2010-10-01
* Library Version: 2016-10-05
* Generated: Wed Oct 05 06:15:39 PDT 2016
*/
using System;
using System.Xml;
using System.Collections.Generic;
using System.Xml.Serialization;
using Claytondus.AmazonMWS.Runtime;
namespace Claytondus.AmazonMWS.FbaInbound.Model
{
[XmlTypeAttribute(Namespace = "http://mws.amazonaws.com/FulfillmentInboundShipment/2010-10-01/")]
[XmlRootAttribute(Namespace = "http://mws.amazonaws.com/FulfillmentInboundShipment/2010-10-01/", IsNullable = false)]
public class PrepDetailsList : AbstractMwsObject
{
private List<PrepDetails> _prepDetails;
/// <summary>
/// Gets and sets the PrepDetails property.
/// </summary>
[XmlElementAttribute(ElementName = "PrepDetails")]
public List<PrepDetails> PrepDetails
{
get
{
if(this._prepDetails == null)
{
this._prepDetails = new List<PrepDetails>();
}
return this._prepDetails;
}
set { this._prepDetails = value; }
}
/// <summary>
/// Sets the PrepDetails property.
/// </summary>
/// <param name="prepDetails">PrepDetails property.</param>
/// <returns>this instance.</returns>
public PrepDetailsList WithPrepDetails(PrepDetails[] prepDetails)
{
this._prepDetails.AddRange(prepDetails);
return this;
}
/// <summary>
/// Checks if PrepDetails property is set.
/// </summary>
/// <returns>true if PrepDetails property is set.</returns>
public bool IsSetPrepDetails()
{
return this.PrepDetails.Count > 0;
}
public override void ReadFragmentFrom(IMwsReader reader)
{
_prepDetails = reader.ReadList<PrepDetails>("PrepDetails");
}
public override void WriteFragmentTo(IMwsWriter writer)
{
writer.WriteList("PrepDetails", _prepDetails);
}
public override void WriteTo(IMwsWriter writer)
{
writer.Write("http://mws.amazonaws.com/FulfillmentInboundShipment/2010-10-01/", "PrepDetailsList", this);
}
public PrepDetailsList() : base()
{
}
}
}
| 32.945652 | 121 | 0.588585 | [
"Apache-2.0"
] | claytondus/Claytondus.AmazonMWS | Claytondus.AmazonMWS.FbaInbound/Model/PrepDetailsList.cs | 3,031 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
namespace Aurochses.Xunit.AspNetCore.Mvc.Localization
{
/// <summary>
/// Class ModelLocalizationAssert.
/// </summary>
public class ModelLocalizationAssert
{
/// <summary>
/// Validates the models.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <param name="projectPath">The project path.</param>
/// <param name="resourcesDirectoryPath">The resources directory path.</param>
/// <param name="modelsDirectoryPath">The models directory path.</param>
/// <returns>List of LocalizedFileItems</returns>
public static List<LocalizedFileItem> Validate(Assembly assembly, string projectPath, string resourcesDirectoryPath = @"\Resources\Models", string modelsDirectoryPath = @"\Models")
{
var fileItems = FileItemHelpers.GetFileItems(projectPath, modelsDirectoryPath, "", "*.cs");
var localizedFileItems = new List<LocalizedFileItem>();
var namespaceRegex = new Regex(@"namespace (?<namespace>\S+)");
var classRegex = new Regex(@"public class (?<class>\S+)");
foreach (var fileItem in fileItems)
{
var content = File.ReadAllText(fileItem.GetFullPath());
var @namespace = namespaceRegex.Match(content).Groups["namespace"].Value;
var @class = classRegex.Match(content).Groups["class"].Value;
var type = assembly.GetType($"{@namespace}.{@class}");
var item = new LocalizedFileItem(projectPath, modelsDirectoryPath, fileItem.RelativePath, fileItem.FileName);
foreach (var property in type.GetRuntimeProperties())
{
var displayAttribute = property.GetCustomAttribute<DisplayAttribute>();
if (displayAttribute == null) continue;
if (!string.IsNullOrWhiteSpace(displayAttribute.Name)) item.Names.Add(displayAttribute.Name);
if (!string.IsNullOrWhiteSpace(displayAttribute.Prompt)) item.Names.Add(displayAttribute.Prompt);
if (!string.IsNullOrWhiteSpace(displayAttribute.Description)) item.Names.Add(displayAttribute.Description);
}
if (item.Names.Any()) localizedFileItems.Add(item);
}
LocalizationAssert.Validate(projectPath, resourcesDirectoryPath, localizedFileItems);
return localizedFileItems;
}
}
} | 43.032258 | 188 | 0.641679 | [
"MIT"
] | Aurochses/Aurochses.Testing.Mvc.Localization | src/Aurochses.Xunit.AspNetCore.Mvc.Localization/ModelLocalizationAssert.cs | 2,670 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace JustDecompile.External.JustAssembly
{
public enum PropertyMethodType : byte
{
GetMethod = 0,
SetMethod
}
}
| 16.071429 | 46 | 0.724444 | [
"ECL-2.0",
"Apache-2.0"
] | Bebere/JustDecompileEngine | JustDecompile.External.JustAssembly/PropertyMethodType.cs | 227 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Serilog;
namespace SerilogConsoleApp.GettingStarted
{
/// <summary>
/// https://github.com/serilog/serilog/wiki/Getting-Started#example-application
/// file:///C:/temp/logs/myapp20180630.txt
/// </summary>
class ExampleApplication
{
public static void Run()
{
// An optional static entry point for logging that can be easily referenced
// by different parts of an application. To configure the <see cref="T:Serilog.Log" />
// set the Logger static property to a logger instance.
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.File("C:\\temp\\logs\\myapp.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
Log.Information("Hello, world!");
int a = 10, b = 0;
try
{
Log.Debug("Dividing {A} by {B}", a, b);
Console.WriteLine(a / b);
}
catch (Exception ex)
{
Log.Error(ex, "Something went wrong");
}
Log.CloseAndFlush();
}
}
}
| 31.02439 | 98 | 0.544811 | [
"Apache-2.0"
] | reyou/Ggg.Csharp | apps/apps-web/app-serilog/app/SerilogConsoleApp/GettingStarted/ExampleApplication.cs | 1,274 | C# |
// ***********************************************************************
// Assembly : MPT.CSI.OOAPI
// Author : Mark Thomas
// Created : 12-13-2018
//
// Last Modified By : Mark Thomas
// Last Modified On : 12-13-2018
// ***********************************************************************
// <copyright file="SectionResultantProperties.cs" company="">
// Copyright © 2018
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
namespace MPT.CSI.OOAPI.Core.Helpers.Definitions.Sections.FrameSections
{
/// <summary>
/// Class SectionResultantProperties.
/// </summary>
public class SectionResultantProperties : ApiProperty
{
/// <summary>
/// The section overall depth. [L].
/// </summary>
/// <value>The t3.</value>
public virtual double t3 { get; set; }
/// <summary>
/// The section overall width. [L].
/// </summary>
/// <value>The t2.</value>
public virtual double t2 { get; set; }
/// <summary>
/// The gross cross-sectional area. [L^2].
/// </summary>
/// <value>The ag.</value>
public double Ag { get; set; }
/// <summary>
/// The shear area for forces in the section local 2-axis direction. [L^2].
/// </summary>
/// <value>The as2.</value>
public double As2 { get; set; }
/// <summary>
/// The shear area for forces in the section local 3-axis direction. [L^2].
/// </summary>
/// <value>The as3.</value>
public double As3 { get; set; }
/// <summary>
/// The torsional constant. [L^4].
/// </summary>
/// <value>The j.</value>
public double J { get; set; }
/// <summary>
/// The moment of inertia for bending about the local 2 axis. [L^4].
/// </summary>
/// <value>The i22.</value>
public double I22 { get; set; }
/// <summary>
/// The moment of inertia for bending about the local 3 axis. [L^4].
/// </summary>
/// <value>The i33.</value>
public double I33 { get; set; }
/// <summary>
/// The section modulus for bending about the local 2 axis. [L^3].
/// </summary>
/// <value>The S22.</value>
public double S22 { get; set; }
/// <summary>
/// The section modulus for bending about the local 3 axis. [L^3].
/// </summary>
/// <value>The S33.</value>
public double S33 { get; set; }
/// <summary>
/// The plastic modulus for bending about the local 2 axis. [L^3].
/// </summary>
/// <value>The Z22.</value>
public double Z22 { get; set; }
/// <summary>
/// The plastic modulus for bending about the local 3 axis. [L^3].
/// </summary>
/// <value>The Z33.</value>
public double Z33 { get; set; }
/// <summary>
/// The radius of gyration about the local 2 axis. [L].
/// </summary>
/// <value>The R22.</value>
public double r22 { get; set; }
/// <summary>
/// The radius of gyration about the local 3 axis. [L].
/// </summary>
/// <value>The R33.</value>
public double r33 { get; set; }
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>A new object that is a copy of this instance.</returns>
public override object Clone()
{
return this.Copy();
}
}
}
| 31.347458 | 83 | 0.480941 | [
"MIT"
] | MarkPThomas/MPT.Net | MPT/CSI/API/MPT.CSI.OOAPI/Core/Helpers/Definitions/Sections/FrameSections/SectionResultantProperties.cs | 3,702 | C# |
// ******************************************************************
// Copyright � 2015-2018 nventive inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ******************************************************************
using System;
using System.Collections.Immutable;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
namespace Uno.Threading
{
/// <summary>
/// This is a lightweight alternative to TaskCompletionSource.
/// </summary>
/// <remarks>
/// In most situation, the TaskCompletionSource could be replaced directly by this one.
/// It is sligthly more efficient to use the .Task insead of directly awaiting this object.
/// </remarks>
public class FastTaskCompletionSource<T> : INotifyCompletion
{
private int _terminationType; // 0-nom completed, 1-result, 2-exception, 3-canceled
public enum TerminationType
{
Running = 0,
Result = 1,
Exception = 2,
Canceled = 3
}
private volatile bool _terminationSet;
private ImmutableList<Action>? _continuations;
/// <summary>
/// Current state of the object
/// </summary>
public TerminationType Termination => (TerminationType) _terminationType;
/// <summary>
/// If any termination has been set
/// </summary>
public bool IsCompleted => _terminationType != (int)TerminationType.Running;
/// <summary>
/// If SetCanceled has been called.
/// </summary>
/// <remarks>
/// Calling SetException with a "TaskCanceledException" will produce the same result.
/// </remarks>
public bool IsCanceled => _terminationType == (int)TerminationType.Canceled;
/// <summary>
/// The capture of the original exception, if any.
/// </summary>
/// <remarks>
/// Will be null until a SetException() has been called.
/// NOTE: will be null if SetException is called with a "TaskCanceledException".
/// </remarks>
public ExceptionDispatchInfo? ExceptionInfo { get; private set; }
/// <summary>
/// The result, if any.
/// </summary>
/// <remarks>
/// Will be null until a SetResult() has been called.
/// </remarks>
public T? Result { get; private set; }
/// <summary>
/// Get the captured exception (if any) - null if none or N/A
/// </summary>
/// <remarks>
/// Will be null until a SetException() has been called.
/// NOTE: will be null if SetException is called with a "TaskCanceledException".
/// </remarks>
public Exception? Exception => ExceptionInfo?.SourceException;
private static SpinWait _spin = new SpinWait();
/// <summary>
/// Set the termination as "Canceled"
/// </summary>
/// <remarks>
/// Will throw an InvalidOperationException if a termination has been set.
/// Calling SetException with a "TaskCanceledException" will produce the same result.
/// </remarks>
public void SetCanceled()
{
if (!TrySetCanceled())
{
throw new InvalidOperationException("Already completed.");
}
}
/// <summary>
/// Set the termination as "Canceled"
/// </summary>
/// <remarks>
/// Calling SetException with a "TaskCanceledException" will produce the same result.
/// </remarks>
public bool TrySetCanceled()
{
if (Interlocked.CompareExchange(ref _terminationType, (int)TerminationType.Canceled, (int)TerminationType.Running) != (int)TerminationType.Running)
{
return false;
}
RaiseOnCompleted();
return true;
}
/// <summary>
/// Set the termination on an exception
/// </summary>
/// <remarks>
/// Will throw an InvalidOperationException if a termination has been set.
/// Calling SetException with a "TaskCanceledException" will result as a if SetCanceled() has been called.
/// </remarks>
public void SetException(Exception exception)
{
if (!TrySetException(exception))
{
throw new InvalidOperationException("Already completed.");
}
}
/// <summary>
/// Set the termination on an exception wrapped in an ExceptionDispatchInfo
/// </summary>
/// <remarks>
/// Will throw an InvalidOperationException if a termination has been set.
/// Calling SetException with a "TaskCanceledException" will result as a if SetCanceled() has been called.
/// </remarks>
public void SetException(ExceptionDispatchInfo exceptionInfo)
{
if (!TrySetException(exceptionInfo))
{
throw new InvalidOperationException("Already completed.");
}
}
/// <summary>
/// Set the termination on an exception
/// </summary>
/// <remarks>
/// Calling SetException with a "TaskCanceledException" will result as a if SetCanceled() has been called.
/// </remarks>
public bool TrySetException(Exception exception)
{
if (exception == null)
{
throw new ArgumentNullException(nameof(exception));
}
if (exception is TaskCanceledException)
{
return TrySetCanceled();
}
if (Interlocked.CompareExchange(ref _terminationType, (int)TerminationType.Exception, (int)TerminationType.Running) != (int)TerminationType.Running)
{
return false;
}
ExceptionInfo = ExceptionDispatchInfo.Capture(exception);
_terminationSet = true;
RaiseOnCompleted();
return true;
}
/// <summary>
/// Set the termination on an exception wrapped in an ExceptionDispatchInfo
/// </summary>
/// <remarks>
/// Calling SetException with a "TaskCanceledException" will result as a if SetCanceled() has been called.
/// </remarks>
public bool TrySetException(ExceptionDispatchInfo exceptionInfo)
{
if (exceptionInfo == null)
{
throw new ArgumentNullException(nameof(exceptionInfo));
}
if (exceptionInfo.SourceException is TaskCanceledException)
{
return TrySetCanceled();
}
if (exceptionInfo.SourceException is OperationCanceledException)
{
return TrySetCanceled();
}
if (Interlocked.CompareExchange(ref _terminationType, (int)TerminationType.Exception, (int)TerminationType.Running) != (int)TerminationType.Running)
{
return false;
}
ExceptionInfo = exceptionInfo;
_terminationSet = true;
RaiseOnCompleted();
return true;
}
/// <summary>
/// Set the termination on a result
/// </summary>
/// <remarks>
/// Will throw an InvalidOperationException if a termination has been set.
/// </remarks>
public void SetResult(T result)
{
if (!TrySetResult(result))
{
throw new InvalidOperationException("Already completed.");
}
}
/// <summary>
/// Set the termination on a result
/// </summary>
public bool TrySetResult(T result)
{
if (Interlocked.CompareExchange(ref _terminationType, (int)TerminationType.Result, (int)TerminationType.Running) != (int)TerminationType.Running)
{
return false;
}
Result = result;
_terminationSet = true;
RaiseOnCompleted();
return true;
}
private void RaiseOnCompleted()
{
var continuations = Interlocked.Exchange(ref _continuations, null);
if (continuations == null)
{
return; // nothing to do
}
foreach (var continuation in continuations)
{
continuation?.Invoke();
}
}
/// <summary>
/// GetResult or throw an exception, according to termination. BLOCKING: DON'T CALL THIS!
/// </summary>
/// <remarks>
/// BLOCKING CALL! Will wait until a termination has been set.
/// The method is resigned for the "await" pattern, should not be called from code.
/// </remarks>
public T? GetResult()
{
switch (Termination)
{
case TerminationType.Result:
SpinUntilTermination();
return Result;
case TerminationType.Exception:
SpinUntilTermination();
ExceptionInfo?.Throw();
return default(T); // will never reach here
case TerminationType.Canceled:
throw new OperationCanceledException();
case TerminationType.Running:
default:
throw new InvalidOperationException("Still in progress.");
}
}
/// <summary>
/// "await" pattern implementation.
/// </summary>
public FastTaskCompletionSource<T> GetAwaiter()
{
return this;
}
/// <summary>
/// "await" pattern implementation.
/// </summary>
public void OnCompleted(Action continuation)
{
Transactional.Update(
ref _continuations,
continuation,
(previous, c) => previous == null ? ImmutableList<Action>.Empty.Add(c) : previous.Add(c));
if (Termination != TerminationType.Running)
{
RaiseOnCompleted();
}
}
private Task<T?>? _task;
/// <summary>
/// Task you can use to await for the result.
/// </summary>
public Task<T?> Task
{
get
{
if (_task != null)
{
return _task;
}
if (_terminationType == 1) // Completed with a result ?
{
// Creat an already-completed task (will result in sync behavior for await code)
Interlocked.CompareExchange(ref _task, CreateSyncTask(), null);
}
else
{
// There's no way to create a "sync" Task for non-result terminations,
// so we fallback to async mode in this case.
// Create a waiting task for completition
Interlocked.CompareExchange(ref _task, CreateAsyncTask(), null);
}
return _task;
}
}
private Task<T?> CreateSyncTask()
{
SpinUntilTermination();
return System.Threading.Tasks.Task.FromResult(Result);
}
private void SpinUntilTermination()
{
while (!_terminationSet)
{
_spin.SpinOnce();
}
}
private async Task<T?> CreateAsyncTask()
{
return await this;
}
}
} | 26.9729 | 151 | 0.671858 | [
"Apache-2.0"
] | nventive/Uno.Core | src/Uno.Core.Extensions.Threading/FastTaskCompletionSource.cs | 9,955 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.V20200801.Inputs
{
/// <summary>
/// Describes the connection monitor endpoint filter.
/// </summary>
public sealed class ConnectionMonitorEndpointFilterArgs : Pulumi.ResourceArgs
{
[Input("items")]
private InputList<Inputs.ConnectionMonitorEndpointFilterItemArgs>? _items;
/// <summary>
/// List of items in the filter.
/// </summary>
public InputList<Inputs.ConnectionMonitorEndpointFilterItemArgs> Items
{
get => _items ?? (_items = new InputList<Inputs.ConnectionMonitorEndpointFilterItemArgs>());
set => _items = value;
}
/// <summary>
/// The behavior of the endpoint filter. Currently only 'Include' is supported.
/// </summary>
[Input("type")]
public InputUnion<string, Pulumi.AzureNative.Network.V20200801.ConnectionMonitorEndpointFilterType>? Type { get; set; }
public ConnectionMonitorEndpointFilterArgs()
{
}
}
}
| 32.707317 | 127 | 0.662938 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Network/V20200801/Inputs/ConnectionMonitorEndpointFilterArgs.cs | 1,341 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace FlowerShopWinApp.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.548387 | 151 | 0.583567 | [
"MIT"
] | BIEMAX/FlowerShopManager | FlowerShopWinApp/Properties/Settings.Designer.cs | 1,073 | C# |
/*
*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Data;
using System.Runtime.Serialization;
using Fido_Main.Fido_Support.ErrorHandling;
using Newtonsoft.Json;
namespace Fido_Main.Fido_Support.Objects.ThreatGRID
{
[DataContract]
internal class Object_ThreatGRID_IP_ConfigClass
{
[DataContract]
public class ThreatGRID_IP_HLInfo
{
[DataMember]
[JsonProperty("data")]
internal ThreatGRID_IP_HLDetail Data_Array { get; set; }
[DataMember]
[JsonProperty("id")]
internal string Id { get; set; }
[DataMember]
[JsonProperty("api_version")]
internal string API_Version { get; set; }
}
[DataContract]
internal class ThreatGRID_IP_HLDetail
{
[DataMember]
[JsonProperty("ip")]
internal string IP { get; set; }
[DataMember]
[JsonProperty("asn")]
internal ThreatGRID_IP_ASNDetail ASN_Array { get; set; }
[DataMember]
[JsonProperty("location")]
internal ThreatGRID_IP_Location Location_Array { get; set; }
[DataMember]
[JsonProperty("rev")]
internal string RevDomain { get; set; }
[DataMember]
[JsonProperty("flags")]
internal ThreatGRID_Flag[] Flags { get; set; }
[DataMember]
[JsonProperty("tags")]
internal ThreatGRID_Tags[] Tags { get; set; }
}
[DataContract]
internal class ThreatGRID_IP_ASNDetail
{
[DataMember]
[JsonProperty("org")]
internal string Org { get; set; }
[DataMember]
[JsonProperty("asn")]
internal string ASN { get; set; }
}
[DataContract]
internal class ThreatGRID_IP_Location
{
[DataMember]
[JsonProperty("city")]
internal string City { get; set; }
[DataMember]
[JsonProperty("region")]
internal string Region { get; set; }
[DataMember]
[JsonProperty("country")]
internal string Country { get; set; }
}
[DataContract]
internal class ThreatGRID_Flag
{
[DataMember]
[JsonProperty("flag")]
internal string Flag { get; set; }
[DataMember]
[JsonProperty("reason")]
internal string Reason { get; set; }
[DataMember]
[JsonProperty("mine")]
internal bool isMine { get; set; }
}
[DataContract]
internal class ThreatGRID_Tags
{
[DataMember]
[JsonProperty("tag")]
internal string Flag { get; set; }
[DataMember]
[JsonProperty("count")]
internal string Reason { get; set; }
[DataMember]
[JsonProperty("mine")]
internal bool isMine { get; set; }
}
[DataContract]
internal class ParseConfigs
{
[DataMember]
internal Int16 PrimeKey { get; set; }
[DataMember]
internal string ApiCall { get; set; }
[DataMember]
internal string ApiBaseUrl { get; set; }
[DataMember]
internal string ApiFuncCall { get; set; }
[DataMember]
internal string ApiQueryString { get; set; }
[DataMember]
internal string ApiKey { get; set; }
}
internal static ParseConfigs FormatParse(DataTable dbReturn)
{
try
{
var reformat = new ParseConfigs
{
PrimeKey = Convert.ToInt16(dbReturn.Rows[0].ItemArray[0]),
ApiCall = Convert.ToString(dbReturn.Rows[0].ItemArray[1]),
ApiBaseUrl = Convert.ToString(dbReturn.Rows[0].ItemArray[2]),
ApiFuncCall = Convert.ToString(dbReturn.Rows[0].ItemArray[3]),
ApiQueryString = Convert.ToString(dbReturn.Rows[0].ItemArray[4]),
ApiKey = Convert.ToString(dbReturn.Rows[0].ItemArray[5])
};
return reformat;
}
catch (Exception e)
{
Fido_EventHandler.SendEmail("Fido Error", "Fido Failed: {0} Unable to format datatable return." + e);
}
return null;
}
}
} | 25.568182 | 109 | 0.620222 | [
"Apache-2.0"
] | robfry/crucyble-csharp-micro-detectors | FIDO-Detector/FIDO-Detector/Fido_Support/Objects/ThreatGRID/Object_ThreatGRID_IP_ConfigClass.cs | 4,500 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Server23.Pages
{
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class ErrorModel : PageModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}
| 25.541667 | 88 | 0.699837 | [
"MIT"
] | NicoHeupt/PANDA | Panda/Server23/Pages/Error.cshtml.cs | 613 | C# |
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Newtonsoft.Json;
namespace QuotationCryptocurrency
{
public static class TempDataExtensions
{
public static void Set<T>(this ITempDataDictionary tempData, string key, T value) where T : class
{
tempData[key] = JsonConvert.SerializeObject(value);
}
public static T Get<T>(this ITempDataDictionary tempData, string key) where T : class
{
tempData.TryGetValue(key, out object obj);
if(obj == null)
{
return null;
}
T result = JsonConvert.DeserializeObject<T>((string)obj);
return result;
}
public static T Peek<T>(this ITempDataDictionary tempData, string key) where T : class
{
T value = Get<T>(tempData, key);
Set<T>(tempData, key, value);
return value;
}
}
}
| 28.333333 | 105 | 0.580749 | [
"MIT"
] | CosmosBeautiful/QuotationCryptocurrency | QuotationCryptocurrency/QuotationCryptocurrency.Web/Extensions/TempDataExtensions.cs | 937 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
#if CODE_STYLE
using WorkspacesResources = Microsoft.CodeAnalysis.CodeStyleResources;
#endif
namespace Microsoft.CodeAnalysis.Options
{
public readonly struct OptionKey : IEquatable<OptionKey>
{
public IOption Option { get; }
public string Language { get; }
public OptionKey(IOption option, string language = null)
{
if (language != null && !option.IsPerLanguage)
{
throw new ArgumentException(WorkspacesResources.A_language_name_cannot_be_specified_for_this_option);
}
else if (language == null && option.IsPerLanguage)
{
throw new ArgumentNullException(WorkspacesResources.A_language_name_must_be_specified_for_this_option);
}
this.Option = option ?? throw new ArgumentNullException(nameof(option));
this.Language = language;
}
public override bool Equals(object obj)
{
return obj is OptionKey key &&
Equals(key);
}
public bool Equals(OptionKey other)
{
return Option == other.Option && Language == other.Language;
}
public override int GetHashCode()
{
var hash = Option?.GetHashCode() ?? 0;
if (Language != null)
{
hash = unchecked((hash * (int)0xA5555529) + Language.GetHashCode());
}
return hash;
}
public override string ToString()
{
if (Option is null)
{
return "";
}
var languageDisplay = Option.IsPerLanguage
? $"({Language}) "
: string.Empty;
return languageDisplay + Option.ToString();
}
public static bool operator ==(OptionKey left, OptionKey right)
{
return left.Equals(right);
}
public static bool operator !=(OptionKey left, OptionKey right)
{
return !left.Equals(right);
}
}
}
| 28.419753 | 119 | 0.56907 | [
"Apache-2.0"
] | Sliptory/roslyn | src/Workspaces/Core/Portable/Options/OptionKey.cs | 2,304 | C# |
using System;
namespace Estudos.MinhaApi.Api.Areas.HelpPage.ModelDescriptions
{
public class ParameterAnnotation
{
public Attribute AnnotationAttribute { get; set; }
public string Documentation { get; set; }
}
} | 21.909091 | 63 | 0.701245 | [
"MIT"
] | ariele-fatima/API_REST_com_ASP_dotNET | Estudos.MinhaApi/Estudos.MinhaApi.Api/Areas/HelpPage/ModelDescriptions/ParameterAnnotation.cs | 241 | C# |
using System;
using Microsoft.Extensions.Logging;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace $ext_safeprojectname$
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
public sealed partial class App : Application
{
private Window _window;
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
InitializeLogging();
this.InitializeComponent();
#if HAS_UNO || NETFX_CORE
this.Suspending += OnSuspending;
#endif
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="args">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
// this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
#if NET6_0_OR_GREATER && WINDOWS
_window = new Window();
_window.Activate();
#else
_window = Windows.UI.Xaml.Window.Current;
#endif
var rootFrame = _window.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
// TODO: Load state from previously suspended application
}
// Place the frame in the current Window
_window.Content = rootFrame;
}
#if !(NET6_0_OR_GREATER && WINDOWS)
if (args.PrelaunchActivated == false)
#endif
{
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), args.Arguments);
}
// Ensure the current window is active
_window.Activate();
}
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new InvalidOperationException($"Failed to load {e.SourcePageType.FullName}: {e.Exception}");
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
/// <summary>
/// Configures global Uno Platform logging
/// </summary>
private static void InitializeLogging()
{
var factory = LoggerFactory.Create(builder =>
{
#if __WASM__
builder.AddProvider(new global::Uno.Extensions.Logging.WebAssembly.WebAssemblyConsoleLoggerProvider());
#elif __IOS__
builder.AddProvider(new global::Uno.Extensions.Logging.OSLogLoggerProvider());
#elif NETFX_CORE
builder.AddDebug();
#else
builder.AddConsole();
#endif
// Exclude logs below this level
builder.SetMinimumLevel(LogLevel.Information);
// Default filters for Uno Platform namespaces
builder.AddFilter("Uno", LogLevel.Warning);
builder.AddFilter("Windows", LogLevel.Warning);
builder.AddFilter("Microsoft", LogLevel.Warning);
// Generic Xaml events
// builder.AddFilter("Windows.UI.Xaml", LogLevel.Debug );
// builder.AddFilter("Windows.UI.Xaml.VisualStateGroup", LogLevel.Debug );
// builder.AddFilter("Windows.UI.Xaml.StateTriggerBase", LogLevel.Debug );
// builder.AddFilter("Windows.UI.Xaml.UIElement", LogLevel.Debug );
// builder.AddFilter("Windows.UI.Xaml.FrameworkElement", LogLevel.Trace );
// Layouter specific messages
// builder.AddFilter("Windows.UI.Xaml.Controls", LogLevel.Debug );
// builder.AddFilter("Windows.UI.Xaml.Controls.Layouter", LogLevel.Debug );
// builder.AddFilter("Windows.UI.Xaml.Controls.Panel", LogLevel.Debug );
// builder.AddFilter("Windows.Storage", LogLevel.Debug );
// Binding related messages
// builder.AddFilter("Windows.UI.Xaml.Data", LogLevel.Debug );
// builder.AddFilter("Windows.UI.Xaml.Data", LogLevel.Debug );
// Binder memory references tracking
// builder.AddFilter("Uno.UI.DataBinding.BinderReferenceHolder", LogLevel.Debug );
// RemoteControl and HotReload related
// builder.AddFilter("Uno.UI.RemoteControl", LogLevel.Information);
// Debug JS interop
// builder.AddFilter("Uno.Foundation.WebAssemblyRuntime", LogLevel.Debug );
});
global::Uno.Extensions.LogExtensionPoint.AmbientLoggerFactory = factory;
}
}
}
| 39.111111 | 119 | 0.598684 | [
"Apache-2.0"
] | ArchieCoder/uno | src/SolutionTemplate/UnoSolutionTemplate.net6/Shared/App.xaml.cs | 6,690 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Class03.Models.Models;
namespace Class03.Models.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
| 23.204545 | 112 | 0.592556 | [
"MIT"
] | sedc-codecademy/skwd8-08-aspnetmvc | g2/Class03/Class03.DemoApp/Class03.Models/Controllers/HomeController.cs | 1,023 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using FlubuCore.Context;
using FlubuCore.Tasks;
using FlubuCore.Tasks.Process;
namespace FlubuCore.Azure.Tasks.Batch
{
public partial class AzureBatchFileTask : ExternalProcessTaskBase<AzureBatchFileTask>
{
/// <summary>
/// Manage Batch input files.
/// </summary>
public AzureBatchFileTask()
{
WithArguments("az batch file");
}
protected override string Description { get; set; }
}
}
| 21.423077 | 90 | 0.635548 | [
"MIT"
] | flubu-core/FlubuCore.Azure | FlubuCore.Azure/Tasks/Batch/AzureBatchFileTask.cs | 557 | C# |
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using FluentAssertions;
using NUnit.Framework;
using SAGESharp.Animations;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace SAGESharp.Tests.Animations
{
class BKDTests
{
private static readonly FieldInfo LENGTH_FIELD = typeof(BKD)
.GetField("length", BindingFlags.NonPublic | BindingFlags.Instance);
[Test]
public void Test_Getting_The_Length_Of_A_BKD_Object()
{
BKD bkd = new BKD();
LENGTH_FIELD.SetValue(bkd, (ushort)3647);
bkd.Length.Should().Be(60.7833366f);
}
[Test]
public void Test_Setting_The_Length_Of_A_BKD_Object()
{
BKD bkd = new BKD
{
Length = 60.7833366f
};
LENGTH_FIELD.GetValue(bkd).Should().Be(3647);
}
[Test]
public void Test_Setting_A_Null_Entry_List_To_A_BKD_Object()
{
BKD bkd = new BKD();
Action action = () => bkd.Entries = null;
action.Should().ThrowArgumentNullException("value");
}
[TestCaseSource(nameof(EqualObjectsTestCases))]
public void Test_Comparing_Equal_Objects(IComparisionTestCase<BKD> testCase) => testCase.Execute();
public static IComparisionTestCase<BKD>[] EqualObjectsTestCases() => new IComparisionTestCase<BKD>[]
{
ComparisionTestCase.CompareObjectAgainstItself(SampleBKD()),
ComparisionTestCase.CompareTwoEqualObjects(SampleBKD),
ComparisionTestCase.CompareNullWithOperators<BKD>()
};
[TestCaseSource(nameof(NotEqualObjectsTestCases))]
public void Test_Comparing_NotEqual_Objects(IComparisionTestCase<BKD> testCase) => testCase.Execute();
public static IComparisionTestCase<BKD>[] NotEqualObjectsTestCases() => new IComparisionTestCase<BKD>[]
{
ComparisionTestCase.CompareTwoNotEqualObjects(
supplier: SampleBKD,
updater: bkd => bkd.Length *= 4
),
ComparisionTestCase.CompareTwoNotEqualObjects(
supplier: SampleBKD,
updater: bkd => bkd.Entries.Add(new BKDEntry())
),
ComparisionTestCase.CompareNotNullObjectAgainstNull(SampleBKD())
};
public static BKD SampleBKD() => new BKD
{
Length = 1.5f,
Entries = new List<BKDEntry>
{
BKDEntryTests.SampleBKDEntry()
}
};
}
}
| 32.069767 | 111 | 0.616389 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | TheLegendOfMataNui/SAGESharp | SAGESharp.Tests/Animations/BKDTests.cs | 2,760 | C# |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Messages.Messages
File: TimeInForce.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Messages
{
using System;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using StockSharp.Localization;
/// <summary>
/// Limit order time in force.
/// </summary>
[DataContract]
[Serializable]
public enum TimeInForce
{
/// <summary>
/// Good til cancelled.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.GTCKey, Description = LocalizedStrings.GoodTilCancelledKey)]
PutInQueue,
/// <summary>
/// Fill Or Kill.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.FOKKey, Description = LocalizedStrings.FillOrKillKey)]
MatchOrCancel,
/// <summary>
/// Immediate Or Cancel.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.IOCKey, Description = LocalizedStrings.ImmediateOrCancelKey)]
CancelBalance,
}
} | 31.346154 | 137 | 0.665644 | [
"Apache-2.0"
] | Ahrvo-Trading-Systems/StockSharp | Messages/TimeInForce.cs | 1,630 | C# |
using System;
using Microsoft.Practices.TransientFaultHandling;
namespace MadsKristensen.EditorExtensions
{
public class FileTransientErrorDetectionStrategy : ITransientErrorDetectionStrategy
{
public bool IsTransient(Exception ex)
{
return true;
}
}
}
| 21.642857 | 87 | 0.709571 | [
"Apache-2.0"
] | DotNetSparky/WebEssentials2013 | EditorExtensions/Shared/Helpers/Policies/Strategies/FileTransientErrorDetectionStrategy.cs | 305 | C# |
using System;
using System.Net;
using EventStore.ClientAPI;
using EventStore.Core.Services;
using EventStore.Core.Tests.Http.Users;
using NUnit.Framework;
using Newtonsoft.Json.Linq;
namespace EventStore.Core.Tests.Http.StreamSecurity {
namespace stream_access {
[TestFixture, Category("LongRunning")]
class when_creating_a_secured_stream_by_posting_metadata : SpecificationWithUsers {
private HttpWebResponse _response;
protected override void When() {
var metadata =
(StreamMetadata)
StreamMetadata.Build()
.SetMetadataReadRole("admin")
.SetMetadataWriteRole("admin")
.SetReadRole("")
.SetWriteRole("other");
var jsonMetadata = metadata.AsJsonString();
_response = MakeArrayEventsPost(
TestMetadataStream,
new[] {
new {
EventId = Guid.NewGuid(),
EventType = SystemEventTypes.StreamMetadata,
Data = new JRaw(jsonMetadata)
}
});
}
[Test]
public void returns_ok_status_code() {
Assert.AreEqual(HttpStatusCode.Created, _response.StatusCode);
}
[Test]
public void refuses_to_post_event_as_anonymous() {
var response = PostEvent(new {Some = "Data"});
Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Test]
public void accepts_post_event_as_authorized_user() {
var response = PostEvent(new {Some = "Data"}, GetCorrectCredentialsFor("user1"));
Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
}
[Test]
public void accepts_post_event_as_authorized_user_by_trusted_auth() {
var uri = MakeUrl(TestStream);
var request2 = WebRequest.Create(uri);
var httpWebRequest = (HttpWebRequest)request2;
httpWebRequest.ConnectionGroupName = TestStream;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/vnd.eventstore.events+json";
httpWebRequest.UseDefaultCredentials = false;
httpWebRequest.Headers.Add("ES-TrustedAuth", "root; admin, other");
httpWebRequest.GetRequestStream()
.WriteJson(
new[] {
new {
EventId = Guid.NewGuid(),
EventType = "event-type",
Data = new {Some = "Data"}
}
});
var request = httpWebRequest;
var httpWebResponse = GetRequestResponse(request);
var response = httpWebResponse;
Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
}
}
}
}
| 30.278481 | 85 | 0.701923 | [
"Apache-2.0",
"CC0-1.0"
] | MadKat13/EventStore | src/EventStore.Core.Tests/Http/StreamSecurity/stream_access.cs | 2,394 | C# |
using Sdl.Web.Common.Models;
using System;
using System.ComponentModel.DataAnnotations;
using Sdl.Web.Common;
namespace Sdl.Web.Modules.AudienceManager.Models
{
/// <summary>
/// LoginForm entity
/// </summary>
[Serializable]
[DxaNoOutputCache]
public class LoginForm : EntityModel
{
/// <summary>
/// Holds the form control value for username
/// </summary>
[Required(ErrorMessage = "@Model.NoUserNameMessage")]
[SemanticProperty(IgnoreMapping=true)]
public string UserName { get; set; }
/// <summary>
/// Holds the form control value for password
/// </summary>
[Required(ErrorMessage = "@Model.NoPasswordMessage")]
[SemanticProperty(IgnoreMapping = true)]
public string Password { get; set; }
/// <summary>
/// Holds the form control value for remember me
/// </summary>
[SemanticProperty(IgnoreMapping = true)]
public bool RememberMe { get; set; }
/// <summary>
/// Form heading text
/// </summary>
public string Heading { get; set; }
/// <summary>
/// Label text for username input control on view
/// </summary>
public string UserNameLabel { get; set; }
/// <summary>
/// Label text for password input control on view
/// </summary>
public string PasswordLabel { get; set; }
/// <summary>
/// Label text for remember me check box on view
/// </summary>
public string RememberMeLabel { get; set; }
/// <summary>
/// Label text for submit botton on view
/// </summary>
public string SubmitButtonLabel { get; set; }
/// <summary>
/// User name not specified message
/// </summary>
public string NoUserNameMessage { get; set; }
/// <summary>
/// Password not specified message
/// </summary>
public string NoPasswordMessage { get; set; }
/// <summary>
/// Authentication error message
/// </summary>
public string AuthenticationErrorMessage { get; set; }
}
} | 29.28 | 62 | 0.569217 | [
"Apache-2.0"
] | RWS/dxa-modules | webapp-net/AudienceManager/Models/LoginForm.cs | 2,198 | C# |
using CompletelyOptional;
using UnityEngine;
namespace OptionalUI
{
/// <summary>
/// Configuable Settings. Every configuable value is tied to <see cref="UIconfig"/> and <see cref="key"/>.
/// <para>Saving and loading will be handled automatically when this is added to the <see cref="OpTab"/>.</para>
/// </summary>
/// <remarks>Adding '_' before key (or leaving it empty) makes this <see cref="cosmetic"/>, preventing it to be saved.</remarks>
public abstract class UIconfig : UIelement
{
/// <summary>
/// Rectangular <see cref="UIconfig"/>.
/// </summary>
/// <param name="pos">BottomLeft Position</param>
/// <param name="size">Size</param>
/// <param name="key">Key: this must be unique</param>
/// <param name="defaultValue">Default Value</param>
public UIconfig(Vector2 pos, Vector2 size, string key, string defaultValue = "") : base(pos, size)
{
if (string.IsNullOrEmpty(key)) { this.cosmetic = true; this.key = "_"; }
else if (key.Substring(0, 1) == "_") { this.cosmetic = true; this.key = key; }
else { this.cosmetic = false; this.key = key; }
this._value = defaultValue;
this.defaultValue = this._value;
this.greyedOut = false;
this._held = false;
this.bumpBehav = new BumpBehaviour(this);
}
/// <summary>
/// Circular <see cref="UIconfig"/>.
/// </summary>
/// <param name="pos">BottomLeft Position (NOT center!)</param>
/// <param name="rad">Radius</param>
/// <param name="key">Key: this must be unique</param>
/// <param name="defaultValue">Default Value</param>
public UIconfig(Vector2 pos, float rad, string key, string defaultValue = "") : base(pos, rad)
{
if (string.IsNullOrEmpty(key)) { this.cosmetic = true; this.key = "_"; }
else if (key.Substring(0, 1) == "_") { this.cosmetic = true; this.key = key; }
else { this.cosmetic = false; this.key = key; }
this._value = defaultValue;
this.defaultValue = this._value;
this.greyedOut = false;
this._held = false;
this.bumpBehav = new BumpBehaviour(this);
}
/// <summary>
/// This is set in ctor.
/// <para>It'll be the default <see cref="value"/> of this <see cref="UIconfig"/> when your mod is installed first/configs are reset.</para>
/// </summary>
public string defaultValue { get; protected internal set; }
public override void Reset()
{
base.Reset();
this.value = this.defaultValue;
this.held = false;
}
/// <summary>
/// Set <see cref="key"/> to empty or start with '_' to make this <see cref="UIconfig"/> cosmetic and prevent saving
/// </summary>
public readonly bool cosmetic;
/// <summary>
/// Mimics <see cref="Menu.ButtonBehavior"/> of vanilla Rain World UIs
/// </summary>
public BumpBehaviour bumpBehav { get; private set; }
/// <summary>
/// Whether this is held or not.
/// If this is true, other <see cref="UIelement"/> will be frozen.
/// </summary>
protected internal bool held
{
get { return _held; }
set
{
if (_held != value)
{
_held = value;
ConfigMenu.freezeMenu = value;
}
}
}
private bool _held;
/// <summary>
/// Unique key for this <see cref="UIconfig"/>
/// </summary>
public readonly string key;
/// <summary>
/// If this is true, this <see cref="UIconfig"/> will be greyed out and can't be interacted.
/// </summary>
public bool greyedOut;
/// <summary>
/// Either this is <see cref="greyedOut"/> or <see cref="UIelement.isHidden"/>.
/// Prevents its interaction in <see cref="Update(float)"/>.
/// </summary>
protected internal bool disabled => greyedOut || isHidden;
/// <summary>
/// If you want to change value directly without running <see cref="OnChange"/>.
/// This is not recommended unless you know what you are doing.
/// </summary>
public void ForceValue(string newValue)
{
this._value = newValue;
}
protected internal string _value;
/// <summary>
/// Value in <see cref="string"/> form, which is how it is saved. Changing this will call <see cref="OnChange"/> automatically.
/// </summary>
public virtual string value
{
get
{
return _value;
}
set
{
if (_value != value)
{
_value = value;
if (_init) { OnChange(); }
}
}
}
/// <summary>
/// Value in <see cref="int"/> form
/// </summary>
public int valueInt
{
get { return int.TryParse(value, out int i) ? i : 0; }
set { this.value = value.ToString(); }
}
/// <summary>
/// Value in <see cref="float"/> form
/// </summary>
public float valueFloat
{
get { return float.TryParse(value, out float d) ? d : 0f; }
set { this.value = value.ToString(); }
}
/// <summary>
/// Value in <see cref="bool"/> form
/// </summary>
public bool valueBool
{
set { this.value = value ? "true" : "false"; }
get
{
if (this.value == "true") { return true; }
else { return false; }
}
}
public override void OnChange()
{
base.OnChange();
if (!_init) { return; }
if (!cosmetic)
{
OptionScript.configChanged = true;
(menu as ConfigMenu).saveButton.menuLabel.text = InternalTranslator.Translate("APPLY");
}
}
/// <summary>
/// Separates Graphical update for code-visiblilty.
/// </summary>
/// <param name="dt">deltaTime</param>
public override void GrafUpdate(float dt)
{
base.GrafUpdate(dt);
}
/// <summary>
/// Update method that happens every frame.
/// </summary>
/// <param name="dt">deltaTime</param>
public override void Update(float dt)
{
if (!_init) { return; }
base.Update(dt);
this.bumpBehav.Update(dt);
if (this.held && this.inScrollBox) { this.scrollBox.MarkDirty(0.5f); this.scrollBox.Update(dt); }
if (showDesc && !this.greyedOut) { ConfigMenu.description = this.description; }
}
protected internal virtual bool CopyFromClipboard(string value)
{
try { this.value = value; this.held = false; return this.value == value; }
catch { return false; }
}
protected internal virtual string CopyToClipboard()
{
this.held = false;
return this.value;
}
public override void Hide()
{
this.held = false;
base.Hide();
}
}
}
| 34 | 148 | 0.511526 | [
"MIT"
] | PJB3005/CompletelyOptional | CompletelyOptional/OptionalUI/UIconfig.cs | 7,548 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Codility01.Helpers.DataStructures
{
public class BTreeNode<TValue>
where TValue : IComparable<TValue>
{
private readonly List<TValue> _duplicates;
private readonly bool _allowsDuplicates;
public TValue Value { get; }
public BTreeNode<TValue> Left { get; set; }
public BTreeNode<TValue> Right { get; set; }
public bool IsBalanced
{
get
{
var bf = BalanceFactor();
return bf >= -1 && bf <= 1;
}
}
public bool HasDuplicates => _duplicates.Count > 0;
public BTreeNode(TValue value, bool allowsDuplicates = false)
{
Value = value;
_allowsDuplicates = allowsDuplicates;
if (_allowsDuplicates)
_duplicates = new List<TValue>();
}
public BTreeNode<TValue> RightmostChild(out BTreeNode<TValue> parent)
{
parent = null;
if (Right == null)
return this;
else
{
var rightmost = Right.RightmostChild(out parent);
if (rightmost == Right)
parent = this;
return rightmost;
}
}
public BTreeNode<TValue> LeftmostChild(out BTreeNode<TValue> parent)
{
parent = null;
if (Left == null)
return this;
else
{
var leftmost = Left.LeftmostChild(out parent);
if (leftmost == Left)
parent = this;
return leftmost;
}
}
public BTreeNode<TValue> FindChild(TValue value, out BTreeNode<TValue> parent)
{
parent = this;
var comparison = Value.CompareTo(value);
switch(comparison)
{
case -1:
return
Left == null ? null
: Left.ValueEquals(value) ? Left
: Left.FindChild(value, out parent);
case 1:
return
Right == null ? null
: Right.ValueEquals(value) ? Right
: Right.FindChild(value, out parent);
default:
return null;
}
}
public BTreeNode<TValue> Add(TValue value)
{
var comparison = Value.CompareTo(value);
if (comparison < 0)
{
if (Left == null)
return Left = new BTreeNode<TValue>(value);
else
return Left.Add(value);
}
else if (comparison == 0)
{
if (!_allowsDuplicates)
throw new Exception("Duplicate encountered");
_duplicates.Add(value);
return this;
}
else //if (comparison > 0)
{
if (Right == null)
return Right = new BTreeNode<TValue>(value);
else
return Right.Add(value);
}
}
public BTreeNode<TValue> Remove(TValue value)
{
var child = FindChild(value, out var parent);
if (child == null)
return null;
else if(parent.Left == child)
{
//get childs rightmost
var rightmost = child.RightmostChild(out var _rightmostParent);
if (rightmost != null)
{
_rightmostParent.Right = null;
parent.Left = rightmost;
}
else parent.Left = child.Left;
}
else //if(parent.Right == child)
{
var leftmost = child.LeftmostChild(out var _leftmostParent);
if (leftmost != null)
{
_leftmostParent.Left = null;
parent.Right = leftmost;
}
else parent.Right = child.Right;
}
return child;
}
/// <summary>
/// left rotation
/// </summary>
/// <param name="child"></param>
public void RotateRightChild(BTreeNode<TValue> parent)
{
if(Right != null)
{
var pivot = Right;
if (parent.Left == this)
parent.Left = pivot;
else
parent.Right = pivot;
Right = pivot.Left;
pivot.Left = this;
}
}
/// <summary>
/// right rotation
/// </summary>
/// <param name="child"></param>
public void RotateLeftChild(BTreeNode<TValue> parent)
{
if (Left != null)
{
var pivot = Left;
if (parent.Left == this)
parent.Left = pivot;
else
parent.Right = pivot;
Left = pivot.Right;
pivot.Right = this;
}
}
public void Balance()
{
var balanceFactor = BalanceFactor();
if (balanceFactor < -2)
Left.Balance();
else if (balanceFactor > 2)
Right.Balance();
}
public bool ValueEquals(TValue value) => Value.CompareTo(value) == 0;
public int Height() => Math.Max(
(Left?.Height() + 1) ?? 0,
(Right?.Height() + 1) ?? 0);
public int BalanceFactor() => (Right?.Height() ?? 0) - (Left?.Height() ?? 0);
}
}
| 19.108108 | 80 | 0.614569 | [
"MIT"
] | d-dantte/Algorithms | Codility01/Helpers/DataStructures/BTreeNode.cs | 4,244 | C# |
using SampleProject.TemplateClasses.CustomElements.PageElements.InnerElements;
using Xamarin.Forms;
namespace SampleProject.TemplateClasses.CustomElements.PageElements
{
public class ImageHeader : ContentView
{
public Grid grid { get; set; }
public InnerElementsImageHeader innerElements {get;set;}
}
} | 30.181818 | 79 | 0.76506 | [
"MIT"
] | Melgaco/XamComp | SampleProject/SampleProject/TemplateClasses/CustomElements/PageElements/ImageHeader.cs | 334 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Mts.Model.V20140618;
using System;
using System.Collections.Generic;
namespace Aliyun.Acs.Mts.Transform.V20140618
{
public class DeleteTemplateResponseUnmarshaller
{
public static DeleteTemplateResponse Unmarshall(UnmarshallerContext context)
{
DeleteTemplateResponse deleteTemplateResponse = new DeleteTemplateResponse();
deleteTemplateResponse.HttpResponse = context.HttpResponse;
deleteTemplateResponse.RequestId = context.StringValue("DeleteTemplate.RequestId");
deleteTemplateResponse.TemplateId = context.StringValue("DeleteTemplate.TemplateId");
return deleteTemplateResponse;
}
}
} | 38.871795 | 88 | 0.761873 | [
"Apache-2.0"
] | brightness007/unofficial-aliyun-openapi-net-sdk | aliyun-net-sdk-mts/Mts/Transform/V20140618/DeleteTemplateResponseUnmarshaller.cs | 1,516 | C# |
using Ryujinx.Graphics.GAL;
using Ryujinx.Graphics.Gpu.State;
namespace Ryujinx.Graphics.Gpu.Engine
{
using Texture = Image.Texture;
partial class Methods
{
/// <summary>
/// Performs a texture to texture copy.
/// </summary>
/// <param name="state">Current GPU state</param>
/// <param name="argument">Method call argument</param>
private void CopyTexture(GpuState state, int argument)
{
var dstCopyTexture = state.Get<CopyTexture>(MethodOffset.CopyDstTexture);
var srcCopyTexture = state.Get<CopyTexture>(MethodOffset.CopySrcTexture);
Texture srcTexture = TextureManager.FindOrCreateTexture(srcCopyTexture);
if (srcTexture == null)
{
return;
}
// When the source texture that was found has a depth format,
// we must enforce the target texture also has a depth format,
// as copies between depth and color formats are not allowed.
if (srcTexture.Format == Format.D32Float)
{
dstCopyTexture.Format = RtFormat.D32Float;
}
Texture dstTexture = TextureManager.FindOrCreateTexture(dstCopyTexture);
if (dstTexture == null)
{
return;
}
var control = state.Get<CopyTextureControl>(MethodOffset.CopyTextureControl);
var region = state.Get<CopyRegion>(MethodOffset.CopyRegion);
int srcX1 = (int)(region.SrcXF >> 32);
int srcY1 = (int)(region.SrcYF >> 32);
int srcX2 = (int)((region.SrcXF + region.SrcWidthRF * region.DstWidth) >> 32);
int srcY2 = (int)((region.SrcYF + region.SrcHeightRF * region.DstHeight) >> 32);
int dstX1 = region.DstX;
int dstY1 = region.DstY;
int dstX2 = region.DstX + region.DstWidth;
int dstY2 = region.DstY + region.DstHeight;
Extents2D srcRegion = new Extents2D(
srcX1 / srcTexture.Info.SamplesInX,
srcY1 / srcTexture.Info.SamplesInY,
srcX2 / srcTexture.Info.SamplesInX,
srcY2 / srcTexture.Info.SamplesInY);
Extents2D dstRegion = new Extents2D(
dstX1 / dstTexture.Info.SamplesInX,
dstY1 / dstTexture.Info.SamplesInY,
dstX2 / dstTexture.Info.SamplesInX,
dstY2 / dstTexture.Info.SamplesInY);
bool linearFilter = control.UnpackLinearFilter();
srcTexture.HostTexture.CopyTo(dstTexture.HostTexture, srcRegion, dstRegion, linearFilter);
// For an out of bounds copy, we must ensure that the copy wraps to the next line,
// so for a copy from a 64x64 texture, in the region [32, 96[, there are 32 pixels that are
// outside the bounds of the texture. We fill the destination with the first 32 pixels
// of the next line on the source texture.
// This can be emulated with 2 copies (the first copy handles the region inside the bounds,
// the second handles the region outside of the bounds).
// We must also extend the source texture by one line to ensure we can wrap on the last line.
// This is required by the (guest) OpenGL driver.
if (srcRegion.X2 > srcTexture.Info.Width)
{
srcCopyTexture.Height++;
srcTexture = TextureManager.FindOrCreateTexture(srcCopyTexture);
srcRegion = new Extents2D(
srcRegion.X1 - srcTexture.Info.Width,
srcRegion.Y1 + 1,
srcRegion.X2 - srcTexture.Info.Width,
srcRegion.Y2 + 1);
srcTexture.HostTexture.CopyTo(dstTexture.HostTexture, srcRegion, dstRegion, linearFilter);
}
dstTexture.SignalModified();
}
}
} | 39.77 | 106 | 0.589389 | [
"MIT"
] | AidanXu/Ryujinx | Ryujinx.Graphics.Gpu/Engine/MethodCopyTexture.cs | 3,977 | 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/tpcshrd.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop.Windows;
/// <include file='PROPERTY_UNITS.xml' path='doc/member[@name="PROPERTY_UNITS"]/*' />
public enum PROPERTY_UNITS
{
/// <include file='PROPERTY_UNITS.xml' path='doc/member[@name="PROPERTY_UNITS.PROPERTY_UNITS_DEFAULT"]/*' />
PROPERTY_UNITS_DEFAULT = 0,
/// <include file='PROPERTY_UNITS.xml' path='doc/member[@name="PROPERTY_UNITS.PROPERTY_UNITS_INCHES"]/*' />
PROPERTY_UNITS_INCHES = 1,
/// <include file='PROPERTY_UNITS.xml' path='doc/member[@name="PROPERTY_UNITS.PROPERTY_UNITS_CENTIMETERS"]/*' />
PROPERTY_UNITS_CENTIMETERS = 2,
/// <include file='PROPERTY_UNITS.xml' path='doc/member[@name="PROPERTY_UNITS.PROPERTY_UNITS_DEGREES"]/*' />
PROPERTY_UNITS_DEGREES = 3,
/// <include file='PROPERTY_UNITS.xml' path='doc/member[@name="PROPERTY_UNITS.PROPERTY_UNITS_RADIANS"]/*' />
PROPERTY_UNITS_RADIANS = 4,
/// <include file='PROPERTY_UNITS.xml' path='doc/member[@name="PROPERTY_UNITS.PROPERTY_UNITS_SECONDS"]/*' />
PROPERTY_UNITS_SECONDS = 5,
/// <include file='PROPERTY_UNITS.xml' path='doc/member[@name="PROPERTY_UNITS.PROPERTY_UNITS_POUNDS"]/*' />
PROPERTY_UNITS_POUNDS = 6,
/// <include file='PROPERTY_UNITS.xml' path='doc/member[@name="PROPERTY_UNITS.PROPERTY_UNITS_GRAMS"]/*' />
PROPERTY_UNITS_GRAMS = 7,
/// <include file='PROPERTY_UNITS.xml' path='doc/member[@name="PROPERTY_UNITS.PROPERTY_UNITS_SILINEAR"]/*' />
PROPERTY_UNITS_SILINEAR = 8,
/// <include file='PROPERTY_UNITS.xml' path='doc/member[@name="PROPERTY_UNITS.PROPERTY_UNITS_SIROTATION"]/*' />
PROPERTY_UNITS_SIROTATION = 9,
/// <include file='PROPERTY_UNITS.xml' path='doc/member[@name="PROPERTY_UNITS.PROPERTY_UNITS_ENGLINEAR"]/*' />
PROPERTY_UNITS_ENGLINEAR = 10,
/// <include file='PROPERTY_UNITS.xml' path='doc/member[@name="PROPERTY_UNITS.PROPERTY_UNITS_ENGROTATION"]/*' />
PROPERTY_UNITS_ENGROTATION = 11,
/// <include file='PROPERTY_UNITS.xml' path='doc/member[@name="PROPERTY_UNITS.PROPERTY_UNITS_SLUGS"]/*' />
PROPERTY_UNITS_SLUGS = 12,
/// <include file='PROPERTY_UNITS.xml' path='doc/member[@name="PROPERTY_UNITS.PROPERTY_UNITS_KELVIN"]/*' />
PROPERTY_UNITS_KELVIN = 13,
/// <include file='PROPERTY_UNITS.xml' path='doc/member[@name="PROPERTY_UNITS.PROPERTY_UNITS_FAHRENHEIT"]/*' />
PROPERTY_UNITS_FAHRENHEIT = 14,
/// <include file='PROPERTY_UNITS.xml' path='doc/member[@name="PROPERTY_UNITS.PROPERTY_UNITS_AMPERE"]/*' />
PROPERTY_UNITS_AMPERE = 15,
/// <include file='PROPERTY_UNITS.xml' path='doc/member[@name="PROPERTY_UNITS.PROPERTY_UNITS_CANDELA"]/*' />
PROPERTY_UNITS_CANDELA = 16,
}
| 47.5 | 145 | 0.721902 | [
"MIT"
] | reflectronic/terrafx.interop.windows | sources/Interop/Windows/Windows/um/tpcshrd/PROPERTY_UNITS.cs | 2,947 | C# |
using System;
using Microsoft.Extensions.Logging;
using MigrationTools.Endpoints;
using MigrationTools.Enrichers;
namespace MigrationTools.Processors
{
/// <summary>
/// The `TfsAreaAndIterationProcessor` migrates all of the Area nd Iteraion paths.
/// </summary>
public class TfsAreaAndIterationProcessor : Processor
{
private TfsAreaAndIterationProcessorOptions _options;
private TfsNodeStructure _nodeStructureEnricher;
public TfsAreaAndIterationProcessor(
TfsNodeStructure tfsNodeStructure,
ProcessorEnricherContainer processorEnrichers,
IEndpointFactory endpointFactory,
IServiceProvider services,
ITelemetryLogger telemetry,
ILogger<Processor> logger)
: base(processorEnrichers, endpointFactory, services, telemetry, logger)
{
_nodeStructureEnricher = tfsNodeStructure;
}
public override void Configure(IProcessorOptions options)
{
base.Configure(options);
Log.LogInformation("TfsAreaAndIterationProcessor::Configure");
_options = (TfsAreaAndIterationProcessorOptions)options;
}
protected override void InternalExecute()
{
Log.LogInformation("Processor::InternalExecute::Start");
EnsureConfigured();
ProcessorEnrichers.ProcessorExecutionBegin(this);
var nodeStructurOptions = new TfsNodeStructureOptions()
{
Enabled = true,
NodeBasePaths = _options.NodeBasePaths,
PrefixProjectToNodes = _options.PrefixProjectToNodes
};
_nodeStructureEnricher.Configure(nodeStructurOptions);
_nodeStructureEnricher.ProcessorExecutionBegin(null);
ProcessorEnrichers.ProcessorExecutionEnd(this);
Log.LogInformation("Processor::InternalExecute::End");
}
private void EnsureConfigured()
{
Log.LogInformation("Processor::EnsureConfigured");
if (_options == null)
{
throw new Exception("You must call Configure() first");
}
if (Source is not TfsWorkItemEndpoint)
{
throw new Exception("The Source endpoint configured must be of type TfsWorkItemEndpoint");
}
if (Target is not TfsWorkItemEndpoint)
{
throw new Exception("The Target endpoint configured must be of type TfsWorkItemEndpoint");
}
}
}
} | 40.956522 | 106 | 0.583156 | [
"MIT"
] | Kota9006/TestMigration | src/MigrationTools.Clients.AzureDevops.ObjectModel/Processors/TfsAreaAndIterationProcessor.cs | 2,828 | C# |
// Copyright (c) Amer Koleci and contributors.
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
using System.Numerics;
using SharpGen.Runtime;
namespace Vortice.DirectX.Direct2D
{
[Shadow(typeof(ID2D1GeometrySinkShadow))]
public partial interface ID2D1GeometrySink
{
/// <summary>
/// Creates a line segment between the current point and the specified end point and adds it to the geometry sink.
/// </summary>
/// <param name="point">The end point of the line to draw.</param>
void AddLine(Vector2 point);
/// <summary>
/// Creates a cubic Bezier curve between the current point and the specified endpoint.
/// </summary>
/// <param name="bezier">A structure that describes the control points and endpoint of the Bezier curve to add. </param>
void AddBezier(BezierSegment bezier);
/// <summary>
/// Creates a quadratic Bezier curve between the current point and the specified endpoint.
/// </summary>
/// <param name="bezier">A structure that describes the control point and the endpoint of the quadratic Bezier curve to add.</param>
/// <unmanaged>void AddQuadraticBezier([In] const D2D1_QUADRATIC_BEZIER_SEGMENT* bezier)</unmanaged>
void AddQuadraticBezier(QuadraticBezierSegment bezier);
/// <summary>
/// Adds a sequence of quadratic Bezier segments as an array in a single call.
/// </summary>
/// <param name="beziers">An array of a sequence of quadratic Bezier segments.</param>
void AddQuadraticBeziers(QuadraticBezierSegment[] beziers);
/// <summary>
/// Adds a single arc to the path geometry.
/// </summary>
/// <param name="arc">The arc segment to add to the figure.</param>
void AddArc(ArcSegment arc);
}
}
| 42.755556 | 140 | 0.655925 | [
"MIT"
] | Aminator/Vortice.Windows | src/Vortice.DirectX.Direct2D/ID2D1GeometrySink.cs | 1,926 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace Azure.Messaging.ServiceBus.Tests
{
public class ReceiverLiveTests : ServiceBusLiveTestBase
{
[Test]
public async Task Peek()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var sender = new QueueSenderClient(TestEnvironment.ServiceBusConnectionString, scope.QueueName);
var messageCt = 10;
IEnumerable<ServiceBusMessage> sentMessages = GetMessages(messageCt);
await sender.SendRangeAsync(sentMessages);
await using var receiver = new QueueReceiverClient(TestEnvironment.ServiceBusConnectionString, scope.QueueName);
Dictionary<string, string> sentMessageIdToLabel = new Dictionary<string, string>();
foreach (ServiceBusMessage message in sentMessages)
{
sentMessageIdToLabel.Add(message.MessageId, Encoding.Default.GetString(message.Body));
}
IAsyncEnumerable<ServiceBusMessage> peekedMessages = receiver.PeekRangeAsync(
maxMessages: messageCt);
var ct = 0;
await foreach (ServiceBusMessage peekedMessage in peekedMessages)
{
var peekedText = Encoding.Default.GetString(peekedMessage.Body);
//var sentText = sentMessageIdToLabel[peekedMessage.MessageId];
//sentMessageIdToLabel.Remove(peekedMessage.MessageId);
//Assert.AreEqual(sentText, peekedText);
TestContext.Progress.WriteLine($"{peekedMessage.Label}: {peekedText}");
ct++;
}
Assert.AreEqual(messageCt, ct);
}
}
[Test]
public async Task ReceiveMessagesInPeekLockMode()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var sender = new QueueSenderClient(TestEnvironment.ServiceBusConnectionString, scope.QueueName);
var messageCount = 10;
IEnumerable<ServiceBusMessage> messages = GetMessages(messageCount);
await sender.SendRangeAsync(messages);
var receiver = new QueueReceiverClient(TestEnvironment.ServiceBusConnectionString, scope.QueueName);
var receivedMessageCount = 0;
var messageEnum = messages.GetEnumerator();
await foreach (var item in receiver.ReceiveBatchAsync(messageCount))
{
receivedMessageCount++;
messageEnum.MoveNext();
Assert.AreEqual(item.MessageId, messageEnum.Current.MessageId);
Assert.AreEqual(item.SystemProperties.DeliveryCount, 1);
}
Assert.AreEqual(receivedMessageCount, messageCount);
messageEnum.Reset();
IAsyncEnumerable<ServiceBusMessage> peekMessages = receiver.PeekRangeAsync(messageCount);
await foreach (var item in peekMessages)
{
messageEnum.MoveNext();
Assert.AreEqual(item.MessageId, messageEnum.Current.MessageId);
}
}
}
[Test]
public async Task ReceiveMessagesInReceiveAndDeleteMode()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var sender = new QueueSenderClient(TestEnvironment.ServiceBusConnectionString, scope.QueueName);
var messageCount = 10;
IEnumerable<ServiceBusMessage> messages = GetMessages(messageCount);
await sender.SendRangeAsync(messages);
var clientOptions = new QueueReceiverClientOptions()
{
ReceiveMode = ReceiveMode.ReceiveAndDelete,
};
var receiver = new QueueReceiverClient(TestEnvironment.ServiceBusConnectionString, scope.QueueName, clientOptions);
var receivedMessageCount = 0;
var messageEnum = messages.GetEnumerator();
await foreach (var item in receiver.ReceiveBatchAsync(messageCount))
{
messageEnum.MoveNext();
Assert.AreEqual(item.MessageId, messageEnum.Current.MessageId);
receivedMessageCount++;
}
Assert.AreEqual(receivedMessageCount, messageCount);
var message = receiver.PeekAsync();
Assert.IsNull(message.Result);
}
}
}
}
| 43.784483 | 131 | 0.604843 | [
"MIT"
] | LijuanZ/azure-sdk-for-net | sdk/servicebus/Azure.Messaging.ServiceBus/tests/ReceiverLiveTests.cs | 5,081 | C# |
using Ftec.ProjetosWeb.WebApi.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Uniftec.ProjetosWeb.Application;
using Uniftec.ProjetosWeb.Repository;
namespace Ftec.ProjetosWeb.WebApi.Controllers
{
/// <summary>
/// API responsável por fazer a manutenção de Sensores
/// </summary>
public class SensorController : ApiController
{
/// <summary>
/// Este método retorna uma listagem de todos os Sensores
/// </summary>
/// <returns>Nao possui retorno</returns>
public HttpResponseMessage Get()
{
try
{
List<Sensor> SensoresModel = new List<Sensor>();
SensorRepository SensorRepository = new SensorRepository(ConfigurationManager.ConnectionStrings["conexao"].ToString());
SensorApplication SensorApplication = new SensorApplication(SensorRepository);
List<Uniftec.ProjetosWeb.Domain.Entities.Sensor> Sensores = SensorApplication.ProcurarTodos();
//Realizar o adapter entre a entidade e o modelo de dados do dominio
foreach (var sen in Sensores)
{
SensoresModel.Add(new Sensor()
{
Id = sen.Id,
Temperatura = sen.Temperatura,
Pressao = sen.Pressao,
Altitude = sen.Altitude,
Umidade = sen.Umidade,
Data = sen.Data,
PontoOrvalho = sen.PontoOrvalho,
MacAddressServidor = sen.MacAddressServidor
});
}
return Request.CreateResponse(HttpStatusCode.OK, SensoresModel);
}
catch (ApplicationException ap)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ap);
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
/// <summary>
/// Este método retorna um Sensor a partir do seu ID
/// </summary>
/// <param name="id">Id relativo a chave de busca para o Sensor</param>
/// <returns>Retorna um Sensor</returns>
public HttpResponseMessage Get(Guid id)
{
try
{
Sensor SensorModel = null;
SensorRepository SensorRepository = new SensorRepository(ConfigurationManager.ConnectionStrings["conexao"].ToString());
SensorApplication SensorApplication = new SensorApplication(SensorRepository);
Uniftec.ProjetosWeb.Domain.Entities.Sensor Sensor = SensorApplication.Procurar(id);
//Realizar o adapter entre a entidade e o modelo de dados do dominio
if (Sensor != null)
{
SensorModel = new Sensor()
{
Id = Sensor.Id,
Temperatura = Sensor.Temperatura,
Pressao = Sensor.Pressao,
Altitude = Sensor.Altitude,
Umidade = Sensor.Umidade,
Data = Sensor.Data,
PontoOrvalho = Sensor.PontoOrvalho,
MacAddressServidor = Sensor.MacAddressServidor
};
return Request.CreateResponse(HttpStatusCode.OK, SensorModel);
}
else
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
public HttpResponseMessage Post([FromBody] Sensor Sensor)
{
try
{
//Inclusão do Sensor na base de dados
//Essa inclusao retorna um ID
//Id retornado para o requisitante do serviço
SensorRepository SensorRepository = new SensorRepository(ConfigurationManager.ConnectionStrings["conexao"].ToString());
SensorApplication SensorApplication = new SensorApplication(SensorRepository);
//Converter o model para uma entidade de dominio
Uniftec.ProjetosWeb.Domain.Entities.Sensor SensorDomain = new Uniftec.ProjetosWeb.Domain.Entities.Sensor()
{
Id = Sensor.Id,
Temperatura = Sensor.Temperatura,
Pressao = Sensor.Pressao,
Altitude = Sensor.Altitude,
Umidade = Sensor.Umidade,
Data = Sensor.Data,
PontoOrvalho = Sensor.PontoOrvalho,
MacAddressServidor = Sensor.MacAddressServidor
};
SensorApplication.Inserir(SensorDomain);
return Request.CreateErrorResponse(HttpStatusCode.OK, Convert.ToString(SensorDomain.Id));
}
catch(Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
public HttpResponseMessage Put(Guid id, [FromBody] Sensor Sensor)
{
try
{
//Alterar o Sensor na base de dados
//Essa alteracao retorna um ID
//Id retornado para o requisitante do serviço
SensorRepository SensorRepository = new SensorRepository(ConfigurationManager.ConnectionStrings["conexao"].ToString());
SensorApplication SensorApplication = new SensorApplication(SensorRepository);
//Converter o model para uma entidade de dominio
Uniftec.ProjetosWeb.Domain.Entities.Sensor SensorDomain = new Uniftec.ProjetosWeb.Domain.Entities.Sensor()
{
Id = Sensor.Id,
Temperatura = Sensor.Temperatura,
Pressao = Sensor.Pressao,
Altitude = Sensor.Altitude,
Umidade = Sensor.Umidade,
Data = Sensor.Data,
PontoOrvalho = Sensor.PontoOrvalho,
MacAddressServidor = Sensor.MacAddressServidor
};
SensorApplication.Alterar(SensorDomain);
return Request.CreateErrorResponse(HttpStatusCode.OK, Convert.ToString(id));
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
public HttpResponseMessage Delete(Guid id)
{
try
{
//Excluir o Sensor na base de dados
//Essa exclusão retorna verdadeiro ou falso
SensorRepository SensorRepository = new SensorRepository(ConfigurationManager.ConnectionStrings["conexao"].ToString());
SensorApplication SensorApplication = new SensorApplication(SensorRepository);
var retorno = SensorApplication.Excluir(id);
return Request.CreateErrorResponse(HttpStatusCode.OK, Convert.ToString(retorno));
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
}
} | 39.96875 | 135 | 0.554861 | [
"MIT"
] | amanda-maschio/gerenciamento-datacenter | Ftec.ProjetosWeb.WebApi/Controllers/SensorController.cs | 7,685 | C# |
using Newtonsoft.Json;
namespace CossSharp.Models
{
public class CossWebCoin
{
[JsonProperty("currency_code")]
public string CurrencyCode { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("buy_limit")]
public decimal BuyLimit { get; set; }
[JsonProperty("sell_limit")]
public decimal SellLimit { get; set; }
[JsonProperty("usdt")]
public decimal Usdt { get; set; }
[JsonProperty("transaction_time_limit")]
public decimal TransactionTimeLimit { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("withdrawn_fee")]
public decimal? WithdrawnFee { get; set; }
[JsonProperty("minimum_withdrawn_amount")]
public decimal MinimumWithdrawnAmount { get; set; }
[JsonProperty("minimum_deposit_amount")]
public decimal MinimumDepositAmount { get; set; }
[JsonProperty("minimum_order_amount")]
public decimal MinimumOrderAmount { get; set; }
[JsonProperty("decimal_format")]
public string DecimalFormat { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("buy_at")]
public decimal BuyAt { get; set; }
[JsonProperty("sell_at")]
public decimal SellAt { get; set; }
[JsonProperty("min_rate")]
public decimal MinRate { get; set; }
[JsonProperty("max_rate")]
public decimal MaxRate { get; set; }
[JsonProperty("allow_withdrawn")]
public bool AllowWithdrawn { get; set; }
[JsonProperty("allow_deposit")]
public bool AllowDeposit { get; set; }
[JsonProperty("explorer_website_mainnet_link")]
public string ExplorerWebsiteMainnetLink { get; set; }
[JsonProperty("explorer_website_testnet_link")]
public string ExplorerWebsiteTestnetLink { get; set; }
[JsonProperty("deposit_block_confirmation")]
public decimal? DepositBlockConfirmation { get; set; }
[JsonProperty("withdraw_block_confirmation")]
public decimal? WithdrawBlockConfirmation { get; set; }
[JsonProperty("icon_url")]
public string IconUrl { get; set; }
[JsonProperty("is_fiat")]
public bool IsFiat { get; set; }
[JsonProperty("allow_sell")]
public bool AllowSell { get; set; }
[JsonProperty("allow_buy")]
public bool AllowBuy { get; set; }
}
}
| 28.876404 | 63 | 0.619066 | [
"MIT"
] | merklegroot/CossSharp | CossSharp/Models/CossWebCoin.cs | 2,572 | 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 dms-2016-01-01.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.DatabaseMigrationService.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.DatabaseMigrationService.Model.Internal.MarshallTransformations
{
/// <summary>
/// ModifyEndpoint Request Marshaller
/// </summary>
public class ModifyEndpointRequestMarshaller : IMarshaller<IRequest, ModifyEndpointRequest> , 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((ModifyEndpointRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(ModifyEndpointRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.DatabaseMigrationService");
string target = "AmazonDMSv20160101.ModifyEndpoint";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.HttpMethod = "POST";
string uriResourcePath = "/";
request.ResourcePath = uriResourcePath;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetCertificateArn())
{
context.Writer.WritePropertyName("CertificateArn");
context.Writer.Write(publicRequest.CertificateArn);
}
if(publicRequest.IsSetDatabaseName())
{
context.Writer.WritePropertyName("DatabaseName");
context.Writer.Write(publicRequest.DatabaseName);
}
if(publicRequest.IsSetEndpointArn())
{
context.Writer.WritePropertyName("EndpointArn");
context.Writer.Write(publicRequest.EndpointArn);
}
if(publicRequest.IsSetEndpointIdentifier())
{
context.Writer.WritePropertyName("EndpointIdentifier");
context.Writer.Write(publicRequest.EndpointIdentifier);
}
if(publicRequest.IsSetEndpointType())
{
context.Writer.WritePropertyName("EndpointType");
context.Writer.Write(publicRequest.EndpointType);
}
if(publicRequest.IsSetEngineName())
{
context.Writer.WritePropertyName("EngineName");
context.Writer.Write(publicRequest.EngineName);
}
if(publicRequest.IsSetExtraConnectionAttributes())
{
context.Writer.WritePropertyName("ExtraConnectionAttributes");
context.Writer.Write(publicRequest.ExtraConnectionAttributes);
}
if(publicRequest.IsSetPassword())
{
context.Writer.WritePropertyName("Password");
context.Writer.Write(publicRequest.Password);
}
if(publicRequest.IsSetPort())
{
context.Writer.WritePropertyName("Port");
context.Writer.Write(publicRequest.Port);
}
if(publicRequest.IsSetServerName())
{
context.Writer.WritePropertyName("ServerName");
context.Writer.Write(publicRequest.ServerName);
}
if(publicRequest.IsSetServiceAccessRoleArn())
{
context.Writer.WritePropertyName("ServiceAccessRoleArn");
context.Writer.Write(publicRequest.ServiceAccessRoleArn);
}
if(publicRequest.IsSetSslMode())
{
context.Writer.WritePropertyName("SslMode");
context.Writer.Write(publicRequest.SslMode);
}
if(publicRequest.IsSetUsername())
{
context.Writer.WritePropertyName("Username");
context.Writer.Write(publicRequest.Username);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
}
} | 37.2375 | 143 | 0.584089 | [
"Apache-2.0"
] | Bynder/aws-sdk-net | sdk/src/Services/DatabaseMigrationService/Generated/Model/Internal/MarshallTransformations/ModifyEndpointRequestMarshaller.cs | 5,958 | C# |
namespace DotA2.Gambling.Model
{
public class GambleResult
{
public float Odds { get; set; }
public Prediction Prediction { get; set; }
public Prediction Result { get; set; }
public float Win { get; set; }
public float NewBalance { get; set; }
public int BettingAccountId { get; set; }
}
} | 30.083333 | 51 | 0.578947 | [
"MIT",
"Unlicense"
] | Cruik/DiscordGambleBot | src/DotA2.Gambling.Model/GambleResult.cs | 363 | C# |
/*
* Intersight REST API
*
* This is Intersight REST API
*
* OpenAPI spec version: 1.0.9-262
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = intersight.Client.SwaggerDateConverter;
namespace intersight.Model
{
/// <summary>
/// ConnectorStreamMessageRef
/// </summary>
[DataContract]
public partial class ConnectorStreamMessageRef : IEquatable<ConnectorStreamMessageRef>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="ConnectorStreamMessageRef" /> class.
/// </summary>
[JsonConstructorAttribute]
public ConnectorStreamMessageRef()
{
}
/// <summary>
/// Gets or Sets Moid
/// </summary>
[DataMember(Name="Moid", EmitDefaultValue=false)]
public string Moid { get; private set; }
/// <summary>
/// Gets or Sets ObjectType
/// </summary>
[DataMember(Name="ObjectType", EmitDefaultValue=false)]
public string ObjectType { get; private 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 ConnectorStreamMessageRef {\n");
sb.Append(" Moid: ").Append(Moid).Append("\n");
sb.Append(" ObjectType: ").Append(ObjectType).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, 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 ConnectorStreamMessageRef);
}
/// <summary>
/// Returns true if ConnectorStreamMessageRef instances are equal
/// </summary>
/// <param name="other">Instance of ConnectorStreamMessageRef to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ConnectorStreamMessageRef other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Moid == other.Moid ||
this.Moid != null &&
this.Moid.Equals(other.Moid)
) &&
(
this.ObjectType == other.ObjectType ||
this.ObjectType != null &&
this.ObjectType.Equals(other.ObjectType)
);
}
/// <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.Moid != null)
hash = hash * 59 + this.Moid.GetHashCode();
if (this.ObjectType != null)
hash = hash * 59 + this.ObjectType.GetHashCode();
return hash;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 32.591549 | 140 | 0.565687 | [
"Apache-2.0"
] | ategaw-cisco/intersight-powershell | csharp/swaggerClient/src/intersight/Model/ConnectorStreamMessageRef.cs | 4,628 | C# |
using System.Collections.Generic;
namespace TableauAPI.RESTHelpers
{
/// <summary>
/// Different versions of server have different URL formats
/// </summary>
public enum ServerVersion
{
/// <summary>
/// Tableau Server 9.x
/// </summary>
Server8_3,
Server9,
Server9_1,
Server9_2,
Server9_3,
Server10_0,
Server10_1,
Server10_2,
Server10_3,
Server10_4,
Server10_5,
Server2018_1,
Server2018_2,
Server2018_3,
Server2019_1,
Server2019_2,
Server2019_3,
Server2019_4,
Server2020_1,
Server2020_2
}
public class ServerVersionLookup
{
public static string APIVersion(ServerVersion version )
{
var mappingA = new Dictionary<ServerVersion, string>()
{
{ ServerVersion.Server8_3, "2.0" },
{ ServerVersion.Server9, "2.0" },
{ ServerVersion.Server9_1, "2.0" },
{ ServerVersion.Server9_2, "2.1" },
{ ServerVersion.Server9_3, "2.2" },
{ ServerVersion.Server10_0, "2.3" },
{ ServerVersion.Server10_1, "2.4" },
{ ServerVersion.Server10_2, "2.5" },
{ ServerVersion.Server10_3, "2.6" },
{ ServerVersion.Server10_4, "2.7" },
{ ServerVersion.Server10_5, "2.8" },
{ ServerVersion.Server2018_1, "3.0" },
{ ServerVersion.Server2018_2, "3.1" },
{ ServerVersion.Server2018_3, "3.2" },
{ ServerVersion.Server2019_1, "3.3" },
{ ServerVersion.Server2019_2, "3.4" },
{ ServerVersion.Server2019_3, "3.5" },
{ ServerVersion.Server2019_4, "3.6" },
{ ServerVersion.Server2020_1, "3.7" },
{ ServerVersion.Server2020_2, "3.8" }
};
return mappingA[version];
}
}
}
| 27.441176 | 66 | 0.555734 | [
"MIT"
] | Micheal-Nguyen/TableauAPI | TableauAPI/RESTHelpers/ServerVersion.cs | 1,868 | C# |
namespace ResXManager.Model
{
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using JetBrains.Annotations;
public abstract class ResourceTableEntryRulePunctuation : IResourceTableEntryRule
{
/// <inheritdoc />
public bool IsEnabled { get; set; }
/// <inheritdoc />
public abstract string RuleId { get; }
public bool CompliesToRule([CanBeNull] string neutralValue, [NotNull, ItemCanBeNull] IEnumerable<string> values, [CanBeNull] out string message)
{
var reference = GetPunctuationSequence(neutralValue).ToArray();
if (values.Select(GetPunctuationSequence).Any(value => !reference.SequenceEqual(value)))
{
message = GetErrorMessage(new string(reference));
return false;
}
message = null;
return true;
}
[NotNull]
protected abstract IEnumerable<char> GetCharIterator([NotNull] string value);
[NotNull]
protected abstract string GetErrorMessage([NotNull] string reference);
[NotNull]
private static string NormalizeUnicode([CanBeNull] string value) => value?.Normalize() ?? string.Empty;
[NotNull]
private IEnumerable<char> GetPunctuationSequence([CanBeNull] string value)
{
return GetCharIterator(NormalizeUnicode(value))
.SkipWhile(char.IsWhiteSpace).
TakeWhile(IsPunctuation).
Select(NormalizePunctuation);
}
private static char NormalizePunctuation(char value)
{
switch ((int)value)
{
case 0x055C: return '!'; // ARMENIAN EXCLAMATION MARK
case 0x055D: return ','; // ARMENIAN COMMA
case 0x055E: return '?'; // ARMENIAN QUESTION MARK
case 0x0589: return '.'; // ARMENIAN FULL STOP
case 0x07F8: return ','; // NKO COMMA
case 0x07F9: return '!'; // NKO EXCLAMATION MARK
case 0x1944: return '!'; // LIMBU EXCLAMATION MARK
case 0x1945: return '?'; // LIMBU QUESTION MARK
case 0x3001: return ','; // IDEOGRAPHIC COMMA
case 0x3002: return '.'; // IDEOGRAPHIC FULL STOP
case 0xFF01: return '!'; // FULLWIDTH EXCLAMATION MARK
case 0xFF0C: return ','; // FULLWIDTH COMMA
case 0xFF0E: return '.'; // FULLWIDTH FULL STOP
case 0xFF1A: return ':'; // FULLWIDTH COLON
case 0xFF1B: return ';'; // FULLWIDTH SEMICOLON
case 0xFF1F: return '?'; // FULLWIDTH QUESTION MARK
default: return value;
}
}
/// <summary>
/// This is used instead of <see cref="char.IsPunctuation(char)"/>, because the default
/// method allows significantly more characters than required.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
private static bool IsPunctuation(char value)
{
// exclude quotes, special chars (\#), hot-key prefixes (&_), language specifics with no common equivalent (¡¿).
const string excluded = "'\"\\#&_¡¿";
// ReSharper disable once SwitchStatementMissingSomeCases
switch (char.GetUnicodeCategory(value))
{
case UnicodeCategory.OtherPunctuation:
return !excluded.Contains(value);
case UnicodeCategory.DashPunctuation:
return true;
default:
return false;
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
| 38.32 | 152 | 0.572025 | [
"MIT"
] | bartekmotyl/ResXResourceManager | ResXManager.Model/ResourceTableEntryRulePunctuation.cs | 3,838 | C# |
using System;
using Newtonsoft.Json;
using System.Xml.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// ZhubUidTelPair Data Structure.
/// </summary>
[Serializable]
public class ZhubUidTelPair : AlipayObject
{
/// <summary>
/// 手机号
/// </summary>
[JsonProperty("phone")]
[XmlElement("phone")]
public string Phone { get; set; }
/// <summary>
/// 支付宝uid
/// </summary>
[JsonProperty("user_id")]
[XmlElement("user_id")]
public string UserId { get; set; }
}
}
| 22.142857 | 52 | 0.558065 | [
"MIT"
] | ciker/PayMent-Core | src/Essensoft.AspNetCore.Payment.Alipay/Domain/ZhubUidTelPair.cs | 632 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.CompilerServices;
namespace System.Runtime.Intrinsics.Arm
{
/// <summary>
/// This class provides access to the ARM base hardware instructions via intrinsics
/// </summary>
[Intrinsic]
[CLSCompliant(false)]
public abstract class ArmBase
{
internal ArmBase() { }
public static bool IsSupported { get => IsSupported; }
[Intrinsic]
public abstract class Arm64
{
internal Arm64() { }
public static bool IsSupported { get => IsSupported; }
/// <summary>
/// A64: CLS Wd, Wn
/// </summary>
public static int LeadingSignCount(int value) => LeadingSignCount(value);
/// <summary>
/// A64: CLS Xd, Xn
/// </summary>
public static int LeadingSignCount(long value) => LeadingSignCount(value);
/// <summary>
/// A64: CLZ Xd, Xn
/// </summary>
public static int LeadingZeroCount(long value) => LeadingZeroCount(value);
/// <summary>
/// A64: CLZ Xd, Xn
/// </summary>
public static int LeadingZeroCount(ulong value) => LeadingZeroCount(value);
/// <summary>
/// A64: SMULH Xd, Xn, Xm
/// </summary>
public static long MultiplyHigh(long left, long right) => MultiplyHigh(left, right);
/// <summary>
/// A64: UMULH Xd, Xn, Xm
/// </summary>
public static ulong MultiplyHigh(ulong left, ulong right) => MultiplyHigh(left, right);
/// <summary>
/// A64: RBIT Xd, Xn
/// </summary>
public static long ReverseElementBits(long value) => ReverseElementBits(value);
/// <summary>
/// A64: RBIT Xd, Xn
/// </summary>
public static ulong ReverseElementBits(ulong value) => ReverseElementBits(value);
}
/// <summary>
/// A32: CLZ Rd, Rm
/// A64: CLZ Wd, Wn
/// </summary>
public static int LeadingZeroCount(int value) => LeadingZeroCount(value);
/// <summary>
/// A32: CLZ Rd, Rm
/// A64: CLZ Wd, Wn
/// </summary>
public static int LeadingZeroCount(uint value) => LeadingZeroCount(value);
/// <summary>
/// A32: RBIT Rd, Rm
/// A64: RBIT Wd, Wn
/// </summary>
public static int ReverseElementBits(int value) => ReverseElementBits(value);
/// <summary>
/// A32: RBIT Rd, Rm
/// A64: RBIT Wd, Wn
/// </summary>
public static uint ReverseElementBits(uint value) => ReverseElementBits(value);
}
}
| 31.782609 | 99 | 0.53249 | [
"MIT"
] | 3DCloud/runtime | src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Arm/ArmBase.cs | 2,924 | C# |
using JPProject.Domain.Core.Events;
namespace JPProject.Sso.Domain.Events.GlobalConfiguration
{
public class GlobalConfigurationCreatedEvent : Event
{
public string Key { get; }
public string Value { get; }
public bool IsPublic { get; }
public bool Sensitive { get; }
public GlobalConfigurationCreatedEvent(string key, string value, in bool isPublic, in bool sensitive)
{
Key = key;
Value = value;
IsPublic = isPublic;
Sensitive = sensitive;
}
}
}
| 27 | 109 | 0.610229 | [
"MIT"
] | dimitertodorov/JPProject.Core | src/SSO/JPProject.Sso.Domain/Events/GlobalConfiguration/GlobalConfigurationCreatedEvent.cs | 569 | C# |
using System;
using System.Windows.Forms;
using SteamAuth;
namespace Steam_Desktop_Authenticator
{
public partial class LoginForm : Form
{
public UserLogin userLogin;
public SteamGuardAccount androidAccount;
public bool refreshLogin = false;
public bool loginFromAndroid = false;
public LoginForm(bool forceAndroidImport = false)
{
InitializeComponent();
}
public void SetUsername(string username)
{
txtUsername.Text = username;
}
public string FilterPhoneNumber(string phoneNumber)
{
return phoneNumber.Replace("-", "").Replace("(", "").Replace(")", "");
}
public bool PhoneNumberOkay(string phoneNumber)
{
if (phoneNumber == null || phoneNumber.Length == 0) return false;
if (phoneNumber[0] != '+') return false;
return true;
}
private void btnSteamLogin_Click(object sender, EventArgs e)
{
string username = txtUsername.Text;
string password = txtPassword.Text;
if (loginFromAndroid)
{
FinishExtract(username, password);
return;
}
else if (refreshLogin)
{
RefreshLogin(username, password);
return;
}
userLogin = new UserLogin(username, password);
LoginResult response = LoginResult.BadCredentials;
while ((response = userLogin.DoLogin()) != LoginResult.LoginOkay)
{
switch (response)
{
case LoginResult.NeedEmail:
InputForm emailForm = new InputForm("Enter the code sent to your email:");
emailForm.ShowDialog();
if (emailForm.Canceled)
{
this.Close();
return;
}
userLogin.EmailCode = emailForm.txtBox.Text;
break;
case LoginResult.NeedCaptcha:
CaptchaForm captchaForm = new CaptchaForm(userLogin.CaptchaGID);
captchaForm.ShowDialog();
if (captchaForm.Canceled)
{
this.Close();
return;
}
userLogin.CaptchaText = captchaForm.CaptchaCode;
break;
case LoginResult.Need2FA:
MessageBox.Show("This account already has a mobile authenticator linked to it.\nRemove the old authenticator from your Steam account before adding a new one.", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
return;
case LoginResult.BadRSA:
MessageBox.Show("Error logging in: Steam returned \"BadRSA\".", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
return;
case LoginResult.BadCredentials:
MessageBox.Show("Error logging in: Username or password was incorrect.", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
return;
case LoginResult.TooManyFailedLogins:
MessageBox.Show("Error logging in: Too many failed logins, try again later.", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
return;
case LoginResult.GeneralFailure:
MessageBox.Show("Error logging in: Steam returned \"GeneralFailure\".", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
return;
}
}
//Login succeeded
SessionData session = userLogin.Session;
AuthenticatorLinker linker = new AuthenticatorLinker(session);
AuthenticatorLinker.LinkResult linkResponse = AuthenticatorLinker.LinkResult.GeneralFailure;
while ((linkResponse = linker.AddAuthenticator()) != AuthenticatorLinker.LinkResult.AwaitingFinalization)
{
switch (linkResponse)
{
case AuthenticatorLinker.LinkResult.MustProvidePhoneNumber:
string phoneNumber = "";
while (!PhoneNumberOkay(phoneNumber))
{
InputForm phoneNumberForm = new InputForm("Enter your phone number in the following format: +{cC} phoneNumber. EG, +1 123-456-7890");
phoneNumberForm.txtBox.Text = "+1 ";
phoneNumberForm.ShowDialog();
if (phoneNumberForm.Canceled)
{
this.Close();
return;
}
phoneNumber = FilterPhoneNumber(phoneNumberForm.txtBox.Text);
}
linker.PhoneNumber = phoneNumber;
break;
case AuthenticatorLinker.LinkResult.MustRemovePhoneNumber:
linker.PhoneNumber = null;
break;
case AuthenticatorLinker.LinkResult.GeneralFailure:
MessageBox.Show("Error adding your phone number. Steam returned \"GeneralFailure\".");
this.Close();
return;
}
}
Manifest manifest = Manifest.GetManifest();
string passKey = null;
if (manifest.Entries.Count == 0)
{
passKey = manifest.PromptSetupPassKey("Please enter an encryption passkey. Leave blank or hit cancel to not encrypt (VERY INSECURE).");
}
else if (manifest.Entries.Count > 0 && manifest.Encrypted)
{
bool passKeyValid = false;
while (!passKeyValid)
{
InputForm passKeyForm = new InputForm("Please enter your current encryption passkey.");
passKeyForm.ShowDialog();
if (!passKeyForm.Canceled)
{
passKey = passKeyForm.txtBox.Text;
passKeyValid = manifest.VerifyPasskey(passKey);
if (!passKeyValid)
{
MessageBox.Show("That passkey is invalid. Please enter the same passkey you used for your other accounts.");
}
}
else
{
this.Close();
return;
}
}
}
//Save the file immediately; losing this would be bad.
if (!manifest.SaveAccount(linker.LinkedAccount, passKey != null, passKey))
{
manifest.RemoveAccount(linker.LinkedAccount);
MessageBox.Show("Unable to save mobile authenticator file. The mobile authenticator has not been linked.");
this.Close();
return;
}
MessageBox.Show("The Mobile Authenticator has not yet been linked. Before finalizing the authenticator, please write down your revocation code: " + linker.LinkedAccount.RevocationCode);
AuthenticatorLinker.FinalizeResult finalizeResponse = AuthenticatorLinker.FinalizeResult.GeneralFailure;
while (finalizeResponse != AuthenticatorLinker.FinalizeResult.Success)
{
InputForm smsCodeForm = new InputForm("Please input the SMS code sent to your phone.");
smsCodeForm.ShowDialog();
if (smsCodeForm.Canceled)
{
manifest.RemoveAccount(linker.LinkedAccount);
this.Close();
return;
}
InputForm confirmRevocationCode = new InputForm("Please enter your revocation code to ensure you've saved it.");
confirmRevocationCode.ShowDialog();
if (confirmRevocationCode.txtBox.Text.ToUpper() != linker.LinkedAccount.RevocationCode)
{
MessageBox.Show("Revocation code incorrect; the authenticator has not been linked.");
manifest.RemoveAccount(linker.LinkedAccount);
this.Close();
return;
}
string smsCode = smsCodeForm.txtBox.Text;
finalizeResponse = linker.FinalizeAddAuthenticator(smsCode);
switch (finalizeResponse)
{
case AuthenticatorLinker.FinalizeResult.BadSMSCode:
continue;
case AuthenticatorLinker.FinalizeResult.UnableToGenerateCorrectCodes:
MessageBox.Show("Unable to generate the proper codes to finalize this authenticator. The authenticator should not have been linked. In the off-chance it was, please write down your revocation code, as this is the last chance to see it: " + linker.LinkedAccount.RevocationCode);
manifest.RemoveAccount(linker.LinkedAccount);
this.Close();
return;
case AuthenticatorLinker.FinalizeResult.GeneralFailure:
MessageBox.Show("Unable to finalize this authenticator. The authenticator should not have been linked. In the off-chance it was, please write down your revocation code, as this is the last chance to see it: " + linker.LinkedAccount.RevocationCode);
manifest.RemoveAccount(linker.LinkedAccount);
this.Close();
return;
}
}
//Linked, finally. Re-save with FullyEnrolled property.
manifest.SaveAccount(linker.LinkedAccount, passKey != null, passKey);
MessageBox.Show("Mobile authenticator successfully linked. Please write down your revocation code: " + linker.LinkedAccount.RevocationCode);
this.Close();
}
/// <summary>
/// Handles logging in to refresh session data. i.e. changing steam password.
/// </summary>
/// <param name="username">Steam username</param>
/// <param name="password">Steam password</param>
private async void RefreshLogin(string username, string password)
{
long steamTime = await TimeAligner.GetSteamTimeAsync();
Manifest man = Manifest.GetManifest();
androidAccount.FullyEnrolled = true;
UserLogin mUserLogin = new UserLogin(username, password);
LoginResult response = LoginResult.BadCredentials;
while ((response = mUserLogin.DoLogin()) != LoginResult.LoginOkay)
{
switch (response)
{
case LoginResult.NeedEmail:
InputForm emailForm = new InputForm("Enter the Steam Guard code sent to your email:");
emailForm.ShowDialog();
if (emailForm.Canceled)
{
this.Close();
return;
}
mUserLogin.EmailCode = emailForm.txtBox.Text;
break;
case LoginResult.NeedCaptcha:
CaptchaForm captchaForm = new CaptchaForm(mUserLogin.CaptchaGID);
captchaForm.ShowDialog();
if (captchaForm.Canceled)
{
this.Close();
return;
}
mUserLogin.CaptchaText = captchaForm.CaptchaCode;
break;
case LoginResult.Need2FA:
mUserLogin.TwoFactorCode = androidAccount.GenerateSteamGuardCodeForTime(steamTime);
break;
case LoginResult.BadRSA:
MessageBox.Show("Error logging in: Steam returned \"BadRSA\".", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
return;
case LoginResult.BadCredentials:
MessageBox.Show("Error logging in: Username or password was incorrect.", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
return;
case LoginResult.TooManyFailedLogins:
MessageBox.Show("Error logging in: Too many failed logins, try again later.", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
return;
case LoginResult.GeneralFailure:
MessageBox.Show("Error logging in: Steam returned \"GeneralFailure\".", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
return;
}
}
androidAccount.Session = mUserLogin.Session;
HandleManifest(man, true);
}
/// <summary>
/// Handles logging in after data has been extracted from Android phone
/// </summary>
/// <param name="username">Steam username</param>
/// <param name="password">Steam password</param>
private async void FinishExtract(string username, string password)
{
long steamTime = await TimeAligner.GetSteamTimeAsync();
Manifest man = Manifest.GetManifest();
androidAccount.FullyEnrolled = true;
UserLogin mUserLogin = new UserLogin(username, password);
LoginResult response = LoginResult.BadCredentials;
while ((response = mUserLogin.DoLogin()) != LoginResult.LoginOkay)
{
switch (response)
{
case LoginResult.NeedEmail:
InputForm emailForm = new InputForm("Enter the code sent to your email:");
emailForm.ShowDialog();
if (emailForm.Canceled)
{
this.Close();
return;
}
mUserLogin.EmailCode = emailForm.txtBox.Text;
break;
case LoginResult.NeedCaptcha:
CaptchaForm captchaForm = new CaptchaForm(mUserLogin.CaptchaGID);
captchaForm.ShowDialog();
if (captchaForm.Canceled)
{
this.Close();
return;
}
mUserLogin.CaptchaText = captchaForm.CaptchaCode;
break;
case LoginResult.Need2FA:
mUserLogin.TwoFactorCode = androidAccount.GenerateSteamGuardCodeForTime(steamTime);
break;
case LoginResult.BadRSA:
MessageBox.Show("Error logging in: Steam returned \"BadRSA\".", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
return;
case LoginResult.BadCredentials:
MessageBox.Show("Error logging in: Username or password was incorrect.", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
return;
case LoginResult.TooManyFailedLogins:
MessageBox.Show("Error logging in: Too many failed logins, try again later.", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
return;
case LoginResult.GeneralFailure:
MessageBox.Show("Error logging in: Steam returned \"GeneralFailure\".", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
return;
}
}
androidAccount.Session = mUserLogin.Session;
HandleManifest(man);
}
private void HandleManifest(Manifest man, bool IsRefreshing = false)
{
string passKey = null;
if (man.Entries.Count == 0)
{
passKey = man.PromptSetupPassKey("Please enter an encryption passkey. Leave blank or hit cancel to not encrypt (VERY INSECURE).");
}
else if (man.Entries.Count > 0 && man.Encrypted)
{
bool passKeyValid = false;
while (!passKeyValid)
{
InputForm passKeyForm = new InputForm("Please enter your current encryption passkey.");
passKeyForm.ShowDialog();
if (!passKeyForm.Canceled)
{
passKey = passKeyForm.txtBox.Text;
passKeyValid = man.VerifyPasskey(passKey);
if (!passKeyValid)
{
MessageBox.Show("That passkey is invalid. Please enter the same passkey you used for your other accounts.");
}
}
else
{
this.Close();
return;
}
}
}
man.SaveAccount(androidAccount, passKey != null, passKey);
if (IsRefreshing)
{
MessageBox.Show("Your login session was refreshed.");
}
else
{
MessageBox.Show("Mobile authenticator successfully linked. Please write down your revocation code: " + androidAccount.RevocationCode);
}
this.Close();
}
private void LoginForm_Load(object sender, EventArgs e)
{
if (androidAccount != null && androidAccount.AccountName != null)
{
txtUsername.Text = androidAccount.AccountName;
}
}
}
}
| 43.961538 | 302 | 0.497864 | [
"MIT"
] | Block0511/SteamDesktopAuthenticator | Steam Desktop Authenticator/LoginForm.cs | 19,431 | C# |
using System;
using System.Reactive.Linq;
namespace TDD_Katas_project.FizzBuzzKata.Rx
{
/// <summary>
/// Added a different implementation for FizzBuzz using Reactive extensions.
/// The changes are described at: http://blog.drorhelper.com/2015/02/fizzbuzz-tdd-kata-using-reactive.html
/// Pull Request by: https://github.com/dhelper
/// These changes have been manually merged into repository
/// </summary>
public class FizzBuzzRx
{
public static string Generate(int max)
{
var result = string.Empty;
if (max <= 0)
{
return result;
}
var observable = Observable.Range(1, max);
var dividedByThree = observable
.Where(i => i % 3 == 0)
.Select(_ => "Fizz");
var dividedByFive = observable
.Where(i => i % 5 == 0)
.Select(_ => "Buzz");
var simpleNumbers = observable
.Where(i => i % 3 != 0 && i % 5 != 0)
.Select(i => i.ToString());
var commaDelimiter = observable.Select(_ => ",");
IObservable<string> specialCases = (dividedByThree).Merge(dividedByFive);
simpleNumbers
.Merge(specialCases)
.Merge(commaDelimiter)
.Subscribe(s => result += s);
return result;
}
}
} | 30.510638 | 110 | 0.529289 | [
"Apache-2.0"
] | illusionsnew/TDD-samples | Src/cs/FizzBuzzKata/Rx/FizzBuzzRx.cs | 1,436 | C# |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace Zephyr.Utils.NPOI.DDF
{
using System;
using System.Collections;
/// <summary>
/// This class stores the type and description of an escher property.
/// @author Glen Stampoultzis (glens at apache.org)
/// </summary>
public class EscherPropertyMetaData
{
// Escher property types.
public const byte TYPE_UNKNOWN = (byte)0;
public const byte TYPE_bool = (byte)1;
public const byte TYPE_RGB = (byte)2;
public const byte TYPE_SHAPEPATH = (byte)3;
public const byte TYPE_SIMPLE = (byte)4;
public const byte TYPE_ARRAY = (byte)5;
private String description;
private byte type;
/// <summary>
/// Initializes a new instance of the <see cref="EscherPropertyMetaData"/> class.
/// </summary>
/// <param name="description">The description of the escher property.</param>
public EscherPropertyMetaData(String description)
{
this.description = description;
}
/// <summary>
/// Initializes a new instance of the <see cref="EscherPropertyMetaData"/> class.
/// </summary>
/// <param name="description">The description of the escher property.</param>
/// <param name="type">The type of the property.</param>
public EscherPropertyMetaData(String description, byte type)
{
this.description = description;
this.type = type;
}
/// <summary>
/// Gets the description.
/// </summary>
/// <value>The description.</value>
public String Description
{
get { return description; }
}
/// <summary>
/// Gets the type.
/// </summary>
/// <value>The type.</value>
public byte Type
{
get { return type; }
}
}
} | 34.975309 | 89 | 0.594423 | [
"MIT"
] | zhupangithub/WEBERP | Code/Zephyr.Net/Zephyr.Utils/Document/Excel/NPOI/DDF/EscherPropertyMetaData.cs | 2,833 | C# |
using System.Net.Http;
using System.Threading.Tasks;
using Covid19Api.Constants;
using Covid19Api.Services.Abstractions.Loader;
using HtmlAgilityPack;
namespace Covid19Api.Services.Loader
{
public class HtmlDocumentLoader : IHtmlDocumentLoader
{
private readonly IHttpClientFactory httpClientFactory;
public HtmlDocumentLoader(IHttpClientFactory httpClientFactory)
{
this.httpClientFactory = httpClientFactory;
}
public async Task<HtmlDocument> LoadAsync()
{
var client = this.httpClientFactory.CreateClient();
var response = await client.GetAsync(Urls.Covid19WorldometerUrl);
var document = new HtmlDocument();
document.LoadHtml(await response.Content.ReadAsStringAsync());
return document;
}
}
} | 27.225806 | 77 | 0.689573 | [
"MIT"
] | alsami/Covid-19-API | src/Covid19Api.Services/Loader/HtmlDocumentLoader.cs | 844 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.ContentManagement.Handlers;
using Orchard.Localization;
using Orchard.Widgets.Models;
using Orchard.Widgets.Services;
namespace Orchard.Widgets.Drivers {
[UsedImplicitly]
public class LayerPartDriver : ContentPartDriver<LayerPart> {
private readonly IRuleManager _ruleManager;
private readonly IWidgetsService _widgetsService;
public LayerPartDriver(
IRuleManager ruleManager,
IWidgetsService widgetsService) {
_ruleManager = ruleManager;
_widgetsService = widgetsService;
T = NullLocalizer.Instance;
}
public Localizer T { get; set; }
protected override DriverResult Editor(LayerPart layerPart, dynamic shapeHelper) {
var results = new List<DriverResult> {
ContentShape("Parts_Widgets_LayerPart",
() => shapeHelper.EditorTemplate(TemplateName: "Parts.Widgets.LayerPart", Model: layerPart, Prefix: Prefix))
};
if (layerPart.Id > 0)
results.Add(ContentShape("Widget_DeleteButton",
deleteButton => deleteButton));
return Combined(results.ToArray());
}
protected override DriverResult Editor(LayerPart layerPart, IUpdateModel updater, dynamic shapeHelper) {
if(updater.TryUpdateModel(layerPart, Prefix, null, null)) {
if (String.IsNullOrWhiteSpace(layerPart.LayerRule)) {
layerPart.LayerRule = "true";
}
if (_widgetsService.GetLayers()
.Any(l =>
l.Id != layerPart.Id
&& String.Equals(l.Name, layerPart.Name, StringComparison.InvariantCultureIgnoreCase))) {
updater.AddModelError("Name", T("A Layer with the same name already exists"));
}
try {
_ruleManager.Matches(layerPart.LayerRule);
}
catch (Exception e) {
updater.AddModelError("Description", T("The rule is not valid: {0}", e.Message));
}
}
return Editor(layerPart, shapeHelper);
}
protected override void Importing(LayerPart part, ImportContentContext context) {
var name = context.Attribute(part.PartDefinition.Name, "Name");
if (name != null) {
part.Name = name;
}
var description = context.Attribute(part.PartDefinition.Name, "Description");
if (description != null) {
part.Description = description;
}
var rule = context.Attribute(part.PartDefinition.Name, "LayerRule");
if (rule != null) {
part.LayerRule = rule;
}
}
protected override void Exporting(LayerPart part, ExportContentContext context) {
context.Element(part.PartDefinition.Name).SetAttributeValue("Name", part.Name);
context.Element(part.PartDefinition.Name).SetAttributeValue("Description", part.Description);
context.Element(part.PartDefinition.Name).SetAttributeValue("LayerRule", part.LayerRule);
}
}
} | 37.846154 | 137 | 0.601626 | [
"BSD-3-Clause"
] | ArsenShnurkov/OrchardCMS-1.7.3-for-mono | src/Orchard.Web/Modules/Orchard.Widgets/Drivers/LayerPartDriver.cs | 3,446 | C# |
using System.Collections.Generic;
using CipherMachine;
using Words;
using UnityEngine;
public class McDondaldsChickenNuggetBigMacCipher : CipherBase
{
public override string Name { get { return "McDondalds™ Chicken Nugget Big Mac Cipher"; } }
public override int Score { get { return 5; } }
public override string Code { get { return "MD"; } }
public override ResultInfo Encrypt(string word, KMBombInfo bomb)
{
var logMessages = new List<string>();
string alpha = "ZABCDEFGHIJKLMNOPQRSTUVWXY", encrypt = "";
int[] vals = generateValues();
int burgerPrice = vals[0], nuggetPrice = vals[1], nuggetCount = vals[2];
string[] screens = { intToPrice(burgerPrice), intToPrice(nuggetPrice), nuggetCount + " Pc.", ""};
for(int i = 0; i < 3; i++)
logMessages.Add(string.Format("Screen {0}: {1}", (i + 1), screens[i]));
for (int i = 0; i < word.Length / 2; i++)
{
string temp = base10To26(alpha.IndexOf(word[i * 2]) * nuggetPrice + alpha.IndexOf(word[i * 2 + 1]) * burgerPrice);
screens[3] = screens[3] + "" + temp[0];
encrypt = encrypt + "" + temp.Substring(1);
}
logMessages.Add(string.Format("Screen 4: {0}", screens[3]));
if (word.Length % 2 == 1)
encrypt = encrypt + "" + word[word.Length - 1];
return new ResultInfo
{
LogMessages = logMessages,
Encrypted = encrypt,
Pages = new[] { new PageInfo(new ScreenInfo[] { screens[0], null, screens[1], null, screens[2], null, screens[3] }) }
};
}
private int[] generateValues()
{
tryagain:
int burgerPrice = Random.Range(99, 425);
List<int> possNuggetPrices = new List<int>();
for (int i = (burgerPrice * 20) / 100; i < (burgerPrice * 60) / 100; i++)
{
if (GCD(burgerPrice, i) == 1)
possNuggetPrices.Add(i);
}
if (possNuggetPrices.Count == 0)
goto tryagain;
int nuggetPrice = possNuggetPrices[Random.Range(0, possNuggetPrices.Count)];
int nuggetCount = EEA(burgerPrice, nuggetPrice);
if(nuggetCount > nuggetPrice)
{
var temp = nuggetCount;
nuggetCount = nuggetPrice;
nuggetPrice = temp;
}
return new int[] { burgerPrice, nuggetPrice, nuggetCount };
}
private int GCD(int a, int b)
{
if (b > a)
{
int temp = a + 0;
a = b + 0;
b = temp + 0;
}
int r = a % b;
while (r > 0)
{
a = b;
b = r;
r = a % b;
}
return b;
}
private int EEA(int A, int B)
{
int init = A + 0;
int Q = A / B;
int R = A % B;
int T1 = 0;
int T2 = 1;
int T3 = T1 - (T2 * Q);
while (R > 0)
{
A = B;
B = R;
Q = A / B;
R = A % B;
T1 = T2;
T2 = T3;
T3 = T1 - (T2 * Q);
}
return CMTools.mod(T2, init);
}
private string intToPrice(int n)
{
string price = "$" + (n / 100);
if (n % 100 < 10)
price = price + ".0" + (n % 100);
else
price = price + "." + (n % 100);
return price;
}
private string base10To26(int num)
{
string conv = "", alpha = "ZABCDEFGHIJKLMNOPQRSTUVWXY";
while(num > 0)
{
conv = alpha[num % 26] + "" + conv;
num /= 26;
}
while (conv.Length < 3)
conv = "Z" + conv;
return conv;
}
private int base26To10(string num)
{
string alpha = "ZABCDEFGHIJKLMNOPQRSTUVWXY";
int conv = 0, mult = 1;
for(int i = num.Length - 1; i >= 0; i--)
conv += (mult * alpha.IndexOf(num[i]));
return conv;
}
}
| 31.927419 | 129 | 0.490023 | [
"MIT"
] | obachs971/CipherCollection | Assets/Scripts/Ciphers/McDondaldsChickenNuggetBigMacCipher.cs | 3,963 | C# |
/* INFINITY CODE 2013-2019 */
/* http://www.infinity-code.com */
using System;
using System.IO;
using System.Text.RegularExpressions;
using InfinityCode.RealWorldTerrain.Generators;
using InfinityCode.RealWorldTerrain.Windows;
using UnityEditor;
using UnityEngine;
namespace InfinityCode.RealWorldTerrain.Phases
{
public class RealWorldTerrainGenerateTerrainsPhase : RealWorldTerrainPhase
{
public static RealWorldTerrainItem activeTerrainItem;
private RealWorldTerrainContainer container;
private double maxElevation;
private double minElevation;
private Vector3 size;
private Vector3 scale;
public override string title
{
get { return "Generate Terrains..."; }
}
private static RealWorldTerrainItem AddTerrainItem(int x, int y, double x1, double y1, double x2, double y2, Vector3 size, Vector3 scale, double maxElevation, double minElevation, GameObject GO)
{
RealWorldTerrainItem item = GO.AddComponent<RealWorldTerrainItem>();
prefs.Apply(item);
item.SetCoordinates(x1, y1, x2, y2);
item.maxElevation = maxElevation;
item.minElevation = minElevation;
item.scale = scale;
item.size = size;
item.x = x;
item.ry = prefs.terrainCount.y - y - 1;
item.y = y;
item.bounds = new Bounds(item.transform.position + size / 2, size);
activeTerrainItem = item;
return item;
}
private RealWorldTerrainItem CreateMesh(Transform parent, int x, int y, double x1, double y1, double x2, double y2, Vector3 size, Vector3 scale, double maxElevation, double minElevation)
{
GameObject GO = new GameObject();
GO.transform.parent = parent;
GO.transform.position = new Vector3(size.x * x, 0, size.z * y);
RealWorldTerrainItem item = AddTerrainItem(x, y, x1, y1, x2, y2, size, scale, maxElevation, minElevation, GO);
GO.name = Regex.Replace(RealWorldTerrainPrefs.LoadPref("TerrainName", "Terrain {x}x{y}"), @"{\w+}", ReplaceTerrainToken);
return item;
}
private RealWorldTerrainItem CreateTerrain(Transform parent, int x, int y, double x1, double y1, double x2, double y2, Vector3 size, Vector3 scale, double maxElevation, double minElevation)
{
TerrainData tdata = new TerrainData
{
baseMapResolution = prefs.baseMapResolution,
heightmapResolution = prefs.heightmapResolution
};
tdata.SetDetailResolution(prefs.detailResolution, prefs.resolutionPerPatch);
tdata.size = size;
GameObject GO = Terrain.CreateTerrainGameObject(tdata);
GO.transform.parent = parent;
GO.transform.position = new Vector3(size.x * x, 0, size.z * y);
GameObjectUtility.SetStaticEditorFlags(GO, GameObjectUtility.GetStaticEditorFlags(GO) & ~StaticEditorFlags.ContributeGI);
RealWorldTerrainItem item = AddTerrainItem(x, y, x1, y1, x2, y2, size, scale, maxElevation, minElevation, GO);
item.terrain = GO.GetComponent<Terrain>();
GO.name = Regex.Replace(RealWorldTerrainPrefs.LoadPref("TerrainName", "Terrain {x}x{y}"), @"{\w+}", ReplaceTerrainToken);
string filename = Path.Combine(container.folder, GO.name) + ".asset";
AssetDatabase.CreateAsset(tdata, filename);
AssetDatabase.SaveAssets();
return item;
}
public override void Enter()
{
if (index >= prefs.terrainCount)
{
Complete();
return;
}
RealWorldTerrainVector2i tCount = prefs.terrainCount;
int x = index % tCount.x;
int y = index / tCount.x;
double fromX = prefs.coordinatesFrom.x;
double fromY = prefs.coordinatesFrom.y;
double toX = prefs.coordinatesTo.x;
double toY = prefs.coordinatesTo.y;
RealWorldTerrainUtils.LatLongToMercat(ref fromX, ref fromY);
RealWorldTerrainUtils.LatLongToMercat(ref toX, ref toY);
double tx1 = (toX - fromX) * (x / (double)tCount.x) + fromX;
double ty1 = toY - (toY - fromY) * ((y + 1) / (double)tCount.y);
double tx2 = (toX - fromX) * ((x + 1) / (double)tCount.x) + fromX;
double ty2 = toY - (toY - fromY) * (y / (double)tCount.y);
int tIndex = y * tCount.x + x;
progress = index / (float)tCount;
if (prefs.resultType == RealWorldTerrainResultType.terrain)
{
terrains[x, y] = container.terrains[tIndex] = CreateTerrain(container.transform, x, y, tx1, ty1, tx2, ty2, size, scale, maxElevation, minElevation);
}
else if (prefs.resultType == RealWorldTerrainResultType.mesh)
{
terrains[x, y] = container.terrains[tIndex] = CreateMesh(container.transform, x, y, tx1, ty1, tx2, ty2, size, scale, maxElevation, minElevation);
}
container.terrains[tIndex].container = container;
index++;
}
public override void Finish()
{
activeTerrainItem = null;
container = null;
}
private string ReplaceResultToken(Match match)
{
string v = match.Value.ToLower().Trim('{', '}');
if (v == "title") return prefs.title;
if (v == "tllat") return prefs.coordinatesFrom.y.ToString();
if (v == "tllng") return prefs.coordinatesFrom.x.ToString();
if (v == "brlat") return prefs.coordinatesTo.y.ToString();
if (v == "brlng") return prefs.coordinatesTo.x.ToString();
if (v == "cx") return prefs.terrainCount.x.ToString();
if (v == "cy") return prefs.terrainCount.y.ToString();
if (v == "st") return prefs.sizeType.ToString();
if (v == "me") return prefs.maxElevationType.ToString();
if (v == "mu") return prefs.nodataValue.ToString();
if (v == "ds") return prefs.depthSharpness.ToString();
if (v == "dr") return prefs.detailResolution.ToString();
if (v == "rpp") return prefs.resolutionPerPatch.ToString();
if (v == "bmr") return prefs.baseMapResolution.ToString();
if (v == "hmr") return prefs.heightmapResolution.ToString();
if (v == "tp") return prefs.textureProvider.ToString();
if (v == "tw") return prefs.textureSize.x.ToString();
if (v == "th") return prefs.textureSize.y.ToString();
if (v == "tml") return prefs.maxTextureLevel.ToString();
if (v == "ticks") return DateTime.Now.Ticks.ToString();
return v;
}
private string ReplaceTerrainToken(Match match)
{
string v = match.Value.ToLower().Trim('{', '}');
if (v == "tllat") return activeTerrainItem.topLatitude.ToString();
if (v == "tllng") return activeTerrainItem.leftLongitude.ToString();
if (v == "brlat") return activeTerrainItem.bottomLatitude.ToString();
if (v == "brlng") return activeTerrainItem.rightLongitude.ToString();
if (v == "x") return activeTerrainItem.x.ToString();
if (v == "y") return activeTerrainItem.ry.ToString();
return v;
}
public override void Start()
{
string resultFolder = "Assets/RWT_Result";
string resultFullPath = Path.Combine(Application.dataPath, "RWT_Result");
if (!Directory.Exists(resultFullPath)) Directory.CreateDirectory(resultFullPath);
string dateStr = DateTime.Now.ToString("yyyy-MM-dd HH-mm");
resultFolder += "/" + dateStr;
resultFullPath = Path.Combine(resultFullPath, dateStr);
if (!Directory.Exists(resultFullPath)) Directory.CreateDirectory(resultFullPath);
else
{
int index = 1;
while (true)
{
string path = resultFullPath + "_" + index;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
resultFolder += "_" + index;
break;
}
index++;
}
}
const float scaleYCoof = 1112.0f;
const float baseScale = 1000;
double fromX = prefs.coordinatesFrom.x;
double fromY = prefs.coordinatesFrom.y;
double toX = prefs.coordinatesTo.x;
double toY = prefs.coordinatesTo.y;
double rangeX = toX - fromX;
double rangeY = fromY - toY;
RealWorldTerrainVector2i tCount = prefs.terrainCount;
double sizeX = 0;
double sizeZ = 0;
if (prefs.sizeType == 0 || prefs.sizeType == 2)
{
double scfY = Math.Sin(fromY * Mathf.Deg2Rad);
double sctY = Math.Sin(toY * Mathf.Deg2Rad);
double ccfY = Math.Cos(fromY * Mathf.Deg2Rad);
double cctY = Math.Cos(toY * Mathf.Deg2Rad);
double cX = Math.Cos(rangeX * Mathf.Deg2Rad);
double sizeX1 = Math.Abs(RealWorldTerrainUtils.EARTH_RADIUS * Math.Acos(scfY * scfY + ccfY * ccfY * cX));
double sizeX2 = Math.Abs(RealWorldTerrainUtils.EARTH_RADIUS * Math.Acos(sctY * sctY + cctY * cctY * cX));
sizeX = (sizeX1 + sizeX2) / 2.0;
sizeZ = RealWorldTerrainUtils.EARTH_RADIUS * Math.Acos(scfY * sctY + ccfY * cctY);
}
else if (prefs.sizeType == 1)
{
sizeX = Math.Abs(rangeX / 360 * RealWorldTerrainUtils.EQUATOR_LENGTH);
sizeZ = Math.Abs(rangeY / 360 * RealWorldTerrainUtils.EQUATOR_LENGTH);
}
maxElevation = RealWorldTerrainUtils.MAX_ELEVATION;
minElevation = -RealWorldTerrainUtils.MAX_ELEVATION;
double sX = sizeX / tCount.x * baseScale * prefs.terrainScale.x;
double sY;
double sZ = sizeZ / tCount.y * baseScale * prefs.terrainScale.z;
if (prefs.elevationRange == RealWorldTerrainElevationRange.autoDetect)
{
double maxEl, minEl;
RealWorldTerrainElevationGenerator.GetElevationRange(out minEl, out maxEl);
if (prefs.generateUnderWater && prefs.nodataValue != 0 && minEl > prefs.nodataValue) minEl = prefs.nodataValue;
maxElevation = maxEl + prefs.autoDetectElevationOffset.y;
minElevation = minEl - prefs.autoDetectElevationOffset.x;
}
else if (prefs.elevationRange == RealWorldTerrainElevationRange.fixedValue)
{
maxElevation = prefs.fixedMaxElevation;
minElevation = prefs.fixedMinElevation;
}
sY = (maxElevation - minElevation) / scaleYCoof * baseScale * prefs.terrainScale.y;
if (prefs.sizeType == 2)
{
double scaleX = sX / prefs.fixedTerrainSize.x;
double scaleZ = sZ / prefs.fixedTerrainSize.z;
sX = prefs.fixedTerrainSize.x;
sZ = prefs.fixedTerrainSize.z;
sY /= (scaleX + scaleZ) / 2;
}
sX = Math.Round(sX);
sY = Math.Round(sY);
sZ = Math.Round(sZ);
if (sY < 1) sY = 1;
RealWorldTerrainWindow.terrains = new RealWorldTerrainItem[tCount.x, tCount.y];
scale = new Vector3((float)(sX * tCount.x / rangeX), (float)(sY / (maxElevation - minElevation)), (float)(sZ * tCount.y / rangeY));
string baseName = Regex.Replace(RealWorldTerrainPrefs.LoadPref("ResultName", "RealWorld Terrain"), @"{\w+}", ReplaceResultToken);
string containerName = baseName;
if (RealWorldTerrainPrefs.LoadPref("AppendIndex", true))
{
int nameIndex = 0;
while (GameObject.Find("/" + containerName))
{
nameIndex++;
containerName = baseName + " " + nameIndex;
}
}
size = new Vector3((float)sX, (float)sY, (float)sZ);
container = RealWorldTerrainWindow.container = new GameObject(containerName).AddComponent<RealWorldTerrainContainer>();
prefs.Apply(container);
double mx1, my1, mx2, my2;
RealWorldTerrainUtils.LatLongToMercat(fromX, fromY, out mx1, out my1);
RealWorldTerrainUtils.LatLongToMercat(toX, toY, out mx2, out my2);
container.SetCoordinates(mx1, my1, mx2, my2);
container.folder = resultFolder;
container.scale = scale;
container.size = new Vector3(size.x * tCount.x, size.y, size.z * tCount.y);
container.terrainCount = prefs.terrainCount;
container.terrains = new RealWorldTerrainItem[prefs.terrainCount.x * prefs.terrainCount.y];
container.minElevation = minElevation;
container.maxElevation = maxElevation;
container.title = prefs.title;
container.bounds = new Bounds(container.size / 2, container.size);
}
}
} | 44.22549 | 202 | 0.57829 | [
"MIT"
] | zFz0000/UnitySimulasiGerakParabola | Assets/Infinity Code/Real World Terrain/Scripts/Editor/Phases/RealWorldTerrainGenerateTerrainsPhase.cs | 13,533 | C# |
using System;
using System.Data;
using System.Dynamic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#if !NETCOREAPP
using System.Transactions;
#endif
using Mighty.Dynamic.Tests.PostgreSql.TableClasses;
using NUnit.Framework;
namespace Mighty.Dynamic.Tests.PostgreSql
{
/// <summary>
/// Suite of tests for stored procedures, functions and cursors on PostgreSQL database.
/// </summary>
/// <remarks>
/// Runs against functions and procedures which are created by running SPTests.sql script on the test database.
/// These objects do not conflict with anything in the Northwind database, and can be added there.
/// </remarks>
[TestFixture]
public class SPTests
{
[Test]
public void InitialNullIntegerOutputParam()
{
var db = new SPTestsDatabase();
// NB This is PostgreSql specific; Npgsql completely ignores the output parameter type and sets it (sensibly) from the return type.
dynamic z = new ExpandoObject();
z.z = null;
dynamic procResult = db.ExecuteProcedure("find_min", inParams: new { x = 5, y = 3 }, outParams: z);
Assert.AreEqual(typeof(int), procResult.z.GetType());
Assert.AreEqual(3, procResult.z);
}
[Test]
public void IntegerReturnParam()
{
var db = new SPTestsDatabase();
// NB Massive is converting all Postgres return params to output params because Npgsql treats all function
// output and return as output (which is because PostgreSQL itself treats them as the same, really).
dynamic fnResult = db.ExecuteProcedure("find_max", inParams: new { x = 6, y = 7 }, returnParams: new { returnValue = true });
Assert.AreEqual(7, fnResult.returnValue);
}
[Test]
public void PostgresAnonymousParametersA()
{
var db = new SPTestsDatabase();
// Only PostgreSQL supports anonymous parameters (AFAIK) - we treat object[] in the context of params differently from
// how it is treated when it appears in args in the standard Massive API, to provide support for this. (Note, object[]
// makes no sense in the context of named parameters otherwise, and will throw an exception on the other DBs.)
dynamic fnResultAnon = db.ExecuteProcedure("find_max", inParams: new object[] { 12, 7 }, returnParams: new { returnValue = 0 });
Assert.AreEqual(12, fnResultAnon.returnValue);
}
[Test]
public void PostgresAnonymousParametersB()
{
var db = new SPTestsDatabase();
// NB This function can't be called except with anonymous parameters.
// (I believe you can't even do it with a SQL block, because Postgres anonymous SQL blocks do not accept parameters? May be wrong...)
dynamic addResult = db.ExecuteProcedure("add_em", inParams: new object[] { 4, 2 }, returnParams: new { RETURN = 0 });
Assert.AreEqual(6, addResult.RETURN);
}
[Test]
public void InputOutputParam()
{
var db = new SPTestsDatabase();
dynamic squareResult = db.ExecuteProcedure("square_num", ioParams: new { x = 4 });
Assert.AreEqual(16, squareResult.x);
}
[Test]
public void InitialNullInputOutputParam()
{
var db = new SPTestsDatabase();
dynamic xParam = new ExpandoObject();
xParam.x = null;
dynamic squareResult = db.ExecuteProcedure("square_num", ioParams: xParam);
Assert.AreEqual(null, squareResult.x);
}
[Test]
public void InitialNullDateReturnParamMethod1()
{
var db = new SPTestsDatabase();
// This method will work on any provider
dynamic dateResult = db.ExecuteProcedure("get_date", returnParams: new { d = (DateTime?)null });
Assert.AreEqual(typeof(DateTime), dateResult.d.GetType());
}
[Test]
public void InitialNullDateReturnParamMethod2()
{
var db = new SPTestsDatabase();
// NB This is PostgreSql specific; Npgsql completely ignores the output parameter type and sets it (sensibly) from the return type.
dynamic dParam = new ExpandoObject();
dParam.d = null;
dynamic dateResult = db.ExecuteProcedure("get_date", returnParams: dParam);
Assert.AreEqual(typeof(DateTime), dateResult.d.GetType());
}
[Test]
public void InitialNullDateReturnParamMethod3()
{
var db = new SPTestsDatabase();
// Look - it REALLY ignores the parameter type. This would not work on other ADO.NET providers.
// (Look at per-DB method: `private static bool IgnoresOutputTypes(this DbParameter p);`)
dynamic dParam = new ExpandoObject();
dParam.d = false;
dynamic dateResult = db.ExecuteProcedure("get_date", returnParams: dParam);
Assert.AreEqual(typeof(DateTime), dateResult.d.GetType());
}
[Test]
public void DefaultValueFromNullInputOutputParam_Npgsql()
{
var db = new SPTestsDatabase();
// the two lines create a null w param with a no type; on most DB providers this only works
// for input params, where a null is a null is a null, but not on output params, where
// we need to know what type the output var should be; but some providers plain ignore
// the output type - in which case we do not insist that the user provide one
dynamic wArgs = new ExpandoObject();
wArgs.w = null;
// w := w + 2; v := w - 1; x := w + 1
dynamic testResult = db.ExecuteProcedure("test_vars", ioParams: wArgs, outParams: new { v = 0, x = 0 });
Assert.AreEqual(1, testResult.v);
Assert.AreEqual(2, testResult.w);
Assert.AreEqual(3, testResult.x);
}
[Test]
public void DefaultValueFromNullInputOutputParam_CrossDb()
{
// This is the cross-DB compatible way to do it.
var db = new SPTestsDatabase();
// w := w + 2; v := w - 1; x := w + 1
dynamic testResult = db.ExecuteProcedure("test_vars", ioParams: new { w = (int?)null }, outParams: new { v = 0, x = 0 });
Assert.AreEqual(1, testResult.v);
Assert.AreEqual(2, testResult.w);
Assert.AreEqual(3, testResult.x);
}
[Test]
public void ProvideValueToInputOutputParam()
{
var db = new SPTestsDatabase();
// w := w + 2; v := w - 1; x := w + 1
dynamic testResult = db.ExecuteProcedure("test_vars", ioParams: new { w = 2 }, outParams: new { v = 0, x = 0 });
Assert.AreEqual(3, testResult.v);
Assert.AreEqual(4, testResult.w);
Assert.AreEqual(5, testResult.x);
}
[Test]
public void ReadOutputParamsUsingQuery()
{
var db = new SPTestsDatabase();
// Again this is Postgres specific: output params are really part of data row and can be read that way
var record = db.SingleFromProcedure("test_vars", new { w = 2 });
Assert.AreEqual(3, record.v);
Assert.AreEqual(4, record.w);
Assert.AreEqual(5, record.x);
}
[Test]
public void QuerySetOfRecordsFromFunction()
{
var db = new SPTestsDatabase();
var setOfRecords = db.QueryFromProcedure("sum_n_product_with_tab", new { x = 10 });
int count = 0;
foreach(var innerRecord in setOfRecords)
{
Console.WriteLine(innerRecord.sum + "\t|\t" + innerRecord.product);
count++;
}
Assert.AreEqual(4, count);
}
#region Dereferencing tests
[Test]
public void DereferenceCursorOutputParameter()
{
var db = new SPTestsDatabase();
// Unlike the Oracle data access layer, Npgsql v3 does not dereference cursor parameters.
// We have added back the support for this which was previously in Npgsql v2.
var employees = db.QueryFromProcedure("cursor_employees", outParams: new { refcursor = new Cursor() });
int count = 0;
foreach(var employee in employees)
{
Console.WriteLine(employee.firstname + " " + employee.lastname);
count++;
}
Assert.AreEqual(9, count);
}
#if !NETCOREAPP
[Test]
public void DereferenceFromQuery_ManualWrapping()
{
var db = new SPTestsDatabase();
// without a cursor param, nothing will trigger the wrapping transaction support in Massive
// so in this case we need to add the wrapping transaction manually (with TransactionScope or
// BeginTransaction, see other examples in this file)
int count = 0;
using(var scope = new TransactionScope())
{
var employees = db.Query("SELECT * FROM cursor_employees()");
foreach(var employee in employees)
{
Console.WriteLine(employee.firstname + " " + employee.lastname);
count++;
}
scope.Complete();
}
Assert.AreEqual(9, count);
}
#endif
[Test]
public void DereferenceFromQuery_AutoWrapping()
{
var db = new SPTestsDatabase();
// use dummy cursor to trigger wrapping transaction support in Massive
var employees = db.QueryWithParams("SELECT * FROM cursor_employees()", outParams: new { abc = new Cursor() });
int count = 0;
foreach(var employee in employees)
{
Console.WriteLine(employee.firstname + " " + employee.lastname);
count++;
}
Assert.AreEqual(9, count);
}
// Test various dereferencing patters (more relevant since we are coding this ourselves)
private void CheckMultiResultSetStructure(IEnumerable<IEnumerable<dynamic>> results, int count0 = 1, int count1 = 1, bool breakTest = false, bool idTest = false)
{
int sets = 0;
int[] counts = new int[2];
foreach(var set in results)
{
foreach(var item in set)
{
counts[sets]++;
if (idTest) Assert.AreEqual(typeof(int), item.id.GetType());
else if (sets == 0) Assert.AreEqual(typeof(int), item.a.GetType());
else Assert.AreEqual(typeof(int), item.c.GetType());
if(breakTest) break;
}
sets++;
}
Assert.AreEqual(2, sets);
Assert.AreEqual(breakTest ? 1 : count0, counts[0]);
Assert.AreEqual(breakTest ? 1 : count1, counts[1]);
}
[Test]
public void DereferenceOneByNFromProcedure()
{
var db = new SPTestsDatabase();
var resultSetOneByN = db.QueryMultipleFromProcedure("cursorOneByN", outParams: new { xyz = new Cursor() });
CheckMultiResultSetStructure(resultSetOneByN);
}
[Test]
public void DereferenceNByOneFromProcedure()
{
var db = new SPTestsDatabase();
// For small result sets, this actually saves one round trip to the database
//db.AutoDereferenceFetchSize = -1;
var resultSetNByOne = db.QueryMultipleFromProcedure("cursorNByOne", outParams: new { c1 = new Cursor(), c2 = new Cursor() });
CheckMultiResultSetStructure(resultSetNByOne);
}
[Test]
public void DereferenceOneByNFromQuery()
{
var db = new SPTestsDatabase();
var resultSetOneByNSQL = db.QueryMultipleWithParams("SELECT * FROM cursorOneByN()",
outParams: new { anyname = new Cursor() });
CheckMultiResultSetStructure(resultSetOneByNSQL);
}
[Test]
public void DereferenceNByOneFromQuery()
{
var db = new SPTestsDatabase();
var resultSetNByOneSQL = db.QueryMultipleWithParams("SELECT * FROM cursorNByOne()",
outParams: new { anyname = new Cursor() });
CheckMultiResultSetStructure(resultSetNByOneSQL);
}
[Test]
public void QueryMultipleWithBreaks()
{
var db = new SPTestsDatabase();
var resultCTestFull = db.QueryMultipleFromProcedure("cbreaktest", outParams: new { c1 = new Cursor(), c2 = new Cursor() });
CheckMultiResultSetStructure(resultCTestFull, 10, 11);
var resultCTestToBreak = db.QueryMultipleFromProcedure("cbreaktest", ioParams: new { c1 = new Cursor(), c2 = new Cursor() });
CheckMultiResultSetStructure(resultCTestToBreak, breakTest: true);
}
#endregion
[Test]
public void QueryFromMixedCursorOutput()
{
var db = new SPTestsDatabase();
// Following the Oracle pattern this WILL dereference; so we need some more interesting result sets in there now.
var firstItemCursorMix = db.SingleFromProcedure("cursor_mix", outParams: new { anyname = new Cursor(), othername = 0 });
Assert.AreEqual(11, firstItemCursorMix.a);
Assert.AreEqual(22, firstItemCursorMix.b);
}
[Test]
public void NonQueryFromMixedCursorOutput()
{
var db = new SPTestsDatabase();
// Following the Oracle pattern this will not dereference: we get a variable value and a cursor ref.
var itemCursorMix = db.ExecuteProcedure("cursor_mix", outParams: new { anyname = new Cursor(), othername = 0 });
Assert.AreEqual(42, itemCursorMix.othername);
Assert.AreEqual(typeof(Cursor), itemCursorMix.anyname.GetType());
Assert.AreEqual(typeof(string), ((Cursor)itemCursorMix.anyname).CursorRef.GetType()); // NB PostgreSql ref cursors return as string
}
[Test]
[TestCase(false)]
[TestCase(true)]
public void InputCursors_BeginTransaction(bool explicitConnection)
{
var db = new SPTestsDatabase(explicitConnection);
if (explicitConnection)
{
MightyTests.ConnectionStringUtils.CheckConnectionStringRequiredForOpenConnection(db);
}
using (var conn = db.OpenConnection(
explicitConnection ?
MightyTests.ConnectionStringUtils.GetConnectionString(TestConstants.ReadWriteTestConnection, TestConstants.ProviderName) :
null
))
{
// cursors in PostgreSQL must share a transaction (not just a connection, as in Oracle)
using(var trans = conn.BeginTransaction())
{
var cursors = db.ExecuteProcedure("cursorNByOne", outParams: new { c1 = new Cursor(), c2 = new Cursor() }, connection: conn);
var cursor1 = db.QueryFromProcedure("fetch_next_ints_from_cursor", new { mycursor = cursors.c1 }, connection: conn);
int count1 = 0;
foreach(var item in cursor1)
{
Assert.AreEqual(11, item.myint1);
Assert.AreEqual(22, item.myint2);
count1++;
}
Assert.AreEqual(1, count1);
var cursor2 = db.QueryFromProcedure("fetch_next_ints_from_cursor", new { mycursor = cursors.c2 }, connection: conn);
int count2 = 0;
foreach(var item in cursor2)
{
Assert.AreEqual(33, item.myint1);
Assert.AreEqual(44, item.myint2);
count2++;
}
Assert.AreEqual(1, count2);
trans.Commit();
}
}
}
#if !NETCOREAPP
[Test]
public void InputCursors_TransactionScope()
{
var db = new SPTestsDatabase();
// cursors in PostgreSQL must share a transaction (not just a connection, as in Oracle)
// to use TransactionScope with Npgsql, the connection string must include "Enlist=true;"
using(var scope = new TransactionScope())
{
var cursors = db.ExecuteProcedure("cursorNByOne", outParams: new { c1 = new Cursor(), c2 = new Cursor() });
var cursor1 = db.QueryFromProcedure("fetch_next_ints_from_cursor", new { mycursor = cursors.c1 });
int count1 = 0;
foreach(var item in cursor1)
{
Assert.AreEqual(11, item.myint1);
Assert.AreEqual(22, item.myint2);
count1++;
}
Assert.AreEqual(1, count1);
var cursor2 = db.QueryFromProcedure("fetch_next_ints_from_cursor", new { mycursor = cursors.c2 });
int count2 = 0;
foreach(var item in cursor2)
{
Assert.AreEqual(33, item.myint1);
Assert.AreEqual(44, item.myint2);
count2++;
}
Assert.AreEqual(1, count2);
scope.Complete();
}
}
/// <summary>
/// For NX1 cursors as above Execute can get the raw cursors.
/// For 1XN as here we have to use Query with automatic dereferencing turned off.
/// </summary>
[Test]
public void InputCursors_1XN()
{
var db = new SPTestsDatabase();
db.NpgsqlAutoDereferenceCursors = false; // for this instance only
// cursors in PostgreSQL must share a transaction (not just a connection, as in Oracle)
// to use TransactionScope with Npgsql, the connection string must include "Enlist=true;"
using(var scope = new TransactionScope())
{
// Including a cursor param is optional and makes no difference, because Npgsql/PostgreSQL is lax about such things
// and we don't need to hint to Massive to do anything special
var cursors = db.QueryFromProcedure("cursorOneByN"); //, outParams: new { abcdef = new Cursor() });
string[] cursor = new string[2];
int i = 0;
foreach(var item in cursors)
{
cursor[i++] = item.cursoronebyn;
}
Assert.AreEqual(2, i);
var cursor1 = db.QueryFromProcedure("fetch_next_ints_from_cursor", new { mycursor = new Cursor(cursor[0]) });
int count1 = 0;
foreach(var item in cursor1)
{
Assert.AreEqual(1, item.myint1);
Assert.AreEqual(2, item.myint2);
count1++;
}
Assert.AreEqual(1, count1);
var cursor2 = db.QueryFromProcedure("fetch_next_ints_from_cursor", new { mycursor = new Cursor(cursor[1]) });
int count2 = 0;
foreach(var item in cursor2)
{
Assert.AreEqual(3, item.myint1);
Assert.AreEqual(4, item.myint2);
count2++;
}
Assert.AreEqual(1, count2);
scope.Complete();
}
}
#endif
// Temporarily commenting out large cursor tests
#if true
readonly int LargeCursorSize = 1000000;
/// <summary>
/// Explicit dereferencing is more fiddly to do, but you still have the choice to do it (even when automatic dereferencing is on).
/// </summary>
[Test]
public void LargeCursor_ExplicitFetch()
{
int FetchSize = 20000;
int count = 0;
int batchCount = 0;
var db = new SPTestsDatabase();
using(var conn = db.OpenConnection())
{
// cursors in PostgreSQL must share a transaction (not just a connection, as in Oracle)
using(var trans = conn.BeginTransaction())
{
var result = db.ExecuteProcedure("lump", returnParams: new { cursor = new Cursor() }, connection: conn);
while(true)
{
var fetchTest = db.Query($@"FETCH {FetchSize} FROM ""{result.cursor.CursorRef}""", connection: conn);
int subcount = 0;
foreach(var item in fetchTest)
{
count++;
subcount++;
// there is no ORDER BY (it would not be sensible on such a huge data set) - this only sometimes works...
//Assert.AreEqual(count, item.id);
}
if(subcount == 0)
{
break;
}
batchCount++;
}
db.Execute($@"CLOSE ""{result.cursor.CursorRef}""", connection: conn);
trans.Commit();
}
}
Assert.AreEqual((LargeCursorSize + FetchSize - 1) / FetchSize, batchCount);
Assert.AreEqual(LargeCursorSize, count);
}
/// <remarks>
/// Implicit dereferencing is much easier to do, but also safe even for large or huge cursors.
/// PostgreSQL specific settings; the following are the defaults which should work fine for most situations:
/// db.AutoDereferenceCursors = true;
/// db.AutoDereferenceFetchSize = 10000;
/// </remarks>
[Test]
public void LargeCursor_AutomaticDereferencing()
{
var db = new SPTestsDatabase();
// Either of these will show big server-side buffers in PostrgeSQL logs (but will still pass)
//db.AutoDereferenceFetchSize = -1; // FETCH ALL
//db.AutoDereferenceFetchSize = 400000;
var fetchTest = db.QueryFromProcedure("lump", returnParams: new { cursor = new Cursor() });
int count = 0;
foreach(var item in fetchTest)
{
count++;
// there is no ORDER BY (it would not be sensible on such a huge data set) - this only sometimes works...
//Assert.AreEqual(count, item.id);
}
Assert.AreEqual(LargeCursorSize, count);
}
[Test]
public void LargeCursorX2_AutomaticDereferencing()
{
var db = new SPTestsDatabase();
// Either of these will show big server-side buffers in PostrgeSQL logs (but will still pass)
//db.AutoDereferenceFetchSize = -1; // FETCH ALL
//db.AutoDereferenceFetchSize = 400000;
var results = db.QueryMultipleFromProcedure("lump2", returnParams: new { cursor = new Cursor() });
int rcount = 0;
foreach (var result in results)
{
rcount++;
int count = 0;
foreach(var item in result)
{
count++;
// there is no ORDER BY (it would not be sensible on such a huge data set) - this only sometimes works...
//Assert.AreEqual(count, item.id);
}
Assert.AreEqual(LargeCursorSize, count);
}
Assert.AreEqual(2, rcount);
}
#endif
#if false
[Test]
public void HugeCursorTest()
{
var db = new SPTestsDatabase();
//// Huge cursor tests....
var config = db.SingleFromQuery("SELECT current_setting('work_mem') work_mem, current_setting('log_temp_files') log_temp_files");
//// huge data from SELECT *
//var resultLargeSelectTest = db.QueryWithParams("SELECT * FROM large");
//foreach(var item in resultLargeSelectTest)
//{
// int a = 1;
//}
//// huge data from (implicit) FETCH ALL
//// AUTO-DEREFERENCE TWO HUGE, ONLY FETCH FROM ONE
//var resultLargeProcTest = db.QueryFromProcedure("lump2", returnParams: new { abc = new Cursor() });
//foreach (var item in resultLargeProcTest)
//{
// Console.WriteLine(item.id);
// break;
//}
var results = db.QueryMultipleFromProcedure("lump2", returnParams: new { abc = new Cursor() });
db.NpgsqlAutoDereferenceFetchSize = 4000000;
CheckMultiResultSetStructure(results, 10000000, 10000000, true, true);
// one item from cursor
//using (var conn = db.OpenConnection())
//{
// using (var trans = conn.BeginTransaction())
// {
// var result = db.ExecuteAsProcedure("lump2", returnParams: new { abc = new Cursor(), def = new Cursor() }, connection: conn);
// var singleItemTest = db.QueryWithParams($@"FETCH 5000000 FROM ""{result.abc}"";", connection: conn);
// foreach (var item in singleItemTest)
// {
// Console.WriteLine(item.id);
// break;
// }
// NB plain Execute() did NOT take a connection, and changing this MIGHT be an API breaking change??? TEST...!
// (This is the first, and so far only, really unwanted side effect of trying to stay 100% non-breaking.)
// db.Execute($@"CLOSE ""{result.abc}"";", conn);
// trans.Commit();
// }
//}
}
#endif
// TO DO:
#if false
public void ToDo()
{
var db = new SPTestsDatabase();
// AFAIK these will never work (you can't assign to vars in SQL block)
//dynamic intResult = db.Execute(":a := 1", inParams: new aArgs());
//dynamic dateResult = db.Execute("begin :d := SYSDATE; end;", outParams: new myParamsD());
}
#endif
}
}
| 44.157635 | 169 | 0.55113 | [
"BSD-3-Clause"
] | MightyORM/MightyORM | tests/Dynamic/PostgreSql/SPTests.cs | 26,894 | 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.Monitoring.V3.Snippets
{
// [START monitoring_v3_generated_ServiceMonitoringService_UpdateService_async]
using Google.Cloud.Monitoring.V3;
using Google.Protobuf.WellKnownTypes;
using System.Threading.Tasks;
public sealed partial class GeneratedServiceMonitoringServiceClientSnippets
{
/// <summary>Snippet for UpdateServiceAsync</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 UpdateServiceRequestObjectAsync()
{
// Create client
ServiceMonitoringServiceClient serviceMonitoringServiceClient = await ServiceMonitoringServiceClient.CreateAsync();
// Initialize request argument(s)
UpdateServiceRequest request = new UpdateServiceRequest
{
Service = new Service(),
UpdateMask = new FieldMask(),
};
// Make the request
Service response = await serviceMonitoringServiceClient.UpdateServiceAsync(request);
}
}
// [END monitoring_v3_generated_ServiceMonitoringService_UpdateService_async]
}
| 40.595745 | 127 | 0.70283 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.Monitoring.V3/Google.Cloud.Monitoring.V3.GeneratedSnippets/ServiceMonitoringServiceClient.UpdateServiceRequestObjectAsyncSnippet.g.cs | 1,908 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SnakeGenetic")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SnakeGenetic")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[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("311E720D-6D35-4580-BE68-54E77BEE65C3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | 38.771429 | 84 | 0.742078 | [
"MIT"
] | Neralion/SnakeBattle | SnakeGenetic/Properties/AssemblyInfo.cs | 1,360 | C# |
using dueltank.core.Models.Db;
using dueltank.Domain.Repository;
using dueltank.Domain.Service;
using NSubstitute;
using NUnit.Framework;
using System.Threading.Tasks;
using dueltank.core.Models.Cards;
using dueltank.core.Models.Search.Cards;
using dueltank.tests.core;
namespace dueltank.domain.unit.tests.ServiceTests
{
[TestFixture]
[Category(TestType.Unit)]
public class CardServiceTests
{
CardService _sut;
private ICardRepository _cardRepository;
[SetUp]
public void SetUp()
{
_cardRepository = Substitute.For<ICardRepository>();
_sut = new CardService(_cardRepository);
}
[Test]
public async Task Should_Invoke_GetCardByNumber_Once()
{
// Arrange
const int cardNumber = 32525523;
_cardRepository.GetCardByNumber(Arg.Any<long>()).Returns(new Card());
// Act
await _sut.GetCardByNumber(cardNumber);
// Assert
await _cardRepository.Received(1).GetCardByNumber(cardNumber);
}
[Test]
public async Task Should_Invoke_GetCardByName_Once()
{
// Arrange
const string cardNumber = "Call Of The Haunted";
_cardRepository.GetCardByName(Arg.Any<string>()).Returns(new CardSearch());
// Act
await _sut.GetCardByName(cardNumber);
// Assert
await _cardRepository.Received(1).GetCardByName(cardNumber);
}
[Test]
public async Task Should_Invoke_Search_Once()
{
// Arrange
var cardSearchCriteria = new CardSearchCriteria();
_cardRepository.Search(Arg.Any<CardSearchCriteria>()).Returns(new CardSearchResult());
// Act
await _sut.Search(cardSearchCriteria);
// Assert
await _cardRepository.Received(1).Search(Arg.Any<CardSearchCriteria>());
}
}
} | 27.611111 | 98 | 0.615694 | [
"MIT"
] | fablecode/dueltank | src/Api/src/Tests/Unit/dueltank.domain.unit.tests/ServiceTests/CardServiceTests.cs | 1,990 | C# |
using System;
namespace AwesomeCharts {
public class XAxisBarChartFormatter : IValueFormatter {
public string FormatAxisValue(float value, float min, float max) {
return value.ToString();
}
}
}
| 19.5 | 74 | 0.653846 | [
"Apache-2.0"
] | serranda/SecuritySeriousGame | SIMSCADA/Assets/ImportedAssets/Awesome Charts/Core/Scripts/UI/XAxisBarChartValueFormatter.cs | 236 | C# |
using FluentAssertions;
using NUnit.Framework;
using TestApi.Common.Builders;
using TestApi.Common.Data;
using TestApi.Domain;
using TestApi.Contract.Enums;
using TestApi.Mappings;
namespace TestApi.UnitTests.Mappings
{
public class AllocationToDetailsResponseMapperTests
{
[Test]
public void Should_map_all_properties()
{
var user = new UserBuilder(EmailData.FAKE_EMAIL_STEM, 1)
.WithUserType(UserType.Individual)
.ForApplication(Application.TestApi)
.BuildUser();
var allocation = new Allocation(user);
var response = AllocationToDetailsResponseMapper.MapToResponse(allocation);
response.Should().BeEquivalentTo(allocation, options => options.Excluding(x => x.User));
}
}
} | 30.333333 | 100 | 0.675214 | [
"MIT"
] | hmcts/vh-test-api | TestApi/TestApi.UnitTests/Mappings/AllocationToDetailsResponseMapperTests.cs | 821 | C# |
namespace Microsoft.Maui.Controls.Compatibility.ControlGallery.GalleryPages.CollectionViewGalleries
{
internal class TemplateCodeCollectionViewGridGallery : ContentPage
{
public TemplateCodeCollectionViewGridGallery(ItemsLayoutOrientation orientation = ItemsLayoutOrientation.Vertical)
{
var layout = new Grid
{
RowDefinitions = new RowDefinitionCollection
{
new RowDefinition { Height = GridLength.Auto },
new RowDefinition { Height = GridLength.Auto },
new RowDefinition { Height = GridLength.Star }
}
};
var itemsLayout = new GridItemsLayout(2, orientation);
var itemTemplate = ExampleTemplates.PhotoTemplate();
var collectionView = new CollectionView { ItemsLayout = itemsLayout, ItemTemplate = itemTemplate, AutomationId = "collectionview" };
var generator = new ItemsSourceGenerator(collectionView, 100);
var spanSetter = new SpanSetter(collectionView);
layout.Children.Add(generator);
layout.Children.Add(spanSetter);
Grid.SetRow(spanSetter, 1);
layout.Children.Add(collectionView);
Grid.SetRow(collectionView, 2);
Content = layout;
spanSetter.UpdateSpan();
generator.GenerateItems();
}
}
} | 31.289474 | 135 | 0.751892 | [
"MIT"
] | 10088/maui | src/Compatibility/ControlGallery/src/Core/GalleryPages/CollectionViewGalleries/TemplateCodeCollectionViewGridGallery.cs | 1,191 | C# |
/// <license>
/// This file is part of Ordisoftware Core Library.
/// Copyright 2004-2021 Olivier Rogier.
/// See www.ordisoftware.com for more information.
/// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
/// If a copy of the MPL was not distributed with this file, You can obtain one at
/// https://mozilla.org/MPL/2.0/.
/// If it is not possible or desirable to put the notice in a particular file,
/// then You may include the notice in a location(such as a LICENSE file in a
/// relevant directory) where a recipient would be likely to look for such a notice.
/// You may add additional accurate notices of copyright ownership.
/// </license>
/// <created> 2020-08 </created>
/// <edited> 2020-08 </edited>
using System;
using System.Collections.Generic;
namespace Ordisoftware.Core
{
/// <summary>
/// Provide null safe string list.
/// </summary>
[Serializable]
public class NullSafeStringList : List<string>
{
public NullSafeStringList()
{
}
public NullSafeStringList(int capacity) : base(capacity)
{
}
public NullSafeStringList(IEnumerable<string> collection) : base(collection)
{
}
public new string this[int index]
{
get
{
CheckIndex(index);
return index < Count ? base[index] : null;
}
set
{
CheckIndex(index);
if ( index < Count )
base[index] = value;
else
CreateOutOfRange(index, value);
}
}
private void CheckIndex(int index)
{
if ( index >= 0 ) return;
throw new IndexOutOfRangeException(SysTranslations.IndexCantBeNegative.GetLang(nameof(NullSafeStringList), index));
}
private void CreateOutOfRange(int index, string value)
{
Capacity = index + 1;
int count = index + 1 - Count;
for ( int i = 0; i < count; i++ )
Add(null);
base[index] = value;
}
}
}
| 25.986667 | 121 | 0.636737 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Ordisoftware/Hebrew-Calendar | Project/Source/Common/Core/Collections/NullSafeStringList.cs | 1,951 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Build.Shared;
using Shouldly;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.Build.Shared.FileSystem;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Build.UnitTests
{
public class FileMatcherTest : IDisposable
{
private readonly TestEnvironment _env;
public FileMatcherTest(ITestOutputHelper output)
{
_env = TestEnvironment.Create(output);
}
public void Dispose()
{
_env.Dispose();
}
[Theory]
[InlineData("*.txt", 5)]
[InlineData("???.cs", 1)]
[InlineData("????.cs", 1)]
[InlineData("file?.txt", 1)]
[InlineData("fi?e?.txt", 2)]
[InlineData("???.*", 1)]
[InlineData("????.*", 4)]
[InlineData("*.???", 5)]
[InlineData("f??e1.txt", 2)]
[InlineData("file.*.txt", 1)]
public void GetFilesPatternMatching(string pattern, int expectedMatchCount)
{
TransientTestFolder testFolder = _env.CreateFolder();
foreach (var file in new[]
{
"Foo.cs",
"Foo2.cs",
"file.txt",
"file1.txt",
"file1.txtother",
"fie1.txt",
"fire1.txt",
"file.bak.txt"
})
{
File.WriteAllBytes(Path.Combine(testFolder.Path, file), new byte[1]);
}
string[] fileMatches = FileMatcher.Default.GetFiles(testFolder.Path, pattern);
fileMatches.Length.ShouldBe(expectedMatchCount, $"Matches: '{String.Join("', '", fileMatches)}'");
}
[Theory]
[MemberData(nameof(GetFilesComplexGlobbingMatchingInfo.GetTestData), MemberType = typeof(GetFilesComplexGlobbingMatchingInfo))]
public void GetFilesComplexGlobbingMatching(GetFilesComplexGlobbingMatchingInfo info)
{
TransientTestFolder testFolder = _env.CreateFolder();
// Create directories and files
foreach (string fullPath in GetFilesComplexGlobbingMatchingInfo.FilesToCreate.Select(i => Path.Combine(testFolder.Path, i.ToPlatformSlash())))
{
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
File.WriteAllBytes(fullPath, new byte[1]);
}
void Verify(string include, string[] excludes, bool shouldHaveNoMatches = false, string customMessage = null)
{
string[] matchedFiles = FileMatcher.Default.GetFiles(testFolder.Path, include, excludes?.ToList());
if (shouldHaveNoMatches)
{
matchedFiles.ShouldBeEmpty(customMessage);
}
else
{
// The matches are:
// 1. Normalized ("\" regardless of OS and lowercase)
// 2. Sorted
// Are the same as the expected matches sorted
matchedFiles
.Select(i => i.Replace(Path.DirectorySeparatorChar, '\\'))
.OrderBy(i => i)
.ToArray()
.ShouldBe(info.ExpectedMatches.OrderBy(i => i), caseSensitivity: Case.Insensitive, customMessage: customMessage);
}
}
// Normal matching
Verify(info.Include, info.Excludes);
// Include forward slash
Verify(info.Include.Replace('\\', '/'), info.Excludes, customMessage: "Include directory separator was changed to forward slash");
// Excludes forward slash
Verify(info.Include, info.Excludes?.Select(o => o.Replace('\\', '/')).ToArray(), customMessage: "Excludes directory separator was changed to forward slash");
// Uppercase includes
Verify(info.Include.ToUpperInvariant(), info.Excludes, info.ExpectNoMatches, "Include was changed to uppercase");
// Changing the case of the exclude break Linux
if (!NativeMethodsShared.IsLinux)
{
// Uppercase excludes
Verify(info.Include, info.Excludes?.Select(o => o.ToUpperInvariant()).ToArray(), false, "Excludes were changed to uppercase");
}
// Backward compatibilities:
// 1. When an include or exclude starts with a fixed directory part e.g. "src/foo/**",
// then matching should be case-sensitive on Linux, as the directory was checked for its existance
// by using Directory.Exists, which is case-sensitive on Linux (on OSX is not).
// 2. On Unix, when an include uses a simple ** wildcard e.g. "**\*.cs", the file pattern e.g. "*.cs",
// should be matched case-sensitive, as files were retrieved by using the searchPattern parameter
// of Directory.GetFiles, which is case-sensitive on Unix.
}
/// <summary>
/// A test data class for providing data to the <see cref="FileMatcherTest.GetFilesComplexGlobbingMatching"/> test.
/// </summary>
public class GetFilesComplexGlobbingMatchingInfo
{
/// <summary>
/// The list of known files to create.
/// </summary>
public static string[] FilesToCreate =
{
@"src\foo.cs",
@"src\bar.cs",
@"src\baz.cs",
@"src\foo\foo.cs",
@"src\bar\bar.cs",
@"src\baz\baz.cs",
@"src\foo\inner\foo.cs",
@"src\foo\inner\foo\foo.cs",
@"src\foo\inner\bar\bar.cs",
@"src\bar\inner\baz.cs",
@"src\bar\inner\baz\baz.cs",
@"src\bar\inner\foo\foo.cs",
@"build\baz\foo.cs",
@"readme.txt",
@"licence.md"
};
/// <summary>
/// Gets or sets the include pattern.
/// </summary>
public string Include { get; set; }
/// <summary>
/// Gets or sets a list of exclude patterns.
/// </summary>
public string[] Excludes { get; set; }
/// <summary>
/// Gets or sets the list of expected matches.
/// </summary>
public string[] ExpectedMatches { get; set; }
/// <summary>
/// Get or sets a value indicating to expect no matches if the include pattern is mutated to uppercase.
/// </summary>
public bool ExpectNoMatches { get; set; }
public override string ToString()
{
IEnumerable<string> GetParts()
{
yield return $"Include = {Include}";
if (Excludes != null)
{
yield return $"Excludes = {String.Join(";", Excludes)}";
}
if (ExpectNoMatches)
{
yield return "ExpectNoMatches";
}
}
return String.Join(", ", GetParts());
}
/// <summary>
/// Gets the test data
/// </summary>
public static IEnumerable<object> GetTestData()
{
yield return new object[]
{
new GetFilesComplexGlobbingMatchingInfo
{
Include = @"src\**\inner\**\*.cs",
ExpectedMatches = new[]
{
@"src\foo\inner\foo.cs",
@"src\foo\inner\foo\foo.cs",
@"src\foo\inner\bar\bar.cs",
@"src\bar\inner\baz.cs",
@"src\bar\inner\baz\baz.cs",
@"src\bar\inner\foo\foo.cs"
},
ExpectNoMatches = NativeMethodsShared.IsLinux
}
};
yield return new object[]
{
new GetFilesComplexGlobbingMatchingInfo
{
Include = @"src\**\inner\**\*.cs",
Excludes = new[]
{
@"src\foo\inner\foo.*.cs"
},
ExpectedMatches = new[]
{
@"src\foo\inner\foo.cs",
@"src\foo\inner\foo\foo.cs",
@"src\foo\inner\bar\bar.cs",
@"src\bar\inner\baz.cs",
@"src\bar\inner\baz\baz.cs",
@"src\bar\inner\foo\foo.cs"
},
ExpectNoMatches = NativeMethodsShared.IsLinux,
}
};
yield return new object[]
{
new GetFilesComplexGlobbingMatchingInfo
{
Include = @"src\**\inner\**\*.cs",
Excludes = new[]
{
@"**\foo\**"
},
ExpectedMatches = new[]
{
@"src\bar\inner\baz.cs",
@"src\bar\inner\baz\baz.cs"
},
ExpectNoMatches = NativeMethodsShared.IsLinux,
}
};
yield return new object[]
{
new GetFilesComplexGlobbingMatchingInfo
{
Include = @"src\**\inner\**\*.cs",
Excludes = new[]
{
@"src\bar\inner\baz\**"
},
ExpectedMatches = new[]
{
@"src\foo\inner\foo.cs",
@"src\foo\inner\foo\foo.cs",
@"src\foo\inner\bar\bar.cs",
@"src\bar\inner\baz.cs",
@"src\bar\inner\foo\foo.cs"
},
ExpectNoMatches = NativeMethodsShared.IsLinux,
}
};
#if !MONO // https://github.com/mono/mono/issues/8441
yield return new object[]
{
new GetFilesComplexGlobbingMatchingInfo
{
Include = @"src\foo\**\*.cs",
Excludes = new[]
{
@"src\foo\**\foo\**"
},
ExpectedMatches = new[]
{
@"src\foo\foo.cs",
@"src\foo\inner\foo.cs",
@"src\foo\inner\bar\bar.cs"
},
ExpectNoMatches = NativeMethodsShared.IsLinux,
}
};
yield return new object[]
{
new GetFilesComplexGlobbingMatchingInfo
{
Include = @"src\foo\inner\**\*.cs",
Excludes = new[]
{
@"src\foo\**\???\**"
},
ExpectedMatches = new[]
{
@"src\foo\inner\foo.cs"
},
ExpectNoMatches = NativeMethodsShared.IsLinux,
}
};
#endif
yield return new object[]
{
new GetFilesComplexGlobbingMatchingInfo
{
Include = @"**\???\**\*.cs",
ExpectedMatches = new[]
{
@"src\foo.cs",
@"src\bar.cs",
@"src\baz.cs",
@"src\foo\foo.cs",
@"src\bar\bar.cs",
@"src\baz\baz.cs",
@"src\foo\inner\foo.cs",
@"src\foo\inner\foo\foo.cs",
@"src\foo\inner\bar\bar.cs",
@"src\bar\inner\baz.cs",
@"src\bar\inner\baz\baz.cs",
@"src\bar\inner\foo\foo.cs",
@"build\baz\foo.cs"
}
}
};
yield return new object[]
{
new GetFilesComplexGlobbingMatchingInfo
{
Include = @"**\*.*",
Excludes = new[]
{
@"**\???\**\*.cs"
},
ExpectedMatches = new[]
{
@"readme.txt",
@"licence.md"
}
}
};
yield return new object[]
{
new GetFilesComplexGlobbingMatchingInfo
{
Include = @"**\?a?\**\?a?\*.c?",
ExpectedMatches = new[]
{
@"src\bar\inner\baz\baz.cs"
}
}
};
yield return new object[]
{
new GetFilesComplexGlobbingMatchingInfo
{
Include = @"**\?a?\**\?a?.c?",
Excludes = new[]
{
@"**\?a?\**\?a?\*.c?"
},
ExpectedMatches = new[]
{
@"src\bar\bar.cs",
@"src\baz\baz.cs",
@"src\foo\inner\bar\bar.cs",
@"src\bar\inner\baz.cs"
}
}
};
}
}
[Fact]
public void WildcardMatching()
{
var inputs = new List<Tuple<string, string, bool>>
{
// No wildcards
new Tuple<string, string, bool>("a", "a", true),
new Tuple<string, string, bool>("a", "", false),
new Tuple<string, string, bool>("", "a", false),
// Non ASCII characters
new Tuple<string, string, bool>("šđčćž", "šđčćž", true),
// * wildcard
new Tuple<string, string, bool>("abc", "*bc", true),
new Tuple<string, string, bool>("abc", "a*c", true),
new Tuple<string, string, bool>("abc", "ab*", true),
new Tuple<string, string, bool>("ab", "*ab", true),
new Tuple<string, string, bool>("ab", "a*b", true),
new Tuple<string, string, bool>("ab", "ab*", true),
new Tuple<string, string, bool>("aba", "ab*ba", false),
new Tuple<string, string, bool>("", "*", true),
// ? wildcard
new Tuple<string, string, bool>("abc", "?bc", true),
new Tuple<string, string, bool>("abc", "a?c", true),
new Tuple<string, string, bool>("abc", "ab?", true),
new Tuple<string, string, bool>("ab", "?ab", false),
new Tuple<string, string, bool>("ab", "a?b", false),
new Tuple<string, string, bool>("ab", "ab?", false),
new Tuple<string, string, bool>("", "?", false),
// Mixed wildcards
new Tuple<string, string, bool>("a", "*?", true),
new Tuple<string, string, bool>("a", "?*", true),
new Tuple<string, string, bool>("ab", "*?", true),
new Tuple<string, string, bool>("ab", "?*", true),
new Tuple<string, string, bool>("abc", "*?", true),
new Tuple<string, string, bool>("abc", "?*", true),
// Multiple mixed wildcards
new Tuple<string, string, bool>("a", "??", false),
new Tuple<string, string, bool>("ab", "?*?", true),
new Tuple<string, string, bool>("ab", "*?*?*", true),
new Tuple<string, string, bool>("abc", "?**?*?", true),
new Tuple<string, string, bool>("abc", "?**?*c?", false),
new Tuple<string, string, bool>("abcd", "?b*??", true),
new Tuple<string, string, bool>("abcd", "?a*??", false),
new Tuple<string, string, bool>("abcd", "?**?c?", true),
new Tuple<string, string, bool>("abcd", "?**?d?", false),
new Tuple<string, string, bool>("abcde", "?*b*?*d*?", true),
// ? wildcard in the input string
new Tuple<string, string, bool>("?", "?", true),
new Tuple<string, string, bool>("?a", "?a", true),
new Tuple<string, string, bool>("a?", "a?", true),
new Tuple<string, string, bool>("a?b", "a?", false),
new Tuple<string, string, bool>("a?ab", "a?aab", false),
new Tuple<string, string, bool>("aa?bbbc?d", "aa?bbc?dd", false),
// * wildcard in the input string
new Tuple<string, string, bool>("*", "*", true),
new Tuple<string, string, bool>("*a", "*a", true),
new Tuple<string, string, bool>("a*", "a*", true),
new Tuple<string, string, bool>("a*b", "a*", true),
new Tuple<string, string, bool>("a*ab", "a*aab", false),
new Tuple<string, string, bool>("a*abab", "a*b", true),
new Tuple<string, string, bool>("aa*bbbc*d", "aa*bbc*dd", false),
new Tuple<string, string, bool>("aa*bbbc*d", "a*bbc*d", true)
};
foreach (var input in inputs)
{
try
{
Assert.Equal(input.Item3, FileMatcher.IsMatch(input.Item1, input.Item2, false));
Assert.Equal(input.Item3, FileMatcher.IsMatch(input.Item1, input.Item2, true));
Assert.Equal(input.Item3, FileMatcher.IsMatch(input.Item1.ToUpperInvariant(), input.Item2, true));
Assert.Equal(input.Item3, FileMatcher.IsMatch(input.Item1, input.Item2.ToUpperInvariant(), true));
}
catch (Exception)
{
Console.WriteLine($"Input {input.Item1} with pattern {input.Item2} failed");
throw;
}
}
}
/*
* Method: GetFileSystemEntries
*
* Simulate Directories.GetFileSystemEntries where file names are short.
*
*/
private static ImmutableArray<string> GetFileSystemEntries(FileMatcher.FileSystemEntity entityType, string path, string pattern, string projectDirectory, bool stripProjectDirectory)
{
if
(
pattern == @"LONGDI~1"
&& (@"D:\" == path || @"\\server\share\" == path || path.Length == 0)
)
{
return ImmutableArray.Create(Path.Combine(path, "LongDirectoryName"));
}
else if
(
pattern == @"LONGSU~1"
&& (@"D:\LongDirectoryName" == path || @"\\server\share\LongDirectoryName" == path || @"LongDirectoryName" == path)
)
{
return ImmutableArray.Create(Path.Combine(path, "LongSubDirectory"));
}
else if
(
pattern == @"LONGFI~1.TXT"
&& (@"D:\LongDirectoryName\LongSubDirectory" == path || @"\\server\share\LongDirectoryName\LongSubDirectory" == path || @"LongDirectoryName\LongSubDirectory" == path)
)
{
return ImmutableArray.Create(Path.Combine(path, "LongFileName.txt"));
}
else if
(
pattern == @"pomegr~1"
&& @"c:\apple\banana\tomato" == path
)
{
return ImmutableArray.Create(Path.Combine(path, "pomegranate"));
}
else if
(
@"c:\apple\banana\tomato\pomegranate\orange" == path
)
{
// No files exist here. This is an empty directory.
return ImmutableArray<string>.Empty;
}
else
{
Console.WriteLine("GetFileSystemEntries('{0}', '{1}')", path, pattern);
Assert.True(false, "Unexpected input into GetFileSystemEntries");
}
return ImmutableArray.Create("<undefined>");
}
private static readonly char S = Path.DirectorySeparatorChar;
public static IEnumerable<object[]> NormalizeTestData()
{
yield return new object[]
{
null,
null
};
yield return new object[]
{
"",
""
};
yield return new object[]
{
" ",
" "
};
yield return new object[]
{
@"\\",
@"\\"
};
yield return new object[]
{
@"\\/\//",
@"\\"
};
yield return new object[]
{
@"\\a/\b/\",
$@"\\a{S}b"
};
yield return new object[]
{
@"\",
@"\"
};
yield return new object[]
{
@"\/\/\/",
@"\"
};
yield return new object[]
{
@"\a/\b/\",
$@"\a{S}b"
};
yield return new object[]
{
"/",
"/"
};
yield return new object[]
{
@"/\/\",
"/"
};
yield return new object[]
{
@"/a\/b/\\",
$@"/a{S}b"
};
yield return new object[]
{
@"c:\",
@"c:\"
};
yield return new object[]
{
@"c:/",
@"c:\"
};
yield return new object[]
{
@"c:/\/\/",
@"c:\"
};
yield return new object[]
{
@"c:/ab",
@"c:\ab"
};
yield return new object[]
{
@"c:\/\a//b",
$@"c:\a{S}b"
};
yield return new object[]
{
@"c:\/\a//b\/",
$@"c:\a{S}b"
};
yield return new object[]
{
@"..\/a\../.\b\/",
$@"..{S}a{S}..{S}.{S}b"
};
yield return new object[]
{
@"**/\foo\/**\/",
$@"**{S}foo{S}**"
};
yield return new object[]
{
"AbCd",
"AbCd"
};
}
[Theory]
[MemberData(nameof(NormalizeTestData))]
public void NormalizeTest(string inputString, string expectedString)
{
FileMatcher.Normalize(inputString).ShouldBe(expectedString);
}
/// <summary>
/// Simple test of the MatchDriver code.
/// </summary>
[Fact]
public void BasicMatchDriver()
{
MatchDriver
(
"Source" + Path.DirectorySeparatorChar + "**",
new string[] // Files that exist and should match.
{
"Source" + Path.DirectorySeparatorChar + "Bart.txt",
"Source" + Path.DirectorySeparatorChar + "Sub" + Path.DirectorySeparatorChar + "Homer.txt",
},
new string[] // Files that exist and should not match.
{
"Destination" + Path.DirectorySeparatorChar + "Bart.txt",
"Destination" + Path.DirectorySeparatorChar + "Sub" + Path.DirectorySeparatorChar + "Homer.txt",
},
null
);
}
/// <summary>
/// This pattern should *not* recurse indefinitely since there is no '**' in the pattern:
///
/// c:\?emp\foo
///
/// </summary>
[Fact]
public void Regress162390()
{
MatchDriver
(
@"c:\?emp\foo.txt",
new string[] { @"c:\temp\foo.txt" }, // Should match
new string[] { @"c:\timp\foo.txt" }, // Shouldn't match
new string[] // Should not even consider.
{
@"c:\temp\sub\foo.txt"
}
);
}
/*
* Method: GetLongFileNameForShortLocalPath
*
* Convert a short local path to a long path.
*
*/
[Fact]
public void GetLongFileNameForShortLocalPath()
{
if (!NativeMethodsShared.IsWindows)
{
return; // "Short names are for Windows only"
}
string longPath = FileMatcher.GetLongPathName
(
@"D:\LONGDI~1\LONGSU~1\LONGFI~1.TXT",
new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries)
);
Assert.Equal(longPath, @"D:\LongDirectoryName\LongSubDirectory\LongFileName.txt");
}
/*
* Method: GetLongFileNameForLongLocalPath
*
* Convert a long local path to a long path (nop).
*
*/
[Fact]
public void GetLongFileNameForLongLocalPath()
{
string longPath = FileMatcher.GetLongPathName
(
@"D:\LongDirectoryName\LongSubDirectory\LongFileName.txt",
new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries)
);
Assert.Equal(longPath, @"D:\LongDirectoryName\LongSubDirectory\LongFileName.txt");
}
/*
* Method: GetLongFileNameForShortUncPath
*
* Convert a short UNC path to a long path.
*
*/
[Fact]
public void GetLongFileNameForShortUncPath()
{
if (!NativeMethodsShared.IsWindows)
{
return; // "Short names are for Windows only"
}
string longPath = FileMatcher.GetLongPathName
(
@"\\server\share\LONGDI~1\LONGSU~1\LONGFI~1.TXT",
new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries)
);
Assert.Equal(longPath, @"\\server\share\LongDirectoryName\LongSubDirectory\LongFileName.txt");
}
/*
* Method: GetLongFileNameForLongUncPath
*
* Convert a long UNC path to a long path (nop)
*
*/
[Fact]
public void GetLongFileNameForLongUncPath()
{
string longPath = FileMatcher.GetLongPathName
(
@"\\server\share\LongDirectoryName\LongSubDirectory\LongFileName.txt",
new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries)
);
Assert.Equal(longPath, @"\\server\share\LongDirectoryName\LongSubDirectory\LongFileName.txt");
}
/*
* Method: GetLongFileNameForRelativePath
*
* Convert a short relative path to a long path
*
*/
[Fact]
public void GetLongFileNameForRelativePath()
{
if (!NativeMethodsShared.IsWindows)
{
return; // "Short names are for Windows only"
}
string longPath = FileMatcher.GetLongPathName
(
@"LONGDI~1\LONGSU~1\LONGFI~1.TXT",
new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries)
);
Assert.Equal(longPath, @"LongDirectoryName\LongSubDirectory\LongFileName.txt");
}
/*
* Method: GetLongFileNameForRelativePathPreservesTrailingSlash
*
* Convert a short relative path with a trailing backslash to a long path
*
*/
[Fact]
public void GetLongFileNameForRelativePathPreservesTrailingSlash()
{
if (!NativeMethodsShared.IsWindows)
{
return; // "Short names are for Windows only"
}
string longPath = FileMatcher.GetLongPathName
(
@"LONGDI~1\LONGSU~1\",
new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries)
);
Assert.Equal(@"LongDirectoryName\LongSubDirectory\", longPath);
}
/*
* Method: GetLongFileNameForRelativePathPreservesExtraSlashes
*
* Convert a short relative path with doubled embedded backslashes to a long path
*
*/
[Fact]
public void GetLongFileNameForRelativePathPreservesExtraSlashes()
{
if (!NativeMethodsShared.IsWindows)
{
return; // "Short names are for Windows only"
}
string longPath = FileMatcher.GetLongPathName
(
@"LONGDI~1\\LONGSU~1\\",
new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries)
);
Assert.Equal(@"LongDirectoryName\\LongSubDirectory\\", longPath);
}
/*
* Method: GetLongFileNameForMixedLongAndShort
*
* Only part of the path might be short.
*
*/
[Fact]
public void GetLongFileNameForMixedLongAndShort()
{
if (!NativeMethodsShared.IsWindows)
{
return; // "Short names are for Windows only"
}
string longPath = FileMatcher.GetLongPathName
(
@"c:\apple\banana\tomato\pomegr~1\orange\",
new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries)
);
Assert.Equal(@"c:\apple\banana\tomato\pomegranate\orange\", longPath);
}
/*
* Method: GetLongFileNameWherePartOfThePathDoesntExist
*
* Part of the path may not exist. In this case, we treat the non-existent parts
* as if they were already a long file name.
*
*/
[Fact]
public void GetLongFileNameWherePartOfThePathDoesntExist()
{
if (!NativeMethodsShared.IsWindows)
{
return; // "Short names are for Windows only"
}
string longPath = FileMatcher.GetLongPathName
(
@"c:\apple\banana\tomato\pomegr~1\orange\chocol~1\vanila~1",
new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries)
);
Assert.Equal(@"c:\apple\banana\tomato\pomegranate\orange\chocol~1\vanila~1", longPath);
}
[Fact]
public void BasicMatch()
{
ValidateFileMatch("file.txt", "File.txt", false);
ValidateNoFileMatch("file.txt", "File.bin", false);
}
[Fact]
public void MatchSingleCharacter()
{
ValidateFileMatch("file.?xt", "File.txt", false);
ValidateNoFileMatch("file.?xt", "File.bin", false);
}
[Fact]
public void MatchMultipleCharacters()
{
ValidateFileMatch("*.txt", "*.txt", false);
ValidateNoFileMatch("*.txt", "*.bin", false);
}
[Fact]
public void SimpleRecursive()
{
ValidateFileMatch("**", ".\\File.txt", true);
}
[Fact]
public void DotForCurrentDirectory()
{
ValidateFileMatch(Path.Combine(".", "File.txt"), Path.Combine(".", "File.txt"), false);
ValidateNoFileMatch(Path.Combine(".", "File.txt"), Path.Combine(".", "File.bin"), false);
}
[Fact]
public void DotDotForParentDirectory()
{
ValidateFileMatch(Path.Combine("..", "..", "*.*"), Path.Combine("..", "..", "File.txt"), false);
if (NativeMethodsShared.IsWindows)
{
// On Linux *. * does not pick up files with no extension
ValidateFileMatch(Path.Combine("..", "..", "*.*"), Path.Combine("..", "..", "File"), false);
}
ValidateNoFileMatch(Path.Combine("..", "..", "*.*"), Path.Combine(new [] {"..", "..", "dir1", "dir2", "File.txt"}), false);
ValidateNoFileMatch(Path.Combine("..", "..", "*.*"), Path.Combine(new [] {"..", "..", "dir1", "dir2", "File"}), false);
}
[Fact]
public void ReduceDoubleSlashesBaseline()
{
// Baseline
ValidateFileMatch(
NativeMethodsShared.IsWindows ? "f:\\dir1\\dir2\\file.txt" : "/dir1/dir2/file.txt",
NativeMethodsShared.IsWindows ? "f:\\dir1\\dir2\\file.txt" : "/dir1/dir2/file.txt",
false);
ValidateFileMatch(Path.Combine("**", "*.cs"), Path.Combine("dir1", "dir2", "file.cs"), true);
ValidateFileMatch(Path.Combine("**", "*.cs"), "file.cs", true);
}
[Fact]
public void ReduceDoubleSlashes()
{
ValidateFileMatch("f:\\\\dir1\\dir2\\file.txt", "f:\\dir1\\dir2\\file.txt", false);
ValidateFileMatch("f:\\\\dir1\\\\\\dir2\\file.txt", "f:\\dir1\\dir2\\file.txt", false);
ValidateFileMatch("f:\\\\dir1\\\\\\dir2\\\\\\\\\\file.txt", "f:\\dir1\\dir2\\file.txt", false);
ValidateFileMatch("..\\**/\\*.cs", "..\\dir1\\dir2\\file.cs", true);
ValidateFileMatch("..\\**/.\\*.cs", "..\\dir1\\dir2\\file.cs", true);
ValidateFileMatch("..\\**\\./.\\*.cs", "..\\dir1\\dir2\\file.cs", true);
}
[Fact]
public void DoubleSlashesOnBothSidesOfComparison()
{
ValidateFileMatch("f:\\\\dir1\\dir2\\file.txt", "f:\\\\dir1\\dir2\\file.txt", false, false);
ValidateFileMatch("f:\\\\dir1\\\\\\dir2\\file.txt", "f:\\\\dir1\\\\\\dir2\\file.txt", false, false);
ValidateFileMatch("f:\\\\dir1\\\\\\dir2\\\\\\\\\\file.txt", "f:\\\\dir1\\\\\\dir2\\\\\\\\\\file.txt", false, false);
ValidateFileMatch("..\\**/\\*.cs", "..\\dir1\\dir2\\\\file.cs", true, false);
ValidateFileMatch("..\\**/.\\*.cs", "..\\dir1\\dir2//\\file.cs", true, false);
ValidateFileMatch("..\\**\\./.\\*.cs", "..\\dir1/\\/\\/dir2\\file.cs", true, false);
}
[Fact]
public void DecomposeDotSlash()
{
ValidateFileMatch("f:\\.\\dir1\\dir2\\file.txt", "f:\\dir1\\dir2\\file.txt", false);
ValidateFileMatch("f:\\dir1\\.\\dir2\\file.txt", "f:\\dir1\\dir2\\file.txt", false);
ValidateFileMatch("f:\\dir1\\dir2\\.\\file.txt", "f:\\dir1\\dir2\\file.txt", false);
ValidateFileMatch("f:\\.//dir1\\dir2\\file.txt", "f:\\dir1\\dir2\\file.txt", false);
ValidateFileMatch("f:\\dir1\\.//dir2\\file.txt", "f:\\dir1\\dir2\\file.txt", false);
ValidateFileMatch("f:\\dir1\\dir2\\.//file.txt", "f:\\dir1\\dir2\\file.txt", false);
ValidateFileMatch(".\\dir1\\dir2\\file.txt", ".\\dir1\\dir2\\file.txt", false);
ValidateFileMatch(".\\.\\dir1\\dir2\\file.txt", ".\\dir1\\dir2\\file.txt", false);
ValidateFileMatch(".//dir1\\dir2\\file.txt", ".\\dir1\\dir2\\file.txt", false);
ValidateFileMatch(".//.//dir1\\dir2\\file.txt", ".\\dir1\\dir2\\file.txt", false);
}
[Fact]
public void RecursiveDirRecursive()
{
// Check that a wildcardpath of **\x\**\ matches correctly since, \**\ is a
// separate code path.
ValidateFileMatch(@"c:\foo\**\x\**\*.*", @"c:\foo\x\file.txt", true);
ValidateFileMatch(@"c:\foo\**\x\**\*.*", @"c:\foo\y\x\file.txt", true);
ValidateFileMatch(@"c:\foo\**\x\**\*.*", @"c:\foo\x\y\file.txt", true);
ValidateFileMatch(@"c:\foo\**\x\**\*.*", @"c:\foo\y\x\y\file.txt", true);
ValidateFileMatch(@"c:\foo\**\x\**\*.*", @"c:\foo\x\x\file.txt", true);
ValidateFileMatch(@"c:\foo\**\x\**\*.*", @"c:\foo\x\x\file.txt", true);
ValidateFileMatch(@"c:\foo\**\x\**\*.*", @"c:\foo\x\x\x\file.txt", true);
}
[Fact]
public void Regress155731()
{
ValidateFileMatch(@"a\b\**\**\**\**\**\e\*", @"a\b\c\d\e\f.txt", true);
ValidateFileMatch(@"a\b\**\e\*", @"a\b\c\d\e\f.txt", true);
ValidateFileMatch(@"a\b\**\**\e\*", @"a\b\c\d\e\f.txt", true);
ValidateFileMatch(@"a\b\**\**\**\e\*", @"a\b\c\d\e\f.txt", true);
ValidateFileMatch(@"a\b\**\**\**\**\e\*", @"a\b\c\d\e\f.txt", true);
}
[Fact]
public void ParentWithoutSlash()
{
// However, we don't wtool this to match,
ValidateNoFileMatch(@"C:\foo\**", @"C:\foo", true);
// because we don't know whether foo is a file or folder.
// Same for UNC
ValidateNoFileMatch
(
"\\\\server\\c$\\Documents and Settings\\User\\**",
"\\\\server\\c$\\Documents and Settings\\User",
true
);
}
[Fact]
public void Unc()
{
//Check UNC functionality
ValidateFileMatch
(
"\\\\server\\c$\\**\\*.cs",
"\\\\server\\c$\\Documents and Settings\\User\\Source.cs",
true
);
ValidateNoFileMatch
(
"\\\\server\\c$\\**\\*.cs",
"\\\\server\\c$\\Documents and Settings\\User\\Source.txt",
true
);
ValidateFileMatch
(
"\\\\**",
"\\\\server\\c$\\Documents and Settings\\User\\Source.cs",
true
);
ValidateFileMatch
(
"\\\\**\\*.*",
"\\\\server\\c$\\Documents and Settings\\User\\Source.cs",
true
);
ValidateFileMatch
(
"**",
"\\\\server\\c$\\Documents and Settings\\User\\Source.cs",
true
);
}
[Fact]
public void ExplicitToolCompatibility()
{
// Explicit ANT compatibility. These patterns taken from the ANT documentation.
ValidateFileMatch("**/SourceSafe/*", "./SourceSafe/Repository", true);
ValidateFileMatch("**\\SourceSafe/*", "./SourceSafe/Repository", true);
ValidateFileMatch("**/SourceSafe/*", ".\\SourceSafe\\Repository", true);
ValidateFileMatch("**/SourceSafe/*", "./org/IIS/SourceSafe/Entries", true);
ValidateFileMatch("**/SourceSafe/*", "./org/IIS/pluggin/tools/tool/SourceSafe/Entries", true);
ValidateNoFileMatch("**/SourceSafe/*", "./org/IIS/SourceSafe/foo/bar/Entries", true);
ValidateNoFileMatch("**/SourceSafe/*", "./SourceSafeRepository", true);
ValidateNoFileMatch("**/SourceSafe/*", "./aSourceSafe/Repository", true);
ValidateFileMatch("org/IIS/pluggin/**", "org/IIS/pluggin/tools/tool/docs/index.html", true);
ValidateFileMatch("org/IIS/pluggin/**", "org/IIS/pluggin/test.xml", true);
ValidateFileMatch("org/IIS/pluggin/**", "org/IIS/pluggin\\test.xml", true);
ValidateNoFileMatch("org/IIS/pluggin/**", "org/IIS/abc.cs", true);
ValidateFileMatch("org/IIS/**/SourceSafe/*", "org/IIS/SourceSafe/Entries", true);
ValidateFileMatch("org/IIS/**/SourceSafe/*", "org\\IIS/SourceSafe/Entries", true);
ValidateFileMatch("org/IIS/**/SourceSafe/*", "org/IIS\\SourceSafe/Entries", true);
ValidateFileMatch("org/IIS/**/SourceSafe/*", "org/IIS/pluggin/tools/tool/SourceSafe/Entries", true);
ValidateNoFileMatch("org/IIS/**/SourceSafe/*", "org/IIS/SourceSafe/foo/bar/Entries", true);
ValidateNoFileMatch("org/IIS/**/SourceSafe/*", "org/IISSourceSage/Entries", true);
}
[Fact]
public void ExplicitToolIncompatibility()
{
// NOTE: Weirdly, ANT syntax is to match a file here.
// We don't because MSBuild philosophy is that a trailing slash indicates a directory
ValidateNoFileMatch("**/test/**", ".\\test", true);
// NOTE: We deviate from ANT format here. ANT would append a ** to any path
// that ends with '/' or '\'. We think this is the wrong thing because 'folder\'
// is a valid folder name.
ValidateNoFileMatch("org/", "org/IISSourceSage/Entries", false);
ValidateNoFileMatch("org\\", "org/IISSourceSage/Entries", false);
}
[Fact]
public void MultipleStarStar()
{
// Multiple-** matches
ValidateFileMatch("c:\\**\\user\\**\\*.*", "c:\\Documents and Settings\\user\\NTUSER.DAT", true);
ValidateNoFileMatch("c:\\**\\user1\\**\\*.*", "c:\\Documents and Settings\\user\\NTUSER.DAT", true);
ValidateFileMatch("c:\\**\\user\\**\\*.*", "c://Documents and Settings\\user\\NTUSER.DAT", true);
ValidateNoFileMatch("c:\\**\\user1\\**\\*.*", "c:\\Documents and Settings//user\\NTUSER.DAT", true);
}
[Fact]
public void RegressItemRecursionWorksAsExpected()
{
// Regress bug#54411: Item recursion doesn't work as expected on "c:\foo\**"
ValidateFileMatch("c:\\foo\\**", "c:\\foo\\two\\subfile.txt", true);
}
[Fact]
public void IllegalPaths()
{
// Certain patterns are illegal.
ValidateIllegal("**.cs");
ValidateIllegal("***");
ValidateIllegal("****");
ValidateIllegal("*.cs**");
ValidateIllegal("*.cs**");
ValidateIllegal("...\\*.cs");
ValidateIllegal("http://www.website.com");
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Nothing's too long for Unix
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp)]
public void IllegalTooLongPath()
{
string longString = new string('X', 500) + "*"; // need a wildcard to do anything
string[] result = FileMatcher.Default.GetFiles(@"c:\", longString);
Assert.Equal(longString, result[0]); // Does not throw
// Not checking that GetFileSpecMatchInfo returns the illegal-path flag,
// not certain that won't break something; this fix is merely to avoid a crash.
}
[Fact]
public void SplitFileSpec()
{
/*************************************************************************************
* Call ValidateSplitFileSpec with various supported combinations.
*************************************************************************************/
ValidateSplitFileSpec("foo.cs", "", "", "foo.cs");
ValidateSplitFileSpec("**\\foo.cs", "", "**\\", "foo.cs");
ValidateSplitFileSpec("f:\\dir1\\**\\foo.cs", "f:\\dir1\\", "**\\", "foo.cs");
ValidateSplitFileSpec("..\\**\\foo.cs", "..\\", "**\\", "foo.cs");
ValidateSplitFileSpec("f:\\dir1\\foo.cs", "f:\\dir1\\", "", "foo.cs");
ValidateSplitFileSpec("f:\\dir?\\foo.cs", "f:\\", "dir?\\", "foo.cs");
ValidateSplitFileSpec("dir?\\foo.cs", "", "dir?\\", "foo.cs");
ValidateSplitFileSpec(@"**\test\**", "", @"**\test\**\", "*.*");
ValidateSplitFileSpec("bin\\**\\*.cs", "bin\\", "**\\", "*.cs");
ValidateSplitFileSpec("bin\\**\\*.*", "bin\\", "**\\", "*.*");
ValidateSplitFileSpec("bin\\**", "bin\\", "**\\", "*.*");
ValidateSplitFileSpec("bin\\**\\", "bin\\", "**\\", "");
ValidateSplitFileSpec("bin\\**\\*", "bin\\", "**\\", "*");
ValidateSplitFileSpec("**", "", "**\\", "*.*");
}
[Fact]
public void Regress367780_CrashOnStarDotDot()
{
string workingPath = _env.CreateFolder().Path;
string workingPathSubfolder = Path.Combine(workingPath, "SubDir");
string offendingPattern = Path.Combine(workingPath, @"*\..\bar");
string[] files = new string[0];
Directory.CreateDirectory(workingPath);
Directory.CreateDirectory(workingPathSubfolder);
files = FileMatcher.Default.GetFiles(workingPath, offendingPattern);
}
[Fact]
public void Regress141071_StarStarSlashStarStarIsLiteral()
{
string workingPath = _env.CreateFolder().Path;
string fileName = Path.Combine(workingPath, "MyFile.txt");
string offendingPattern = Path.Combine(workingPath, @"**\**");
Directory.CreateDirectory(workingPath);
File.WriteAllText(fileName, "Hello there.");
var files = FileMatcher.Default.GetFiles(workingPath, offendingPattern);
string result = String.Join(", ", files);
Console.WriteLine(result);
Assert.False(result.Contains("**"));
Assert.True(result.Contains("MyFile.txt"));
}
[Fact]
public void Regress14090_TrailingDotMatchesNoExtension()
{
string workingPath = _env.CreateFolder().Path;
string workingPathSubdir = Path.Combine(workingPath, "subdir");
string workingPathSubdirBing = Path.Combine(workingPathSubdir, "bing");
string offendingPattern = Path.Combine(workingPath, @"**\sub*\*.");
Directory.CreateDirectory(workingPath);
Directory.CreateDirectory(workingPathSubdir);
File.AppendAllText(workingPathSubdirBing, "y");
var files = FileMatcher.Default.GetFiles(workingPath, offendingPattern);
string result = String.Join(", ", files);
Console.WriteLine(result);
Assert.Equal(1, files.Length);
}
[Fact]
public void Regress14090_TrailingDotMatchesNoExtension_Part2()
{
ValidateFileMatch(@"c:\mydir\**\*.", @"c:\mydir\subdir\bing", true, /* simulate filesystem? */ false);
ValidateNoFileMatch(@"c:\mydir\**\*.", @"c:\mydir\subdir\bing.txt", true);
}
[Fact]
public void FileEnumerationCacheTakesExcludesIntoAccount()
{
try
{
using (var env = TestEnvironment.Create())
{
env.SetEnvironmentVariable("MsBuildCacheFileEnumerations", "1");
var testProject = env.CreateTestProjectWithFiles(string.Empty, new[] {"a.cs", "b.cs", "c.cs"});
var files = FileMatcher.Default.GetFiles(testProject.TestRoot, "**/*.cs");
Array.Sort(files);
Assert.Equal(new []{"a.cs", "b.cs", "c.cs"}, files);
files = FileMatcher.Default.GetFiles(testProject.TestRoot, "**/*.cs", new List<string>{"a.cs"});
Array.Sort(files);
Assert.Equal(new[] {"b.cs", "c.cs" }, files);
files = FileMatcher.Default.GetFiles(testProject.TestRoot, "**/*.cs", new List<string>{"a.cs", "c.cs"});
Array.Sort(files);
Assert.Equal(new[] {"b.cs" }, files);
}
}
finally
{
FileMatcher.ClearFileEnumerationsCache();
}
}
[Fact]
public void RemoveProjectDirectory()
{
string[] strings = new string[1] { NativeMethodsShared.IsWindows ? "c:\\1.file" : "/1.file" };
strings = FileMatcher.RemoveProjectDirectory(strings, NativeMethodsShared.IsWindows ? "c:\\" : "/").ToArray();
Assert.Equal(strings[0], "1.file");
strings = new string[1] { NativeMethodsShared.IsWindows ? "c:\\directory\\1.file" : "/directory/1.file"};
strings = FileMatcher.RemoveProjectDirectory(strings, NativeMethodsShared.IsWindows ? "c:\\" : "/").ToArray();
Assert.Equal(strings[0], NativeMethodsShared.IsWindows ? "directory\\1.file" : "directory/1.file");
strings = new string[1] { NativeMethodsShared.IsWindows ? "c:\\directory\\1.file" : "/directory/1.file" };
strings = FileMatcher.RemoveProjectDirectory(strings, NativeMethodsShared.IsWindows ? "c:\\directory" : "/directory").ToArray();
Assert.Equal(strings[0], "1.file");
strings = new string[1] { NativeMethodsShared.IsWindows ? "c:\\1.file" : "/1.file" };
strings = FileMatcher.RemoveProjectDirectory(strings, NativeMethodsShared.IsWindows ? "c:\\directory" : "/directory" ).ToArray();
Assert.Equal(strings[0], NativeMethodsShared.IsWindows ? "c:\\1.file" : "/1.file");
strings = new string[1] { NativeMethodsShared.IsWindows ? "c:\\directorymorechars\\1.file" : "/directorymorechars/1.file" };
strings = FileMatcher.RemoveProjectDirectory(strings, NativeMethodsShared.IsWindows ? "c:\\directory" : "/directory").ToArray();
Assert.Equal(strings[0], NativeMethodsShared.IsWindows ? "c:\\directorymorechars\\1.file" : "/directorymorechars/1.file" );
if (NativeMethodsShared.IsWindows)
{
strings = new string[1] { "\\Machine\\1.file" };
strings = FileMatcher.RemoveProjectDirectory(strings, "\\Machine").ToArray();
Assert.Equal(strings[0], "1.file");
strings = new string[1] { "\\Machine\\directory\\1.file" };
strings = FileMatcher.RemoveProjectDirectory(strings, "\\Machine").ToArray();
Assert.Equal(strings[0], "directory\\1.file");
strings = new string[1] { "\\Machine\\directory\\1.file" };
strings = FileMatcher.RemoveProjectDirectory(strings, "\\Machine\\directory").ToArray();
Assert.Equal(strings[0], "1.file");
strings = new string[1] { "\\Machine\\1.file" };
strings = FileMatcher.RemoveProjectDirectory(strings, "\\Machine\\directory").ToArray();
Assert.Equal(strings[0], "\\Machine\\1.file");
strings = new string[1] { "\\Machine\\directorymorechars\\1.file" };
strings = FileMatcher.RemoveProjectDirectory(strings, "\\Machine\\directory").ToArray();
Assert.Equal(strings[0], "\\Machine\\directorymorechars\\1.file");
}
}
[Theory]
[InlineData(
@"src/**/*.cs", // Include Pattern
new string[] // Matching files
{
@"src/a.cs",
@"src/a\b\b.cs",
}
)]
[InlineData(
@"src/test/**/*.cs", // Include Pattern
new string[] // Matching files
{
@"src/test/a.cs",
@"src/test/a\b\c.cs",
}
)]
[InlineData(
@"src/test/**/a/b/**/*.cs", // Include Pattern
new string[] // Matching files
{
@"src/test/dir\a\b\a.cs",
@"src/test/dir\a\b\c\a.cs",
}
)]
public void IncludePatternShouldNotPreserveUserSlashesInFixedDirPart(string include, string[] matching)
{
MatchDriver(include, null, matching, null, null, normalizeAllPaths: false, normalizeExpectedMatchingFiles: true);
}
[Theory]
[InlineData(
@"**\*.cs", // Include Pattern
new[] // Exclude patterns
{
@"bin\**"
},
new string[] // Matching files
{
},
new string[] // Non matching files
{
},
new[] // Non matching files that shouldn't be touched
{
@"bin\foo.cs",
@"bin\bar\foo.cs",
@"bin\bar\"
}
)]
[InlineData(
@"**\*.cs", // Include Pattern
new[] // Exclude patterns
{
@"bin\**"
},
new[] // Matching files
{
"a.cs",
@"b\b.cs",
},
new[] // Non matching files
{
@"b\b.txt"
},
new[] // Non matching files that shouldn't be touched
{
@"bin\foo.cs",
@"bin\bar\foo.cs",
@"bin\bar\"
}
)]
public void ExcludePattern(string include, string[] exclude, string[] matching, string[] nonMatching, string[] untouchable)
{
MatchDriver(include, exclude, matching, nonMatching, untouchable);
}
[Fact]
public void ExcludeSpecificFiles()
{
MatchDriverWithDifferentSlashes(
@"**\*.cs", // Include Pattern
new[] // Exclude patterns
{
@"Program_old.cs",
@"Properties\AssemblyInfo_old.cs"
},
new[] // Matching files
{
@"foo.cs",
@"Properties\AssemblyInfo.cs",
@"Foo\Bar\Baz\Buzz.cs"
},
new[] // Non matching files
{
@"Program_old.cs",
@"Properties\AssemblyInfo_old.cs"
},
new string[] // Non matching files that shouldn't be touched
{
}
);
}
[Fact]
public void ExcludePatternAndSpecificFiles()
{
MatchDriverWithDifferentSlashes(
@"**\*.cs", // Include Pattern
new[] // Exclude patterns
{
@"bin\**",
@"Program_old.cs",
@"Properties\AssemblyInfo_old.cs"
},
new[] // Matching files
{
@"foo.cs",
@"Properties\AssemblyInfo.cs",
@"Foo\Bar\Baz\Buzz.cs"
},
new[] // Non matching files
{
@"foo.txt",
@"Foo\foo.txt",
@"Program_old.cs",
@"Properties\AssemblyInfo_old.cs"
},
new[] // Non matching files that shouldn't be touched
{
@"bin\foo.cs",
@"bin\bar\foo.cs",
@"bin\bar\"
}
);
}
[Theory]
[InlineData(
@"**\*.cs", // Include Pattern
new[] // Exclude patterns
{
@"**\bin\**\*.cs",
@"src\Common\**",
},
new[] // Matching files
{
@"foo.cs",
@"src\Framework\Properties\AssemblyInfo.cs",
@"src\Framework\Foo\Bar\Baz\Buzz.cs"
},
new[] // Non matching files
{
@"foo.txt",
@"src\Framework\Readme.md",
@"src\Common\foo.cs",
// Ideally these would be untouchable
@"src\Framework\bin\foo.cs",
@"src\Framework\bin\Debug",
@"src\Framework\bin\Debug\foo.cs",
},
new[] // Non matching files that shouldn't be touched
{
@"src\Common\Properties\",
@"src\Common\Properties\AssemblyInfo.cs",
}
)]
[InlineData(
@"**\*.cs", // Include Pattern
new[] // Exclude patterns
{
@"**\bin\**\*.cs",
@"src\Co??on\**",
},
new[] // Matching files
{
@"foo.cs",
@"src\Framework\Properties\AssemblyInfo.cs",
@"src\Framework\Foo\Bar\Baz\Buzz.cs"
},
new[] // Non matching files
{
@"foo.txt",
@"src\Framework\Readme.md",
@"src\Common\foo.cs",
// Ideally these would be untouchable
@"src\Framework\bin\foo.cs",
@"src\Framework\bin\Debug",
@"src\Framework\bin\Debug\foo.cs",
@"src\Common\Properties\AssemblyInfo.cs"
},
new[] // Non matching files that shouldn't be touched
{
@"src\Common\Properties\"
}
)]
[InlineData(
@"src\**\proj\**\*.cs", // Include Pattern
new[] // Exclude patterns
{
@"src\**\proj\**\none\**\*",
},
new[] // Matching files
{
@"src\proj\m1.cs",
@"src\proj\a\m2.cs",
@"src\b\proj\m3.cs",
@"src\c\proj\d\m4.cs",
},
new[] // Non matching files
{
@"nm1.cs",
@"a\nm2.cs",
@"src\nm3.cs",
@"src\a\nm4.cs",
// Ideally these would be untouchable
@"src\proj\none\nm5.cs",
@"src\proj\a\none\nm6.cs",
@"src\b\proj\none\nm7.cs",
@"src\c\proj\d\none\nm8.cs",
@"src\e\proj\f\none\g\nm8.cs",
},
new string[] // Non matching files that shouldn't be touched
{
}
)]
// patterns with excludes that ideally would prune entire recursive subtrees (files in pruned tree aren't touched at all) but the exclude pattern is too complex for that to work with the current logic
public void ExcludeComplexPattern(string include, string[] exclude, string[] matching, string[] nonMatching, string[] untouchable)
{
MatchDriverWithDifferentSlashes(include, exclude, matching, nonMatching, untouchable);
}
[Theory]
// Empty string is valid
[InlineData(
"",
"",
"",
"",
"^(?<FIXEDDIR>)(?<WILDCARDDIR>)(?<FILENAME>)$",
false,
true
)]
// ... anywhere is invalid
[InlineData(
@"...\foo",
"",
"",
"",
null,
false,
false
)]
// : not placed at second index is invalid
[InlineData(
"http://www.website.com",
"",
"",
"",
null,
false,
false
)]
// ** not alone in filename part is invalid
[InlineData(
"**foo",
"",
"",
"**foo",
"",
false,
false
)]
// ** not alone in filename part is invalid
[InlineData(
"foo**",
"",
"",
"foo**",
"",
false,
false
)]
// ** not alone between slashes in wildcard part is invalid
[InlineData(
@"**foo\bar",
"",
@"**foo\",
"bar",
"",
false,
false
)]
// .. placed after any ** is invalid
[InlineData(
@"**\..\bar",
"",
@"**\..\",
"bar",
"",
false,
false
)]
// Common wildcard characters in wildcard and filename part
[InlineData(
@"*fo?ba?\*fo?ba?",
"",
@"*fo?ba?\",
"*fo?ba?",
@"^(?<FIXEDDIR>)(?<WILDCARDDIR>[^/\\]*fo.ba.[/\\]+)(?<FILENAME>[^/\\]*fo.ba.)$",
true,
true
)]
// Special case for ? and * when trailing . in filename part
[InlineData(
"?oo*.",
"",
"",
"?oo*.",
@"^(?<FIXEDDIR>)(?<WILDCARDDIR>)(?<FILENAME>[^\.].oo[^\.]*)$",
false,
true
)]
// Skip the .* portion of any *.* sequence in filename part
[InlineData(
"*.*foo*.*",
"",
"",
"*.*foo*.*",
@"^(?<FIXEDDIR>)(?<WILDCARDDIR>)(?<FILENAME>[^/\\]*foo[^/\\]*)$",
false,
true
)]
// Collapse successive directory separators
[InlineData(
@"\foo///bar\\\?foo///bar\\\foo",
@"\foo///bar\\\",
@"?foo///bar\\\",
"foo",
@"^(?<FIXEDDIR>[/\\]+foo[/\\]+bar[/\\]+)(?<WILDCARDDIR>.foo[/\\]+bar[/\\]+)(?<FILENAME>foo)$",
true,
true
)]
// Collapse successive relative separators
[InlineData(
@"\./.\foo/.\./bar\./.\?foo/.\./bar\./.\foo",
@"\./.\foo/.\./bar\./.\",
@"?foo/.\./bar\./.\",
"foo",
@"^(?<FIXEDDIR>[/\\]+foo[/\\]+bar[/\\]+)(?<WILDCARDDIR>.foo[/\\]+bar[/\\]+)(?<FILENAME>foo)$",
true,
true
)]
// Collapse successive recursive operators
[InlineData(
@"foo\**/**\bar/**\**/foo\**/**\bar",
@"foo\",
@"**/**\bar/**\**/foo\**/**\",
"bar",
@"^(?<FIXEDDIR>foo[/\\]+)(?<WILDCARDDIR>((.*/)|(.*\\)|())bar((/)|(\\)|(/.*/)|(/.*\\)|(\\.*\\)|(\\.*/))foo((/)|(\\)|(/.*/)|(/.*\\)|(\\.*\\)|(\\.*/)))(?<FILENAME>bar)$",
true,
true
)]
// Collapse all three cases combined
[InlineData(
@"foo\\\.///**\\\.///**\\\.///bar\\\.///**\\\.///**\\\.///foo\\\.///**\\\.///**\\\.///bar",
@"foo\\\.///",
@"**\\\.///**\\\.///bar\\\.///**\\\.///**\\\.///foo\\\.///**\\\.///**\\\.///",
"bar",
@"^(?<FIXEDDIR>foo[/\\]+)(?<WILDCARDDIR>((.*/)|(.*\\)|())bar((/)|(\\)|(/.*/)|(/.*\\)|(\\.*\\)|(\\.*/))foo((/)|(\\)|(/.*/)|(/.*\\)|(\\.*\\)|(\\.*/)))(?<FILENAME>bar)$",
true,
true
)]
public void GetFileSpecInfoCommon(
string filespec,
string expectedFixedDirectoryPart,
string expectedWildcardDirectoryPart,
string expectedFilenamePart,
string expectedMatchFileExpression,
bool expectedNeedsRecursion,
bool expectedIsLegalFileSpec
)
{
if (NativeMethodsShared.IsUnixLike)
{
expectedFixedDirectoryPart = FileUtilities.FixFilePath(expectedFixedDirectoryPart);
expectedWildcardDirectoryPart = FileUtilities.FixFilePath(expectedWildcardDirectoryPart);
}
TestGetFileSpecInfo(
filespec,
expectedFixedDirectoryPart,
expectedWildcardDirectoryPart,
expectedFilenamePart,
expectedMatchFileExpression,
expectedNeedsRecursion,
expectedIsLegalFileSpec
);
}
[PlatformSpecific(TestPlatforms.Windows)]
[Theory]
// Escape pecial regex characters valid in Windows paths
[InlineData(
@"$()+.[^{\?$()+.[^{\$()+.[^{",
@"$()+.[^{\",
@"?$()+.[^{\",
"$()+.[^{",
@"^(?<FIXEDDIR>\$\(\)\+\.\[\^\{[/\\]+)(?<WILDCARDDIR>.\$\(\)\+\.\[\^\{[/\\]+)(?<FILENAME>\$\(\)\+\.\[\^\{)$",
true,
true
)]
// Preserve UNC paths in fixed directory part
[InlineData(
@"\\\.\foo/bar",
@"\\\.\foo/",
"",
"bar",
@"^(?<FIXEDDIR>\\\\foo[/\\]+)(?<WILDCARDDIR>)(?<FILENAME>bar)$",
false,
true
)]
public void GetFileSpecInfoWindows(
string filespec,
string expectedFixedDirectoryPart,
string expectedWildcardDirectoryPart,
string expectedFilenamePart,
string expectedMatchFileExpression,
bool expectedNeedsRecursion,
bool expectedIsLegalFileSpec
)
{
TestGetFileSpecInfo(
filespec,
expectedFixedDirectoryPart,
expectedWildcardDirectoryPart,
expectedFilenamePart,
expectedMatchFileExpression,
expectedNeedsRecursion,
expectedIsLegalFileSpec
);
}
[PlatformSpecific(TestPlatforms.AnyUnix)]
[Theory]
// Escape regex characters valid in Unix paths
[InlineData(
@"$()+.[^{|\?$()+.[^{|\$()+.[^{|",
@"$()+.[^{|/",
@"?$()+.[^{|/",
"$()+.[^{|",
@"^(?<FIXEDDIR>\$\(\)\+\.\[\^\{\|[/\\]+)(?<WILDCARDDIR>.\$\(\)\+\.\[\^\{\|[/\\]+)(?<FILENAME>\$\(\)\+\.\[\^\{\|)$",
true,
true
)]
// Collapse leading successive directory separators in fixed directory part
[InlineData(
@"\\\.\foo/bar",
@"///./foo/",
"",
"bar",
@"^(?<FIXEDDIR>[/\\]+foo[/\\]+)(?<WILDCARDDIR>)(?<FILENAME>bar)$",
false,
true
)]
public void GetFileSpecInfoUnix(
string filespec,
string expectedFixedDirectoryPart,
string expectedWildcardDirectoryPart,
string expectedFilenamePart,
string expectedMatchFileExpression,
bool expectedNeedsRecursion,
bool expectedIsLegalFileSpec
)
{
TestGetFileSpecInfo(
filespec,
expectedFixedDirectoryPart,
expectedWildcardDirectoryPart,
expectedFilenamePart,
expectedMatchFileExpression,
expectedNeedsRecursion,
expectedIsLegalFileSpec
);
}
private void TestGetFileSpecInfo(
string filespec,
string expectedFixedDirectoryPart,
string expectedWildcardDirectoryPart,
string expectedFilenamePart,
string expectedMatchFileExpression,
bool expectedNeedsRecursion,
bool expectedIsLegalFileSpec
)
{
FileMatcher.Default.GetFileSpecInfo(
filespec,
out string fixedDirectoryPart,
out string wildcardDirectoryPart,
out string filenamePart,
out string matchFileExpression,
out bool needsRecursion,
out bool isLegalFileSpec
);
fixedDirectoryPart.ShouldBe(expectedFixedDirectoryPart);
wildcardDirectoryPart.ShouldBe(expectedWildcardDirectoryPart);
filenamePart.ShouldBe(expectedFilenamePart);
matchFileExpression.ShouldBe(expectedMatchFileExpression);
needsRecursion.ShouldBe(expectedNeedsRecursion);
isLegalFileSpec.ShouldBe(expectedIsLegalFileSpec);
}
#region Support functions.
/// <summary>
/// This support class simulates a file system.
/// It accepts multiple sets of files and keeps track of how many files were "hit"
/// In this case, "hit" means that the caller asked for that file directly.
/// </summary>
internal class MockFileSystem
{
/// <summary>
/// Array of files (set1)
/// </summary>
private string[] _fileSet1;
/// <summary>
/// Array of files (set2)
/// </summary>
private string[] _fileSet2;
/// <summary>
/// Array of files (set3)
/// </summary>
private string[] _fileSet3;
/// <summary>
/// Number of times a file from set 1 was requested.
/// </summary>
private int _fileSet1Hits = 0;
/// <summary>
/// Number of times a file from set 2 was requested.
/// </summary>
private int _fileSet2Hits = 0;
/// <summary>
/// Number of times a file from set 3 was requested.
/// </summary>
private int _fileSet3Hits = 0;
/// <summary>
/// Construct.
/// </summary>
/// <param name="fileSet1">First set of files.</param>
/// <param name="fileSet2">Second set of files.</param>
/// <param name="fileSet3">Third set of files.</param>
internal MockFileSystem
(
string[] fileSet1,
string[] fileSet2,
string[] fileSet3
)
{
_fileSet1 = fileSet1;
_fileSet2 = fileSet2;
_fileSet3 = fileSet3;
}
/// <summary>
/// Number of times a file from set 1 was requested.
/// </summary>
internal int FileHits1
{
get { return _fileSet1Hits; }
}
/// <summary>
/// Number of times a file from set 2 was requested.
/// </summary>
internal int FileHits2
{
get { return _fileSet2Hits; }
}
/// <summary>
/// Number of times a file from set 3 was requested.
/// </summary>
internal int FileHits3
{
get { return _fileSet3Hits; }
}
/// <summary>
/// Return files that match the given files.
/// </summary>
/// <param name="candidates">Candidate files.</param>
/// <param name="path">The path to search within</param>
/// <param name="pattern">The pattern to search for.</param>
/// <param name="files">Hashtable receives the files.</param>
/// <returns></returns>
private int GetMatchingFiles(string[] candidates, string path, string pattern, ISet<string> files)
{
int hits = 0;
if (candidates != null)
{
foreach (string candidate in candidates)
{
string normalizedCandidate = Normalize(candidate);
// Get the candidate directory.
string candidateDirectoryName = "";
if (normalizedCandidate.IndexOfAny(FileMatcher.directorySeparatorCharacters) != -1)
{
candidateDirectoryName = Path.GetDirectoryName(normalizedCandidate);
}
// Does the candidate directory match the requested path?
if (FileUtilities.PathsEqual(path, candidateDirectoryName))
{
// Match the basic *.* or null. These both match any file.
if
(
pattern == null ||
String.Compare(pattern, "*.*", StringComparison.OrdinalIgnoreCase) == 0
)
{
++hits;
files.Add(FileMatcher.Normalize(candidate));
}
else if (pattern.Substring(0, 2) == "*.") // Match patterns like *.cs
{
string tail = pattern.Substring(1);
string candidateTail = candidate.Substring(candidate.Length - tail.Length);
if (String.Compare(tail, candidateTail, StringComparison.OrdinalIgnoreCase) == 0)
{
++hits;
files.Add(FileMatcher.Normalize(candidate));
}
}
else if (pattern.Substring(pattern.Length - 4, 2) == ".?") // Match patterns like foo.?xt
{
string leader = pattern.Substring(0, pattern.Length - 4);
string candidateLeader = candidate.Substring(candidate.Length - leader.Length - 4, leader.Length);
if (String.Compare(leader, candidateLeader, StringComparison.OrdinalIgnoreCase) == 0)
{
string tail = pattern.Substring(pattern.Length - 2);
string candidateTail = candidate.Substring(candidate.Length - 2);
if (String.Compare(tail, candidateTail, StringComparison.OrdinalIgnoreCase) == 0)
{
++hits;
files.Add(FileMatcher.Normalize(candidate));
}
}
}
else if (!FileMatcher.HasWildcards(pattern))
{
if (normalizedCandidate == Path.Combine(path, pattern))
{
++hits;
files.Add(candidate);
}
}
else
{
Assert.True(false, String.Format("Unhandled case in GetMatchingFiles: {0}", pattern));
}
}
}
}
return hits;
}
/// <summary>
/// Given a path and pattern, return all the simulated directories out of candidates.
/// </summary>
/// <param name="candidates">Candidate file to extract directories from.</param>
/// <param name="path">The path to search.</param>
/// <param name="pattern">The pattern to match.</param>
/// <param name="directories">Receives the directories.</param>
private void GetMatchingDirectories(string[] candidates, string path, string pattern, ISet<string> directories)
{
if (candidates != null)
{
foreach (string candidate in candidates)
{
string normalizedCandidate = Normalize(candidate);
if (IsMatchingDirectory(path, normalizedCandidate))
{
int nextSlash = normalizedCandidate.IndexOfAny(FileMatcher.directorySeparatorCharacters, path.Length + 1);
if (nextSlash != -1)
{
string match;
//UNC paths start with a \\ fragment. Match against \\ when path is empty (i.e., inside the current working directory)
match = normalizedCandidate.StartsWith(@"\\") && string.IsNullOrEmpty(path)
? @"\\"
: normalizedCandidate.Substring(0, nextSlash);
string baseMatch = Path.GetFileName(normalizedCandidate.Substring(0, nextSlash));
if
(
String.Compare(pattern, "*.*", StringComparison.OrdinalIgnoreCase) == 0
|| pattern == null
)
{
directories.Add(FileMatcher.Normalize(match));
}
else if // Match patterns like ?emp
(
pattern.Substring(0, 1) == "?"
&& pattern.Length == baseMatch.Length
)
{
string tail = pattern.Substring(1);
string baseMatchTail = baseMatch.Substring(1);
if (String.Compare(tail, baseMatchTail, StringComparison.OrdinalIgnoreCase) == 0)
{
directories.Add(FileMatcher.Normalize(match));
}
}
else
{
Assert.True(false, String.Format("Unhandled case in GetMatchingDirectories: {0}", pattern));
}
}
}
}
}
}
/// <summary>
/// Method that is delegable for use by FileMatcher. This method simulates a filesystem by returning
/// files and\or folders that match the requested path and pattern.
/// </summary>
/// <param name="entityType">Files, Directories or both</param>
/// <param name="path">The path to search.</param>
/// <param name="pattern">The pattern to search (may be null)</param>
/// <returns>The matched files or folders.</returns>
internal ImmutableArray<string> GetAccessibleFileSystemEntries(FileMatcher.FileSystemEntity entityType, string path, string pattern, string projectDirectory, bool stripProjectDirectory)
{
string normalizedPath = Normalize(path);
ISet<string> files = new HashSet<string>();
if (entityType == FileMatcher.FileSystemEntity.Files || entityType == FileMatcher.FileSystemEntity.FilesAndDirectories)
{
_fileSet1Hits += GetMatchingFiles(_fileSet1, normalizedPath, pattern, files);
_fileSet2Hits += GetMatchingFiles(_fileSet2, normalizedPath, pattern, files);
_fileSet3Hits += GetMatchingFiles(_fileSet3, normalizedPath, pattern, files);
}
if (entityType == FileMatcher.FileSystemEntity.Directories || entityType == FileMatcher.FileSystemEntity.FilesAndDirectories)
{
GetMatchingDirectories(_fileSet1, normalizedPath, pattern, files);
GetMatchingDirectories(_fileSet2, normalizedPath, pattern, files);
GetMatchingDirectories(_fileSet3, normalizedPath, pattern, files);
}
return files.ToImmutableArray();
}
/// <summary>
/// Given a path, fix it up so that it can be compared to another path.
/// </summary>
/// <param name="path">The path to fix up.</param>
/// <returns>The normalized path.</returns>
internal static string Normalize(string path)
{
if (path.Length == 0)
{
return path;
}
string normalized = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
if (Path.DirectorySeparatorChar != '\\')
{
normalized = path.Replace("\\", Path.DirectorySeparatorChar.ToString());
}
// Replace leading UNC.
if (normalized.StartsWith(@"\\"))
{
normalized = "<:UNC:>" + normalized.Substring(2);
}
// Preserve parent-directory markers.
normalized = normalized.Replace(@".." + Path.DirectorySeparatorChar, "<:PARENT:>");
// Just get rid of doubles enough to satisfy our test cases.
string doubleSeparator = Path.DirectorySeparatorChar.ToString() + Path.DirectorySeparatorChar.ToString();
normalized = normalized.Replace(doubleSeparator, Path.DirectorySeparatorChar.ToString());
normalized = normalized.Replace(doubleSeparator, Path.DirectorySeparatorChar.ToString());
normalized = normalized.Replace(doubleSeparator, Path.DirectorySeparatorChar.ToString());
// Strip any .\
normalized = normalized.Replace(@"." + Path.DirectorySeparatorChar, "");
// Put back the preserved markers.
normalized = normalized.Replace("<:UNC:>", @"\\");
normalized = normalized.Replace("<:PARENT:>", @".." + Path.DirectorySeparatorChar);
return normalized;
}
/// <summary>
/// Determines whether candidate is in a subfolder of path.
/// </summary>
/// <param name="path"></param>
/// <param name="candidate"></param>
/// <returns>True if there is a match.</returns>
private bool IsMatchingDirectory(string path, string candidate)
{
string normalizedPath = Normalize(path);
string normalizedCandidate = Normalize(candidate);
// Current directory always matches for non-rooted paths.
if (path.Length == 0 && !Path.IsPathRooted(candidate))
{
return true;
}
if (normalizedCandidate.Length > normalizedPath.Length)
{
if (String.Compare(normalizedPath, 0, normalizedCandidate, 0, normalizedPath.Length, StringComparison.OrdinalIgnoreCase) == 0)
{
if (FileUtilities.EndsWithSlash(normalizedPath))
{
return true;
}
else if (FileUtilities.IsSlash(normalizedCandidate[normalizedPath.Length]))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Searches the candidates array for one that matches path
/// </summary>
/// <param name="path"></param>
/// <param name="candidates"></param>
/// <returns>The index of the first match or negative one.</returns>
private int IndexOfFirstMatchingDirectory(string path, string[] candidates)
{
if (candidates != null)
{
int i = 0;
foreach (string candidate in candidates)
{
if (IsMatchingDirectory(path, candidate))
{
return i;
}
++i;
}
}
return -1;
}
/// <summary>
/// Delegable method that returns true if the given directory exists in this simulated filesystem
/// </summary>
/// <param name="path">The path to check.</param>
/// <returns>True if the directory exists.</returns>
internal bool DirectoryExists(string path)
{
if (IndexOfFirstMatchingDirectory(path, _fileSet1) != -1)
{
return true;
}
if (IndexOfFirstMatchingDirectory(path, _fileSet2) != -1)
{
return true;
}
if (IndexOfFirstMatchingDirectory(path, _fileSet3) != -1)
{
return true;
}
return false;
}
}
/// <summary>
/// A general purpose method used to:
///
/// (1) Simulate a file system.
/// (2) Check whether all matchingFiles where hit by the filespec pattern.
/// (3) Check whether all nonmatchingFiles were *not* hit by the filespec pattern.
/// (4) Check whether all untouchableFiles were not even requested (usually for perf reasons).
///
/// These can be used in various combinations to test the filematcher framework.
/// </summary>
/// <param name="filespec">A FileMatcher filespec, possibly with wildcards.</param>
/// <param name="matchingFiles">Files that exist and should be matched.</param>
/// <param name="nonmatchingFiles">Files that exists and should not be matched.</param>
/// <param name="untouchableFiles">Files that exist but should not be requested.</param>
private static void MatchDriver
(
string filespec,
string[] matchingFiles,
string[] nonmatchingFiles,
string[] untouchableFiles
)
{
MatchDriver(filespec, null, matchingFiles, nonmatchingFiles, untouchableFiles);
}
/// <summary>
/// Runs the test 4 times with the include and exclude using either forward or backward slashes.
/// Expects the <param name="filespec"></param> and <param name="excludeFileSpects"></param> to contain only backward slashes
///
/// To preserve current MSBuild behaviour, it only does so if the path is not rooted. Rooted paths do not support forward slashes (as observed on MSBuild 14.0.25420.1)
/// </summary>
private static void MatchDriverWithDifferentSlashes
(
string filespec,
string[] excludeFilespecs,
string[] matchingFiles,
string[] nonmatchingFiles,
string[] untouchableFiles
)
{
// tests should call this method with backward slashes
Assert.DoesNotContain(filespec, "/");
foreach (var excludeFilespec in excludeFilespecs)
{
Assert.DoesNotContain(excludeFilespec, "/");
}
var forwardSlashFileSpec = Helpers.ToForwardSlash(filespec);
var forwardSlashExcludeSpecs = excludeFilespecs.Select(Helpers.ToForwardSlash).ToArray();
MatchDriver(filespec, excludeFilespecs, matchingFiles, nonmatchingFiles, untouchableFiles);
MatchDriver(filespec, forwardSlashExcludeSpecs, matchingFiles, nonmatchingFiles, untouchableFiles);
MatchDriver(forwardSlashFileSpec, excludeFilespecs, matchingFiles, nonmatchingFiles, untouchableFiles);
MatchDriver(forwardSlashFileSpec, forwardSlashExcludeSpecs, matchingFiles, nonmatchingFiles, untouchableFiles);
}
private static void MatchDriver(string filespec, string[] excludeFilespecs, string[] matchingFiles, string[] nonmatchingFiles, string[] untouchableFiles, bool normalizeAllPaths = true, bool normalizeExpectedMatchingFiles = false)
{
MockFileSystem mockFileSystem = new MockFileSystem(matchingFiles, nonmatchingFiles, untouchableFiles);
var fileMatcher = new FileMatcher(new FileSystemAdapter(mockFileSystem), mockFileSystem.GetAccessibleFileSystemEntries);
string[] files = fileMatcher.GetFiles
(
String.Empty, /* we don't need project directory as we use mock filesystem */
filespec,
excludeFilespecs?.ToList()
);
Func<string[], string[]> normalizeAllFunc = (paths => normalizeAllPaths ? paths.Select(MockFileSystem.Normalize).ToArray() : paths);
Func<string[], string[]> normalizeMatching = (paths => normalizeExpectedMatchingFiles ? paths.Select(MockFileSystem.Normalize).ToArray() : paths);
string[] normalizedFiles = normalizeAllFunc(files);
// Validate the matching files.
if (matchingFiles != null)
{
string[] normalizedMatchingFiles = normalizeAllFunc(normalizeMatching(matchingFiles));
foreach (string matchingFile in normalizedMatchingFiles)
{
int timesFound = 0;
foreach (string file in normalizedFiles)
{
if (String.Compare(file, matchingFile, StringComparison.OrdinalIgnoreCase) == 0)
{
++timesFound;
}
}
Assert.Equal(1, timesFound);
}
}
// Validate the non-matching files
if (nonmatchingFiles != null)
{
string[] normalizedNonMatchingFiles = normalizeAllFunc(nonmatchingFiles);
foreach (string nonmatchingFile in normalizedNonMatchingFiles)
{
int timesFound = 0;
foreach (string file in normalizedFiles)
{
if (String.Compare(file, nonmatchingFile, StringComparison.OrdinalIgnoreCase) == 0)
{
++timesFound;
}
}
Assert.Equal(0, timesFound);
}
}
// Check untouchable files.
Assert.Equal(0, mockFileSystem.FileHits3); // "At least one file that was marked untouchable was referenced."
}
/// <summary>
/// Simulate GetFileSystemEntries
/// </summary>
/// <param name="path"></param>
/// <param name="pattern"></param>
/// <returns>Array of matching file system entries (can be empty).</returns>
private static ImmutableArray<string> GetFileSystemEntriesLoopBack(FileMatcher.FileSystemEntity entityType, string path, string pattern, string projectDirectory, bool stripProjectDirectory)
{
return ImmutableArray.Create(Path.Combine(path, pattern));
}
/*************************************************************************************
* Validate that SplitFileSpec(...) is returning the expected constituent values.
*************************************************************************************/
private static FileMatcher loopBackFileMatcher = new FileMatcher(FileSystems.Default, GetFileSystemEntriesLoopBack);
private static void ValidateSplitFileSpec
(
string filespec,
string expectedFixedDirectoryPart,
string expectedWildcardDirectoryPart,
string expectedFilenamePart
)
{
string fixedDirectoryPart;
string wildcardDirectoryPart;
string filenamePart;
loopBackFileMatcher.SplitFileSpec
(
filespec,
out fixedDirectoryPart,
out wildcardDirectoryPart,
out filenamePart
);
expectedFixedDirectoryPart = FileUtilities.FixFilePath(expectedFixedDirectoryPart);
expectedWildcardDirectoryPart = FileUtilities.FixFilePath(expectedWildcardDirectoryPart);
expectedFilenamePart = FileUtilities.FixFilePath(expectedFilenamePart);
if
(
expectedWildcardDirectoryPart != wildcardDirectoryPart
|| expectedFixedDirectoryPart != fixedDirectoryPart
|| expectedFilenamePart != filenamePart
)
{
Console.WriteLine("Expect Fixed '{0}' got '{1}'", expectedFixedDirectoryPart, fixedDirectoryPart);
Console.WriteLine("Expect Wildcard '{0}' got '{1}'", expectedWildcardDirectoryPart, wildcardDirectoryPart);
Console.WriteLine("Expect Filename '{0}' got '{1}'", expectedFilenamePart, filenamePart);
Assert.True(false, "FileMatcher Regression: Failure while validating SplitFileSpec.");
}
}
/*************************************************************************************
* Given a pattern (filespec) and a candidate filename (fileToMatch). Verify that they
* do indeed match.
*************************************************************************************/
private static void ValidateFileMatch
(
string filespec,
string fileToMatch,
bool shouldBeRecursive
)
{
ValidateFileMatch(filespec, fileToMatch, shouldBeRecursive, /* Simulate filesystem? */ true);
}
/*************************************************************************************
* Given a pattern (filespec) and a candidate filename (fileToMatch). Verify that they
* do indeed match.
*************************************************************************************/
private static void ValidateFileMatch
(
string filespec,
string fileToMatch,
bool shouldBeRecursive,
bool fileSystemSimulation
)
{
if (!IsFileMatchAssertIfIllegal(filespec, fileToMatch, shouldBeRecursive))
{
Assert.True(false, "FileMatcher Regression: Failure while validating that files match.");
}
// Now, simulate a filesystem with only fileToMatch. Make sure the file exists that way.
if (fileSystemSimulation)
{
MatchDriver
(
filespec,
new string[] { fileToMatch },
null,
null
);
}
}
/*************************************************************************************
* Given a pattern (filespec) and a candidate filename (fileToMatch). Verify that they
* DON'T match.
*************************************************************************************/
private static void ValidateNoFileMatch
(
string filespec,
string fileToMatch,
bool shouldBeRecursive
)
{
if (IsFileMatchAssertIfIllegal(filespec, fileToMatch, shouldBeRecursive))
{
Assert.True(false, "FileMatcher Regression: Failure while validating that files don't match.");
}
// Now, simulate a filesystem with only fileToMatch. Make sure the file doesn't exist that way.
MatchDriver
(
filespec,
null,
new string[] { fileToMatch },
null
);
}
/*************************************************************************************
* Verify that the given filespec is illegal.
*************************************************************************************/
private static void ValidateIllegal
(
string filespec
)
{
Regex regexFileMatch;
bool needsRecursion;
bool isLegalFileSpec;
loopBackFileMatcher.GetFileSpecInfoWithRegexObject
(
filespec,
out regexFileMatch,
out needsRecursion,
out isLegalFileSpec
);
if (isLegalFileSpec)
{
Assert.True(false, "FileMatcher Regression: Expected an illegal filespec, but got a legal one.");
}
// Now, FileMatcher is supposed to take any legal file name and just return it immediately.
// Let's see if it does.
MatchDriver
(
filespec, // Not legal.
new string[] { filespec }, // Should match
null,
null
);
}
/*************************************************************************************
* Given a pattern (filespec) and a candidate filename (fileToMatch) return true if
* FileMatcher would say that they match.
*************************************************************************************/
private static bool IsFileMatchAssertIfIllegal
(
string filespec,
string fileToMatch,
bool shouldBeRecursive
)
{
FileMatcher.Result match = FileMatcher.Default.FileMatch(filespec, fileToMatch);
if (!match.isLegalFileSpec)
{
Console.WriteLine("Checking FileSpec: '{0}' against '{1}'", filespec, fileToMatch);
Assert.True(false, "FileMatcher Regression: Invalid filespec.");
}
if (shouldBeRecursive != match.isFileSpecRecursive)
{
Console.WriteLine("Checking FileSpec: '{0}' against '{1}'", filespec, fileToMatch);
Assert.True(shouldBeRecursive); // "FileMatcher Regression: Match was recursive when it shouldn't be."
Assert.False(shouldBeRecursive); // "FileMatcher Regression: Match was not recursive when it should have been."
}
return match.isMatch;
}
#endregion
private class FileSystemAdapter : IFileSystem
{
private readonly MockFileSystem _mockFileSystem;
public FileSystemAdapter(MockFileSystem mockFileSystem)
{
_mockFileSystem = mockFileSystem;
}
public IEnumerable<string> EnumerateFiles(string path, string searchPattern = "*", SearchOption searchOption = SearchOption.TopDirectoryOnly)
{
return FileSystems.Default.EnumerateFiles(path, searchPattern, searchOption);
}
public IEnumerable<string> EnumerateDirectories(string path, string searchPattern = "*", SearchOption searchOption = SearchOption.TopDirectoryOnly)
{
return FileSystems.Default.EnumerateDirectories(path, searchPattern, searchOption);
}
public IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern = "*", SearchOption searchOption = SearchOption.TopDirectoryOnly)
{
return FileSystems.Default.EnumerateFileSystemEntries(path, searchPattern, searchOption);
}
public bool DirectoryExists(string path)
{
return _mockFileSystem.DirectoryExists(path);
}
public bool FileExists(string path)
{
return FileSystems.Default.FileExists(path);
}
public bool DirectoryEntryExists(string path)
{
return FileSystems.Default.DirectoryEntryExists(path);
}
}
}
}
| 39.326348 | 237 | 0.466964 | [
"MIT"
] | AaronRobinsonMSFT/msbuild | src/Shared/UnitTests/FileMatcher_Tests.cs | 101,354 | C# |
namespace OneIdentity.DevOps.Data
{
/// <summary>
/// Plugin enabled/disabled state
/// </summary>
public class PluginState
{
/// <summary>
/// Is plugin disabled
/// </summary>
public bool Disabled { get; set; }
}
}
| 18.333333 | 42 | 0.530909 | [
"Apache-2.0"
] | LeeHoward1/SafeguardDevOpsService | SafeguardDevOpsService/Data/PluginState.cs | 277 | C# |
// Copyright (c) Alessandro Ghidini. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Threading;
namespace MudBlazor
{
public class Snackbar : IDisposable
{
private Timer Timer { get; }
internal State State { get; }
public string Message { get; }
public event Action<Snackbar> OnClose;
public event Action OnUpdate;
public SnackbarType Type => State.Options.Type;
internal Snackbar(string message, SnackbarOptions options)
{
Message = message;
State = new State(options);
Timer = new Timer(TimerElapsed, null, Timeout.Infinite, Timeout.Infinite);
}
internal void Init() => TransitionTo(SnackbarState.Showing);
internal void Clicked(bool fromCloseIcon)
{
if (!fromCloseIcon)
{
// Execute the click action only if it's not from the close icon
State.Options.Onclick?.Invoke(this);
// If the close icon is show do not start the hiding transition
if (State.Options.ShowCloseIcon) return;
}
State.UserHasInteracted = true;
TransitionTo(SnackbarState.Hiding);
}
private void TransitionTo(SnackbarState state)
{
StopTimer();
State.SnackbarState = state;
var options = State.Options;
if (state.IsShowing())
{
if (options.ShowTransitionDuration <= 0) TransitionTo(SnackbarState.Visible);
else StartTimer(options.ShowTransitionDuration);
}
else if (state.IsVisible() && !options.RequireInteraction)
{
if (options.VisibleStateDuration <= 0) TransitionTo(SnackbarState.Hiding);
else StartTimer(options.VisibleStateDuration);
}
else if (state.IsHiding())
{
if (options.HideTransitionDuration <= 0) OnClose?.Invoke(this);
else StartTimer(options.HideTransitionDuration);
}
OnUpdate?.Invoke();
}
private void TimerElapsed(object state)
{
switch (State.SnackbarState)
{
case SnackbarState.Showing:
TransitionTo(SnackbarState.Visible);
break;
case SnackbarState.Visible:
TransitionTo(SnackbarState.Hiding);
break;
case SnackbarState.Hiding:
OnClose?.Invoke(this);
break;
}
}
private void StartTimer(int duration)
{
State.TransitionStartTime = DateTime.Now;
Timer?.Change(duration, Timeout.Infinite);
}
private void StopTimer()
{
Timer?.Change(Timeout.Infinite, Timeout.Infinite);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposing) return;
StopTimer();
Timer.Dispose();
}
}
}
| 30.777778 | 95 | 0.547834 | [
"MIT"
] | Bimble/MudBlazor | src/MudBlazor/Components/Snackbar/Snackbar.cs | 3,326 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the robomaker-2018-06-29.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.RoboMaker.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.RoboMaker.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ListSimulationJobBatches operation
/// </summary>
public class ListSimulationJobBatchesResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
ListSimulationJobBatchesResponse response = new ListSimulationJobBatchesResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("nextToken", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.NextToken = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("simulationJobBatchSummaries", targetDepth))
{
var unmarshaller = new ListUnmarshaller<SimulationJobBatchSummary, SimulationJobBatchSummaryUnmarshaller>(SimulationJobBatchSummaryUnmarshaller.Instance);
response.SimulationJobBatchSummaries = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerException"))
{
return InternalServerExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterException"))
{
return InvalidParameterExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonRoboMakerException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static ListSimulationJobBatchesResponseUnmarshaller _instance = new ListSimulationJobBatchesResponseUnmarshaller();
internal static ListSimulationJobBatchesResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListSimulationJobBatchesResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 39.791667 | 192 | 0.653613 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/RoboMaker/Generated/Model/Internal/MarshallTransformations/ListSimulationJobBatchesResponseUnmarshaller.cs | 4,775 | C# |
namespace SKIT.FlurlHttpClient.Wechat.TenpayV3.Models
{
/// <summary>
/// <para>表示 [POST] /marketing/membercard-open/callback 接口的响应。</para>
/// </summary>
public class UpdateMarketingMemberCardOpenCallbackResponse : GetMarketingMemberCardOpenCallbackResponse
{
}
}
| 29 | 107 | 0.724138 | [
"MIT"
] | OrchesAdam/DotNetCore.SKIT.FlurlHttpClient.Wechat | src/SKIT.FlurlHttpClient.Wechat.TenpayV3/Models/MarketingMemberCardOpen/Callback/UpdateMarketingMemberCardOpenCallbackResponse.cs | 308 | C# |
using System.Net.Mime;
using Microsoft.Practices.ServiceLocation;
using FubuMVC.Core.Routing;
using FubuMVC.Core.View;
namespace FubuMVC.Core.Controller.Results
{
public class RenderViewResult<OUTPUT>: IInvocationResult
where OUTPUT : class
{
public const string HtmlContentType = MediaTypeNames.Text.Html;
private readonly OUTPUT _output;
public RenderViewResult(OUTPUT output)
{
_output = output;
}
public void Execute(IServiceLocator locator)
{
var renderer = locator.GetInstance<IViewRenderer>();
var writer = locator.GetInstance<IOutputWriter>();
var content = renderer.RenderView(_output);
writer.Write(HtmlContentType, content);
}
}
}
| 28.344828 | 72 | 0.632603 | [
"Apache-2.0"
] | dineshkummarc/FubuMVC-old | src/FubuMVC.Core/Controller/Results/RenderViewResult.cs | 822 | C# |
using Autofac;
using EventBus;
using EventBus.Abstractions;
using RabbitMQServiceBus;
using AzureEventBusServiceBus;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using RabbitMQ.Client;
using Microsoft.AspNetCore.Builder;
using EventBus.Events;
namespace EventBus.Extensions;
public static class ServiceCollectionExtensions
{
public static IApplicationBuilder ConfigServiceBus<TEvent, TEventHandler>(this IApplicationBuilder app)
where TEvent : IntegrationEvent
where TEventHandler : IIntegrationEventHandler<TEvent>
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
eventBus.Subscribe<TEvent, TEventHandler>();
return app;
}
public static IServiceCollection AddEventHandler(this IServiceCollection services)
{
services.Scan(selector =>
{
selector.FromCallingAssembly()
.AddClasses(x => x.AssignableTo(typeof(IIntegrationEventHandler<>)))
.AsSelf()
.WithTransientLifetime();
});
return services;
}
private static bool IsExistingEventBusService(IServiceCollection services)
{
// Get service provider from the provided IServiceCollection
IServiceProvider serviceProvider = services.BuildServiceProvider();
// Get EventBus
IEventBus eventBus = serviceProvider.GetService<IEventBus>();
return eventBus != null;
}
public static IServiceCollection AddAzureServiceBus(this IServiceCollection services, Action<AzureServiceBusSettings> busOpts)
{
if (services == null)
{
throw new ArgumentException(nameof(services));
}
services.Configure(busOpts);
if (IsExistingEventBusService(services))
{
return services;
}
services.AddSingleton<IServiceBusPersisterConnection>(sp =>
{
var settings = sp.GetRequiredService<IOptions<AzureServiceBusSettings>>().Value;
var serviceBusConnection = settings.EventBusConnection;
return new DefaultServiceBusPersisterConnection(serviceBusConnection);
});
services.AddSingleton<IEventBusSubscriptionsManager, InMemoryEventBusSubscriptionsManager>();
services.AddSingleton<IEventBus, EventBusServiceBus>(sp =>
{
var serviceBusPersisterConnection = sp.GetRequiredService<IServiceBusPersisterConnection>();
var iLifetimeScope = sp.GetRequiredService<ILifetimeScope>();
var logger = sp.GetRequiredService<ILogger<EventBusServiceBus>>();
var eventBusSubcriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>();
var settings = sp.GetRequiredService<IOptions<AzureServiceBusSettings>>().Value;
string subscriptionName = settings.SubscriptionClientName;
return new EventBusServiceBus(serviceBusPersisterConnection, logger,
eventBusSubcriptionsManager, iLifetimeScope, subscriptionName);
});
return services;
}
public static IServiceCollection AddRabbitMQServiceBus(this IServiceCollection services, Action<RabbitMQServiceBusSettings> busOpts)
{
services.Configure(busOpts);
if (IsExistingEventBusService(services))
{
return services;
}
services.AddSingleton<IRabbitMQPersistentConnection>(sp =>
{
var settings = sp.GetRequiredService<IOptions<RabbitMQServiceBusSettings>>().Value;
var logger = sp.GetRequiredService<ILogger<DefaultRabbitMQPersistentConnection>>();
var factory = new ConnectionFactory()
{
HostName = settings.EventBusConnection,
DispatchConsumersAsync = true
};
if (!string.IsNullOrEmpty(settings.EventBusUserName))
{
factory.UserName = settings.EventBusUserName;
}
if (!string.IsNullOrEmpty(settings.EventBusPassword))
{
factory.Password = settings.EventBusPassword;
}
var retryCount = 5;
if (!string.IsNullOrEmpty(settings.EventBusRetryCount))
{
retryCount = int.Parse(settings.EventBusRetryCount);
}
return new DefaultRabbitMQPersistentConnection(factory, logger, retryCount);
});
services.AddSingleton<IEventBusSubscriptionsManager, InMemoryEventBusSubscriptionsManager>();
services.AddSingleton<IEventBus, EventBusRabbitMQ>(sp =>
{
var settings = sp.GetRequiredService<IOptions<RabbitMQServiceBusSettings>>().Value;
var subscriptionClientName = settings.SubscriptionClientName;
var rabbitMQPersistentConnection = sp.GetRequiredService<IRabbitMQPersistentConnection>();
var iLifetimeScope = sp.GetRequiredService<ILifetimeScope>();
var logger = sp.GetRequiredService<ILogger<EventBusRabbitMQ>>();
var eventBusSubcriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>();
var retryCount = 5;
if (!string.IsNullOrEmpty(settings.EventBusRetryCount))
{
retryCount = int.Parse(settings.EventBusRetryCount);
}
return new EventBusRabbitMQ(rabbitMQPersistentConnection, logger, iLifetimeScope, eventBusSubcriptionsManager, subscriptionClientName, retryCount);
});
return services;
}
}
| 35.91358 | 159 | 0.678068 | [
"Apache-2.0"
] | vanluom123/EventBusMessage | EventBus/EventBusExtensions/ServiceCollectionExtensions.cs | 5,820 | 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/WebServices.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="WS_GUID_DESCRIPTION" /> struct.</summary>
public static unsafe class WS_GUID_DESCRIPTIONTests
{
/// <summary>Validates that the <see cref="WS_GUID_DESCRIPTION" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<WS_GUID_DESCRIPTION>(), Is.EqualTo(sizeof(WS_GUID_DESCRIPTION)));
}
/// <summary>Validates that the <see cref="WS_GUID_DESCRIPTION" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(WS_GUID_DESCRIPTION).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="WS_GUID_DESCRIPTION" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
Assert.That(sizeof(WS_GUID_DESCRIPTION), Is.EqualTo(16));
}
}
}
| 39.194444 | 145 | 0.676116 | [
"MIT"
] | phizch/terrafx.interop.windows | tests/Interop/Windows/um/WebServices/WS_GUID_DESCRIPTIONTests.cs | 1,413 | C# |
using AudioManager.Core;
using UnityEngine;
using UnityEngine.Audio;
namespace AudioManager.Helper {
public class AudioHelper {
public static void GetStepValueAndTime(float startValue, float endValue, float waitTime, float granularity, out float stepValue, out float stepTime) {
float difference = endValue - startValue;
stepValue = difference / granularity;
stepTime = waitTime / granularity;
}
public static AudioError LoadAudioClipFromPath(string path, out AudioClip clip) {
clip = Resources.Load<AudioClip>(path);
return clip ? AudioError.OK : AudioError.INVALID_PATH;
}
public static bool IsGranularityValid(int granularity) {
return granularity >= Constants.MIN_GRANULARITY;
}
public static void AttachAudioSource(out AudioSource newSource, GameObject newGameObject, AudioClip clip, AudioMixerGroup mixerGroup, bool loop, float volume, float pitch, float spatialBlend, float dopplerLevel, float spreadAngle, AudioRolloffMode rolloffMode, float minDistance, float maxDistance) {
AddAudioSourceComponent(newGameObject, out newSource);
newSource.CopyAudioSourceSettings(clip, mixerGroup, loop, volume, pitch, spatialBlend, dopplerLevel, spreadAngle, rolloffMode, minDistance, maxDistance);
}
public static void AddAudioSourceComponent(GameObject parent, out AudioSource source) {
source = parent.AddComponent<AudioSource>();
}
public static bool IsSound2D(float spatialBlend) {
return spatialBlend <= Constants.SPATIAL_BLEND_2D;
}
public static bool IsProgressValid(float progress) {
return progress <= Constants.MAX_PROGRESS;
}
public static bool IsEndValueValid(float startValue, float endValue) {
return startValue - endValue >= float.Epsilon || endValue - startValue >= float.Epsilon;
}
public static GameObject CreateNewGameObject(string name) {
return new GameObject(name);
}
public static Transform GetTransform(GameObject gameObject) {
return gameObject.transform;
}
public static void SetTransformParent(Transform child, Transform parent) {
child.SetParent(parent);
}
public static void SetTransformPosition(Transform transform, Vector3 position) {
transform.position = position;
}
}
}
| 41.716667 | 308 | 0.684778 | [
"MIT"
] | MathewHDYT/Unity-Audio-Manager | Example_Project/Assets/Scripts/AudioManager/Helper/AudioHelper.cs | 2,505 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Collections;
using System.Globalization;
using System.Web.UI;
namespace Havit.Web.UI.WebControls
{
/// <summary>
/// Vylepšený <see cref="DropDownList"/>.
/// Podporuje lepší zpracování hodnoty DataTextField při databindingu.
/// </summary>
public class ListBoxExt : ListBox
{
/// <summary>
/// Událost, která se volá po vytvoření itemu a jeho data-bindingu.
/// </summary>
public event EventHandler<ListControlItemDataBoundEventArgs> ItemDataBound
{
add
{
Events.AddHandler(eventItemDataBound, value);
}
remove
{
Events.RemoveHandler(eventItemDataBound, value);
}
}
private static readonly object eventItemDataBound = new object();
private int cachedSelectedIndex = -1;
private string cachedSelectedValue;
/// <summary>
/// Gets or sets the index of the selected item in the <see cref="T:System.Web.UI.WebControls.DropDownList"/> control.
/// </summary>
/// <value></value>
/// <returns>The index of the selected item in the <see cref="T:System.Web.UI.WebControls.DropDownList"/> control. The default value is 0, which selects the first item in the list.</returns>
public override int SelectedIndex
{
get
{
return base.SelectedIndex;
}
set
{
base.SelectedIndex = value;
cachedSelectedIndex = value;
}
}
/// <summary>
/// Gets the value of the selected item in the list control, or selects the item in the list control that contains the specified value.
/// </summary>
/// <value></value>
/// <returns>The value of the selected item in the list control. The default is an empty string ("").</returns>
public override string SelectedValue
{
get
{
return base.SelectedValue;
}
set
{
base.SelectedValue = value;
cachedSelectedValue = value;
}
}
/// <summary>
/// Gets or sets the field of the data source that provides the opting group content of the list items.
/// </summary>
public string DataOptionGroupField
{
get
{
return (string)(ViewState["DataOptionGroupField"] ?? String.Empty);
}
set
{
ViewState["DataOptionGroupField"] = value;
}
}
/// <summary>
/// Konstruktor. Nastavuje výchozí režim výběru na Multiple.
/// </summary>
public ListBoxExt()
{
SelectionMode = ListSelectionMode.Multiple;
}
/// <summary>
/// Binds the specified data source to the control that is derived from the <see cref="T:System.Web.UI.WebControls.ListControl"/> class.
/// </summary>
/// <param name="dataSource">An <see cref="T:System.Collections.IEnumerable"/> that represents the data source.</param>
protected override void PerformDataBinding(IEnumerable dataSource)
{
if (dataSource != null)
{
if (!this.AppendDataBoundItems)
{
this.Items.Clear();
}
ICollection @null = dataSource as ICollection;
if (@null != null)
{
this.Items.Capacity = @null.Count + this.Items.Count;
}
foreach (object dataItem in dataSource)
{
ListItem item = CreateItem(dataItem);
this.Items.Add(item);
OnItemDataBound(new ListControlItemDataBoundEventArgs(item, dataItem));
}
}
if (this.cachedSelectedValue != null)
{
int num = -1;
num = FindItemIndexByValue(this.Items, this.cachedSelectedValue);
if (-1 == num)
{
throw new InvalidOperationException("ListBoxEx neobsahuje hodnotu SelectedValue.");
}
if ((this.cachedSelectedIndex != -1) && (this.cachedSelectedIndex != num))
{
throw new ArgumentException("Hodnoty SelectedValue a SelectedIndex se navzájem vylučují.");
}
this.SelectedIndex = num;
this.cachedSelectedValue = null;
this.cachedSelectedIndex = -1;
}
else if (this.cachedSelectedIndex != -1)
{
this.SelectedIndex = this.cachedSelectedIndex;
this.cachedSelectedIndex = -1;
}
}
/// <summary>
/// Vytvoří ListItem, součást PerformDataBindingu.
/// </summary>
protected virtual ListItem CreateItem(object dataItem)
{
return ListControlExtensions.CreateListItem(dataItem, DataTextField, DataTextFormatString, DataValueField, String.Empty /* CheckBoxList nepoužívá OptionGroups */);
}
/// <summary>
/// Implementace nahrazující internal metody ListItemCollection.FindByValueInternal()
/// </summary>
/// <param name="listItemCollection">prohledávaná ListItemCollection</param>
/// <param name="value">hledaná hodnota</param>
private int FindItemIndexByValue(ListItemCollection listItemCollection, string value)
{
ListItem item = listItemCollection.FindByValue(value);
if (item != null)
{
return listItemCollection.IndexOf(item);
}
return -1;
}
/// <summary>
/// Raises the <see cref="ItemDataBound"/> event.
/// </summary>
/// <param name="e">The <see cref="Havit.Web.UI.WebControls.ListControlItemDataBoundEventArgs"/> instance containing the event data.</param>
protected virtual void OnItemDataBound(ListControlItemDataBoundEventArgs e)
{
EventHandler<ListControlItemDataBoundEventArgs> h = (EventHandler<ListControlItemDataBoundEventArgs>)Events[eventItemDataBound];
if (h != null)
{
h(this, e);
}
}
/// <summary>
/// Renderuje položky ListBoxu.
/// Podporuje option groups.
/// </summary>
protected override void RenderContents(HtmlTextWriter writer)
{
// no base call
ListControlExtensions.RenderContents(writer, this, this.Page, this.VerifyMultiSelect);
}
/// <summary>
/// Uloží viewstate. Persistuje Option Groups položek.
/// </summary>
protected override object SaveViewState()
{
return ListControlExtensions.SaveViewState(base.SaveViewState, this.Items);
}
/// <summary>
/// Načte viewstate vč. Option Groups položek.
/// </summary>
protected override void LoadViewState(object savedState)
{
ListControlExtensions.LoadViewState(savedState, base.LoadViewState, () => this.Items);
}
}
}
| 29.333333 | 192 | 0.694352 | [
"MIT"
] | havit/HavitFramework | Havit.Web/UI/WebControls/ListBoxExt.cs | 6,025 | 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("06. QuadraticEquation")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("06. QuadraticEquation")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8be9ff5c-e589-40d7-9db4-88860421ff6c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.243243 | 84 | 0.745583 | [
"MIT"
] | juvemar/Console-I-O | 06. QuadraticEquation/Properties/AssemblyInfo.cs | 1,418 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.VisualStudio.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Remote
{
/// <summary>
/// This class runs against the in-process workspace, and when it sees changes proactively pushes them to
/// the out-of-process workspace through the <see cref="IRemoteAssetSynchronizationService"/>.
/// </summary>
internal sealed class SolutionChecksumUpdater : GlobalOperationAwareIdleProcessor
{
private readonly Workspace _workspace;
private readonly TaskQueue _textChangeQueue;
private readonly AsyncQueue<IAsyncToken> _workQueue;
private readonly object _gate;
private CancellationTokenSource _globalOperationCancellationSource;
// hold the async token from WaitAsync so ExecuteAsync can complete it
private IAsyncToken _currentToken;
public SolutionChecksumUpdater(Workspace workspace, IGlobalOptionService globalOptions, IAsynchronousOperationListenerProvider listenerProvider, CancellationToken shutdownToken)
: base(listenerProvider.GetListener(FeatureAttribute.SolutionChecksumUpdater),
workspace.Services.GetService<IGlobalOperationNotificationService>(),
TimeSpan.FromMilliseconds(globalOptions.GetOption(RemoteHostOptions.SolutionChecksumMonitorBackOffTimeSpanInMS)), shutdownToken)
{
_workspace = workspace;
_textChangeQueue = new TaskQueue(Listener, TaskScheduler.Default);
_workQueue = new AsyncQueue<IAsyncToken>();
_gate = new object();
// start listening workspace change event
_workspace.WorkspaceChanged += OnWorkspaceChanged;
// create its own cancellation token source
_globalOperationCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(shutdownToken);
Start();
}
private CancellationToken ShutdownCancellationToken => CancellationToken;
protected override async Task ExecuteAsync()
{
lock (_gate)
{
Contract.ThrowIfNull(_currentToken);
_currentToken.Dispose();
_currentToken = null;
}
// wait for global operation to finish
await GlobalOperationTask.ConfigureAwait(false);
// update primary solution in remote host
await SynchronizePrimaryWorkspaceAsync(_globalOperationCancellationSource.Token).ConfigureAwait(false);
}
protected override void PauseOnGlobalOperation()
{
var previousCancellationSource = _globalOperationCancellationSource;
// create new cancellation token source linked with given shutdown cancellation token
_globalOperationCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(ShutdownCancellationToken);
CancelAndDispose(previousCancellationSource);
}
protected override async Task WaitAsync(CancellationToken cancellationToken)
{
var currentToken = await _workQueue.DequeueAsync(cancellationToken).ConfigureAwait(false);
lock (_gate)
{
Contract.ThrowIfFalse(_currentToken is null);
_currentToken = currentToken;
}
}
public override void Shutdown()
{
base.Shutdown();
// stop listening workspace change event
_workspace.WorkspaceChanged -= OnWorkspaceChanged;
CancelAndDispose(_globalOperationCancellationSource);
}
private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e)
{
if (e.Kind == WorkspaceChangeKind.DocumentChanged)
{
PushTextChanges(e.OldSolution.GetDocument(e.DocumentId), e.NewSolution.GetDocument(e.DocumentId));
}
// record that we are busy
UpdateLastAccessTime();
EnqueueChecksumUpdate();
}
private void EnqueueChecksumUpdate()
{
// event will raised sequencially. no concurrency on this handler
if (_workQueue.TryPeek(out _))
{
return;
}
_workQueue.Enqueue(Listener.BeginAsyncOperation(nameof(SolutionChecksumUpdater)));
}
private async Task SynchronizePrimaryWorkspaceAsync(CancellationToken cancellationToken)
{
var solution = _workspace.CurrentSolution;
var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
return;
}
using (Logger.LogBlock(FunctionId.SolutionChecksumUpdater_SynchronizePrimaryWorkspace, cancellationToken))
{
var checksum = await solution.State.GetChecksumAsync(cancellationToken).ConfigureAwait(false);
await client.TryInvokeAsync<IRemoteAssetSynchronizationService>(
solution,
(service, solution, cancellationToken) => service.SynchronizePrimaryWorkspaceAsync(solution, checksum, solution.WorkspaceVersion, cancellationToken),
cancellationToken).ConfigureAwait(false);
}
}
private static void CancelAndDispose(CancellationTokenSource cancellationSource)
{
// cancel running tasks
cancellationSource.Cancel();
// dispose cancellation token source
cancellationSource.Dispose();
}
private void PushTextChanges(Document oldDocument, Document newDocument)
{
// this pushes text changes to the remote side if it can.
// this is purely perf optimization. whether this pushing text change
// worked or not doesn't affect feature's functionality.
//
// this basically see whether it can cheaply find out text changes
// between 2 snapshots, if it can, it will send out that text changes to
// remote side.
//
// the remote side, once got the text change, will again see whether
// it can use that text change information without any high cost and
// create new snapshot from it.
//
// otherwise, it will do the normal behavior of getting full text from
// VS side. this optimization saves times we need to do full text
// synchronization for typing scenario.
if ((oldDocument.TryGetText(out var oldText) == false) ||
(newDocument.TryGetText(out var newText) == false))
{
// we only support case where text already exist
return;
}
// get text changes
var textChanges = newText.GetTextChanges(oldText);
if (textChanges.Count == 0)
{
// no changes
return;
}
// whole document case
if (textChanges.Count == 1 && textChanges[0].Span.Length == oldText.Length)
{
// no benefit here. pulling from remote host is more efficient
return;
}
// only cancelled when remote host gets shutdown
_textChangeQueue.ScheduleTask(nameof(PushTextChanges), async () =>
{
var client = await RemoteHostClient.TryGetClientAsync(_workspace, CancellationToken).ConfigureAwait(false);
if (client == null)
{
return;
}
var state = await oldDocument.State.GetStateChecksumsAsync(CancellationToken).ConfigureAwait(false);
await client.TryInvokeAsync<IRemoteAssetSynchronizationService>(
(service, cancellationToken) => service.SynchronizeTextAsync(oldDocument.Id, state.Text, textChanges, cancellationToken),
CancellationToken).ConfigureAwait(false);
}, CancellationToken);
}
}
}
| 40.32093 | 185 | 0.643096 | [
"MIT"
] | CyrusNajmabadi/roslyn | src/Workspaces/Remote/Core/SolutionChecksumUpdater.cs | 8,671 | C# |
//------------------------------------------------------------------------------
// <自动生成>
// 此代码由工具生成。
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </自动生成>
//------------------------------------------------------------------------------
namespace Ytg.ServerWeb.Views.UserGroup {
public partial class UserBonus {
/// <summary>
/// Head1 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlHead Head1;
/// <summary>
/// form2 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form2;
/// <summary>
/// dspan 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl dspan;
/// <summary>
/// liyer 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.WebControls.Literal liyer;
/// <summary>
/// lbUserType 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.WebControls.Label lbUserType;
/// <summary>
/// lbCode 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.WebControls.Label lbCode;
/// <summary>
/// lbNickName 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.WebControls.Label lbNickName;
/// <summary>
/// userrebate 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.WebControls.HiddenField userrebate;
/// <summary>
/// hidUserPlayType 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.WebControls.HiddenField hidUserPlayType;
/// <summary>
/// ltActions 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltActions;
/// <summary>
/// ltTBody 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltTBody;
}
}
| 27.73913 | 81 | 0.46489 | [
"Apache-2.0"
] | heqinghua/lottery-code-qq-814788821- | YtgProject/Ytg.Server/Views/UserGroup/UserBonus.aspx.designer.cs | 4,162 | C# |
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Antlr4.Runtime;
namespace RecShark.ExpressionEvaluator.Extensions
{
public static class ObjectExtensions
{
public static string Default { get; } = "";
public static double AsDouble(this object value, ParserRuleContext context = null)
{
return As(value, context, TryAsDouble);
}
public static bool AsBool(this object value, ParserRuleContext context = null)
{
return As(value, context, TryAsBool);
}
public static string AsString(this object value, ParserRuleContext context = null)
{
return As(value, context, TryAsString);
}
public static List<object> AsList(this object value, ParserRuleContext context = null)
{
return As(value, context, TryAsList);
}
private static T As<T>(object value, ParserRuleContext context, Func<object, (bool, T)> converter, [CallerMemberName] string method = "")
{
var (success, convertedValue) = converter(value);
if (success)
return convertedValue;
var contextMessage = context != null ? $" (for '{context.Start.InputStream}')" : string.Empty;
throw new EvaluationException($"Cannot convert '{value}' to {method.Substring(2).ToLower()}{contextMessage}");
}
private static (bool, double) TryAsDouble(object value)
{
switch (value)
{
case double doubleValue: return (true, doubleValue);
case int intValue: return (true, intValue);
case decimal decimalValue: return (true, decimal.ToDouble(decimalValue));
case string stringValue when stringValue == Default: return (true, 0);
}
return (false, default);
}
private static (bool, bool) TryAsBool(object value)
{
switch (value)
{
case bool boolValue: return (true, boolValue);
case string stringValue when stringValue == Default: return (true, false);
}
return (false, default);
}
private static (bool, string) TryAsString(object value)
{
switch (value)
{
case string stringValue: return (true, stringValue);
}
return (false, default);
}
private static (bool, List<object>) TryAsList(object value)
{
switch (value)
{
case List<object> list: return (true, list);
case string stringValue when stringValue == Default: return (true, new List<object>());
}
return (false, default);
}
}
} | 34.471264 | 145 | 0.543515 | [
"Apache-2.0"
] | KevinRecuerda/RecShark | src/ExpressionEvaluator/Extensions/ObjectExtensions.cs | 2,999 | C# |
using System;
using BizHawk.Emulation.Common;
using BizHawk.Emulation.Cores.Nintendo.GBHawk;
namespace BizHawk.Emulation.Cores.Nintendo.GBHawkLink
{
[Core(
"GBHawkLink",
"",
isPorted: false,
isReleased: true)]
[ServiceNotApplicable(typeof(IDriveLight))]
public partial class GBHawkLink : IEmulator, ISaveRam, IDebuggable, IStatable, IInputPollable, IRegionable, ILinkable,
ISettable<GBHawkLink.GBLinkSettings, GBHawkLink.GBLinkSyncSettings>
{
// we want to create two GBHawk instances that we will run concurrently
// maybe up to 4 eventually?
public GBHawk.GBHawk L;
public GBHawk.GBHawk R;
// if true, the link cable is currently connected
private bool _cableconnected = true;
// if true, the link cable toggle signal is currently asserted
private bool _cablediscosignal = false;
private bool do_r_next = false;
//[CoreConstructor("GB", "GBC")]
public GBHawkLink(CoreComm comm, GameInfo game_L, byte[] rom_L, GameInfo game_R, byte[] rom_R, /*string gameDbFn,*/ object settings, object syncSettings)
{
var ser = new BasicServiceProvider(this);
linkSettings = (GBLinkSettings)settings ?? new GBLinkSettings();
linkSyncSettings = (GBLinkSyncSettings)syncSettings ?? new GBLinkSyncSettings();
_controllerDeck = new GBHawkLinkControllerDeck(GBHawkLinkControllerDeck.DefaultControllerName, GBHawkLinkControllerDeck.DefaultControllerName);
CoreComm = comm;
var temp_set_L = new GBHawk.GBHawk.GBSettings();
var temp_set_R = new GBHawk.GBHawk.GBSettings();
var temp_sync_L = new GBHawk.GBHawk.GBSyncSettings();
var temp_sync_R = new GBHawk.GBHawk.GBSyncSettings();
temp_sync_L.ConsoleMode = linkSyncSettings.ConsoleMode_L;
temp_sync_R.ConsoleMode = linkSyncSettings.ConsoleMode_R;
temp_sync_L.DivInitialTime = linkSyncSettings.DivInitialTime_L;
temp_sync_R.DivInitialTime = linkSyncSettings.DivInitialTime_R;
temp_sync_L.RTCInitialTime = linkSyncSettings.RTCInitialTime_L;
temp_sync_R.RTCInitialTime = linkSyncSettings.RTCInitialTime_R;
L = new GBHawk.GBHawk(new CoreComm(comm.ShowMessage, comm.Notify) { CoreFileProvider = comm.CoreFileProvider },
game_L, rom_L, temp_set_L, temp_sync_L);
R = new GBHawk.GBHawk(new CoreComm(comm.ShowMessage, comm.Notify) { CoreFileProvider = comm.CoreFileProvider },
game_R, rom_R, temp_set_R, temp_sync_R);
ser.Register<IVideoProvider>(this);
ser.Register<ISoundProvider>(this);
_tracer = new TraceBuffer { Header = L.cpu.TraceHeader };
ser.Register<ITraceable>(_tracer);
ServiceProvider = ser;
SetupMemoryDomains();
HardReset();
}
public void HardReset()
{
L.HardReset();
R.HardReset();
}
public DisplayType Region => DisplayType.NTSC;
public int _frame = 0;
private readonly GBHawkLinkControllerDeck _controllerDeck;
private readonly ITraceable _tracer;
public bool LinkConnected
{
get { return _cableconnected; }
set { _cableconnected = value; }
}
private void ExecFetch(ushort addr)
{
MemoryCallbacks.CallExecutes(addr, "System Bus");
}
}
}
| 30.336634 | 155 | 0.754896 | [
"MIT"
] | Moliman/BizHawk | BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawkLink/GBHawkLink.cs | 3,066 | C# |
// Developed by Softeq Development Corporation
// http://www.softeq.com
using System;
using System.Diagnostics.CodeAnalysis;
using NSubstitute;
using Softeq.XToolkit.Common.Tests.WeakTests.Utils;
using Xunit;
namespace Softeq.XToolkit.Common.Tests.WeakTests.WeakGenericFuncTests
{
[SuppressMessage("ReSharper", "xUnit1026", Justification = "Generic parameters used just for test case generation")]
public partial class WeakGenericInstanceFuncTests
{
[Theory]
[MemberData(nameof(WeakDelegatesTestsDataProvider.WeakFuncInputOutputParameters), MemberType = typeof(WeakDelegatesTestsDataProvider))]
public void IsStatic_ReturnsFalse<TIn, TOut>(
TIn inputParameter,
TOut outputParameter)
{
var (_, weakFunc) = WeakDelegateCreator.CreateWeakDelegate(
() => new WeakDelegatesCallCounter(),
x => x.GetWeakInstanceFunc<TIn, TOut>());
Assert.False(weakFunc.IsStatic);
}
[Theory]
[MemberData(nameof(WeakDelegatesTestsDataProvider.WeakFuncInputOutputParameters), MemberType = typeof(WeakDelegatesTestsDataProvider))]
public void IsAlive_WithTargetReference_AfterGarbageCollection_ReturnsTrue<TIn, TOut>(
TIn inputParameter,
TOut outputParameter)
{
var (_, weakFunc) = WeakDelegateCreator.CreateWeakDelegate(
() => new WeakDelegatesCallCounter(),
x => x.GetWeakInstanceFunc<TIn, TOut>());
GC.Collect();
Assert.True(weakFunc.IsAlive);
}
[Theory]
[MemberData(nameof(WeakDelegatesTestsDataProvider.WeakFuncInputOutputParameters), MemberType = typeof(WeakDelegatesTestsDataProvider))]
public void Execute_WithTargetReference_AfterGarbageCollection_InvokesFunc<TIn, TOut>(
TIn inputParameter,
TOut outputParameter)
{
var callCounter = Substitute.For<ICallCounter>();
var (_, weakFunc) = WeakDelegateCreator.CreateWeakDelegate(
() => new WeakDelegatesCallCounter(callCounter),
x => x.GetWeakInstanceFunc<TIn, TOut>());
weakFunc.Execute(inputParameter);
callCounter.Received(1).OnFuncCalled<TIn, TOut>(inputParameter);
}
[Theory]
[MemberData(nameof(WeakDelegatesTestsDataProvider.WeakFuncInputOutputParameters), MemberType = typeof(WeakDelegatesTestsDataProvider))]
public void IsAlive_WithoutTargetReference_AfterGarbageCollection_ReturnsFalse<TIn, TOut>(
TIn inputParameter,
TOut outputParameter)
{
var (reference, weakFunc) = WeakDelegateCreator.CreateWeakDelegate(
() => new WeakDelegatesCallCounter(),
x => x.GetWeakInstanceFunc<TIn, TOut>());
reference.Dispose();
GC.Collect();
Assert.False(weakFunc.IsAlive);
}
[Theory]
[MemberData(nameof(WeakDelegatesTestsDataProvider.WeakFuncInputOutputParameters), MemberType = typeof(WeakDelegatesTestsDataProvider))]
public void Execute_WithoutTargetReference_AfterGarbageCollection_DoesNotInvokeFunc<TIn, TOut>(
TIn inputParameter,
TOut outputParameter)
{
var callCounter = Substitute.For<ICallCounter>();
var (reference, weakFunc) = WeakDelegateCreator.CreateWeakDelegate(
() => new WeakDelegatesCallCounter(callCounter),
x => x.GetWeakInstanceFunc<TIn, TOut>());
reference.Dispose();
GC.Collect();
weakFunc.Execute(inputParameter);
callCounter.DidNotReceive().OnFuncCalled<TIn, TOut>(Arg.Any<TIn>());
}
[Theory]
[MemberData(nameof(WeakDelegatesTestsDataProvider.WeakFuncInputOutputParameters), MemberType = typeof(WeakDelegatesTestsDataProvider))]
public void IsAlive_WhenMarkedForDeletion_ReturnsFalse<TIn, TOut>(
TIn inputParameter,
TOut outputParameter)
{
var (_, weakFunc) = WeakDelegateCreator.CreateWeakDelegate(
() => new WeakDelegatesCallCounter(),
x => x.GetWeakInstanceFunc<TIn, TOut>());
weakFunc.MarkForDeletion();
Assert.False(weakFunc.IsAlive);
}
[Theory]
[MemberData(nameof(WeakDelegatesTestsDataProvider.WeakFuncInputOutputParameters), MemberType = typeof(WeakDelegatesTestsDataProvider))]
public void Execute_WhenMarkedForDeletion_DoesNotInvokeAction<TIn, TOut>(
TIn inputParameter,
TOut outputParameter)
{
var callCounter = Substitute.For<ICallCounter>();
var (_, weakFunc) = WeakDelegateCreator.CreateWeakDelegate(
() => new WeakDelegatesCallCounter(callCounter),
x => x.GetWeakInstanceFunc<TIn, TOut>());
weakFunc.MarkForDeletion();
weakFunc.Execute(inputParameter);
callCounter.DidNotReceive().OnActionCalled();
}
}
}
| 40.173228 | 143 | 0.654057 | [
"MIT"
] | Softeq/XToolkit.WhiteLabel | Softeq.XToolkit.Common.Tests/WeakTests/WeakGenericFuncTests/WeakGenericInstanceFuncTests.cs | 5,102 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WS_CoreServices.Domain
{
public class SmallRolePerson
{
public int RoleID;
public int PersonID;
public SmallRolePerson(int roleID, int personID) {
this.RoleID = roleID;
this.PersonID = personID;
}
}
} | 20.333333 | 58 | 0.639344 | [
"MIT"
] | EdutechSRL/Adevico | 3-Business/4-Services/WebService/WS_CoreServices/Domain/SmallRolePerson.cs | 368 | C# |
using System.Collections.Generic;
using Goals.Shared.Exceptions;
namespace Goals.Models.RequestResponse
{
public abstract class ProcessingResult
{
protected ProcessingResult()
{
Success = true;
Messages = new List<string>();
ProcessingException = new ModelProcessingException();
}
public List<string> Messages { get; set; }
public bool Success { get; set; }
public ModelProcessingException ProcessingException { get; set; }
public void AddMessage(string message, string propName = "")
{
Messages.Add(message);
if (string.IsNullOrWhiteSpace(propName))
{
ProcessingException.GeneralErrors.Add(message);
}
else
{
ProcessingException.AddPropertyError(propName, message);
}
}
}
public class CreateGoalResult : ProcessingResult
{
public Goal Goal { get; set; }
public CreateGoalRequest Request { get; set; }
}
} | 27.769231 | 73 | 0.581717 | [
"MIT"
] | twistedtwig/TrackMyProgress | Goal.Models/RequestResponse/ProcessingResult.cs | 1,085 | C# |
using Harpoon.Background;
using Harpoon.Registrations.EFStorage;
using Harpoon.Tests.Fixtures;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace Harpoon.Tests
{
public class BackgroundSenderTests : IClassFixture<BackgroundSenderFixture>
{
private readonly BackgroundSenderFixture _fixture;
public BackgroundSenderTests(BackgroundSenderFixture fixture)
{
_fixture = fixture;
}
[Fact]
public async Task ArgNullAsync()
{
Assert.Throws<ArgumentNullException>(() => new BackgroundSender(null));
var service = new BackgroundSender(new BackgroundQueue<IWebHookWorkItem>());
await Assert.ThrowsAsync<ArgumentNullException>(() => service.SendAsync(null, CancellationToken.None));
}
[Fact]
public async Task NormalAsync()
{
var queue = new BackgroundQueue<IWebHookWorkItem>();
var service = new BackgroundSender(queue);
var count = 0;
await service.SendAsync(new WebHookWorkItem(Guid.NewGuid(), new WebHookNotification(), new WebHook()), CancellationToken.None);
await queue.DequeueAsync(CancellationToken.None).ContinueWith(t => count++);
Assert.Equal(1, count);
}
[Fact]
public async Task NormalWithHostedServiceAsync()
{
var service = new BackgroundSender(_fixture.Services.GetRequiredService<BackgroundQueue<IWebHookWorkItem>>());
await service.SendAsync(new WebHookWorkItem(Guid.NewGuid(), new WebHookNotification(), new WebHook()), CancellationToken.None);
await Task.Delay(10000);
Assert.Equal(1, BackgroundSenderFixture.FakeWebHookSenderCount);
}
}
} | 35.653846 | 139 | 0.6726 | [
"Unlicense"
] | youngcm2/Harpoon | Harpoon.Tests/BackgroundSenderTests.cs | 1,856 | 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.
using System.Runtime.InteropServices;
namespace TerraFX.Interop
{
[Guid("3051058A-98B5-11CF-BB82-00AA00BDCE0B")]
public partial struct SVGAnimatedNumberList
{
}
}
| 31 | 145 | 0.754839 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | sources/Interop/Windows/um/MsHTML/SVGAnimatedNumberList.cs | 467 | C# |
namespace DotNetty.Suite.Tests.Transport.Socket
{
using System.Collections.Generic;
using System.Net;
using DotNetty.Buffers;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using Xunit.Abstractions;
public abstract class AbstractClientSocketTest : AbstractClientTestsuiteTest
{
public AbstractClientSocketTest(ITestOutputHelper output)
: base(output)
{
}
public static IEnumerable<object[]> GetAllocators()
{
foreach (var item in SocketTestPermutation.Allocators)
{
yield return new[] { item };
}
}
protected override void Configure(Bootstrap cb, IByteBufferAllocator allocator)
{
cb.Option(ChannelOption.Allocator, allocator);
}
protected IPEndPoint NewSocketAddress()
{
return new IPEndPoint(IPAddress.IPv6Loopback, 0);
}
}
}
| 27.25 | 87 | 0.62895 | [
"MIT"
] | cuteant/SpanNetty | test/DotNetty.Suite.Tests/Transport/Socket/AbstractClientSocketTest.cs | 983 | C# |
using System.ComponentModel.DataAnnotations;
namespace EmployeeService.Domain.Location
{
public class State
{
[Key]
public string Id { get; set; }
public string StateCode { get; set; }
public string StateName { get; set; }
public Country Country { get; set; }
//public int CountryId { get; set; }
//public virtual List<City> Cities { get; set; }
}
} | 27.933333 | 56 | 0.606205 | [
"MIT"
] | Matozap/Employee-Microservice | EmployeeService.Domain/Location/State.cs | 421 | C# |
namespace Uintra.Features.Search
{
public static class SearchConstants
{
public static readonly string AttachmentsPipelineName = "attachments";
public static class Global
{
public const int FragmentSize = 100; // depends on elastic fragment_size setting for highlighting (by default 100)
public const string HighlightPreTag = "<em style='background:#ffffc0'>";
public const string HighlightPostTag = "</em>";
}
public static class SearchFacetNames
{
public const string Types = "types";
public const string GlobalFilter = "GlobalFilter";
}
public static class AutocompleteType
{
public const string All = "All";
}
}
}
| 29.148148 | 126 | 0.613723 | [
"MIT"
] | Uintra/Uintra | src/Uintra/Features/Search/SearchConstants.cs | 789 | 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 sms-2016-10-24.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.ServerMigrationService.Model
{
/// <summary>
/// Represents a replication run.
/// </summary>
public partial class ReplicationRun
{
private string _amiId;
private DateTime? _completedTime;
private string _description;
private bool? _encrypted;
private string _kmsKeyId;
private string _replicationRunId;
private DateTime? _scheduledStartTime;
private ReplicationRunStageDetails _stageDetails;
private ReplicationRunState _state;
private string _statusMessage;
private ReplicationRunType _type;
/// <summary>
/// Gets and sets the property AmiId.
/// <para>
/// The identifier of the Amazon Machine Image (AMI) from the replication run.
/// </para>
/// </summary>
public string AmiId
{
get { return this._amiId; }
set { this._amiId = value; }
}
// Check to see if AmiId property is set
internal bool IsSetAmiId()
{
return this._amiId != null;
}
/// <summary>
/// Gets and sets the property CompletedTime.
/// <para>
/// The completion time of the last replication run.
/// </para>
/// </summary>
public DateTime CompletedTime
{
get { return this._completedTime.GetValueOrDefault(); }
set { this._completedTime = value; }
}
// Check to see if CompletedTime property is set
internal bool IsSetCompletedTime()
{
return this._completedTime.HasValue;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// The description of the replication run.
/// </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 Encrypted.
/// <para>
/// Whether the replication run should produce encrypted AMI or not. See also <code>KmsKeyId</code>
/// below.
/// </para>
/// </summary>
public bool Encrypted
{
get { return this._encrypted.GetValueOrDefault(); }
set { this._encrypted = value; }
}
// Check to see if Encrypted property is set
internal bool IsSetEncrypted()
{
return this._encrypted.HasValue;
}
/// <summary>
/// Gets and sets the property KmsKeyId.
/// <para>
/// KMS key ID for replication jobs that produce encrypted AMIs. Can be any of the following:
///
/// </para>
/// <ul> <li>
/// <para>
/// KMS key ID
/// </para>
/// </li> <li>
/// <para>
/// KMS key alias
/// </para>
/// </li> <li>
/// <para>
/// ARN referring to KMS key ID
/// </para>
/// </li> <li>
/// <para>
/// ARN referring to KMS key alias
/// </para>
/// </li> </ul>
/// <para>
/// If encrypted is <i>true</i> but a KMS key id is not specified, the customer's default
/// KMS key for EBS is used.
/// </para>
/// </summary>
public string KmsKeyId
{
get { return this._kmsKeyId; }
set { this._kmsKeyId = value; }
}
// Check to see if KmsKeyId property is set
internal bool IsSetKmsKeyId()
{
return this._kmsKeyId != null;
}
/// <summary>
/// Gets and sets the property ReplicationRunId.
/// <para>
/// The identifier of the replication run.
/// </para>
/// </summary>
public string ReplicationRunId
{
get { return this._replicationRunId; }
set { this._replicationRunId = value; }
}
// Check to see if ReplicationRunId property is set
internal bool IsSetReplicationRunId()
{
return this._replicationRunId != null;
}
/// <summary>
/// Gets and sets the property ScheduledStartTime.
/// <para>
/// The start time of the next replication run.
/// </para>
/// </summary>
public DateTime ScheduledStartTime
{
get { return this._scheduledStartTime.GetValueOrDefault(); }
set { this._scheduledStartTime = value; }
}
// Check to see if ScheduledStartTime property is set
internal bool IsSetScheduledStartTime()
{
return this._scheduledStartTime.HasValue;
}
/// <summary>
/// Gets and sets the property StageDetails.
/// <para>
/// Details of the current stage of the replication run.
/// </para>
/// </summary>
public ReplicationRunStageDetails StageDetails
{
get { return this._stageDetails; }
set { this._stageDetails = value; }
}
// Check to see if StageDetails property is set
internal bool IsSetStageDetails()
{
return this._stageDetails != null;
}
/// <summary>
/// Gets and sets the property State.
/// <para>
/// The state of the replication run.
/// </para>
/// </summary>
public ReplicationRunState State
{
get { return this._state; }
set { this._state = value; }
}
// Check to see if State property is set
internal bool IsSetState()
{
return this._state != null;
}
/// <summary>
/// Gets and sets the property StatusMessage.
/// <para>
/// The description of the current status of the replication job.
/// </para>
/// </summary>
public string StatusMessage
{
get { return this._statusMessage; }
set { this._statusMessage = value; }
}
// Check to see if StatusMessage property is set
internal bool IsSetStatusMessage()
{
return this._statusMessage != null;
}
/// <summary>
/// Gets and sets the property Type.
/// <para>
/// The type of replication run.
/// </para>
/// </summary>
public ReplicationRunType Type
{
get { return this._type; }
set { this._type = value; }
}
// Check to see if Type property is set
internal bool IsSetType()
{
return this._type != null;
}
}
} | 29.189591 | 107 | 0.538462 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/ServerMigrationService/Generated/Model/ReplicationRun.cs | 7,852 | C# |
using System;
using System.Runtime.InteropServices;
namespace FFmpeg.AutoGen
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate string AVClass_item_name (void* @ctx);
public unsafe struct AVClass_item_name_func
{
public IntPtr Pointer;
public static implicit operator AVClass_item_name_func(AVClass_item_name func) => new AVClass_item_name_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void* AVClass_child_next (void* @obj, void* @prev);
public unsafe struct AVClass_child_next_func
{
public IntPtr Pointer;
public static implicit operator AVClass_child_next_func(AVClass_child_next func) => new AVClass_child_next_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate AVClass* AVClass_child_class_next (AVClass* @prev);
public unsafe struct AVClass_child_class_next_func
{
public IntPtr Pointer;
public static implicit operator AVClass_child_class_next_func(AVClass_child_class_next func) => new AVClass_child_class_next_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate AVClassCategory AVClass_get_category (void* @ctx);
public unsafe struct AVClass_get_category_func
{
public IntPtr Pointer;
public static implicit operator AVClass_get_category_func(AVClass_get_category func) => new AVClass_get_category_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVClass_query_ranges (AVOptionRanges** @p0, void* @obj, [MarshalAs(UnmanagedType.LPStr)] string @key, int @flags);
public unsafe struct AVClass_query_ranges_func
{
public IntPtr Pointer;
public static implicit operator AVClass_query_ranges_func(AVClass_query_ranges func) => new AVClass_query_ranges_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void av_fifo_generic_peek_at_func (void* @p0, void* @p1, int @p2);
public unsafe struct av_fifo_generic_peek_at_func_func
{
public IntPtr Pointer;
public static implicit operator av_fifo_generic_peek_at_func_func(av_fifo_generic_peek_at_func func) => new av_fifo_generic_peek_at_func_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void av_fifo_generic_peek_func (void* @p0, void* @p1, int @p2);
public unsafe struct av_fifo_generic_peek_func_func
{
public IntPtr Pointer;
public static implicit operator av_fifo_generic_peek_func_func(av_fifo_generic_peek_func func) => new av_fifo_generic_peek_func_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void av_fifo_generic_read_func (void* @p0, void* @p1, int @p2);
public unsafe struct av_fifo_generic_read_func_func
{
public IntPtr Pointer;
public static implicit operator av_fifo_generic_read_func_func(av_fifo_generic_read_func func) => new av_fifo_generic_read_func_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int av_fifo_generic_write_func (void* @p0, void* @p1, int @p2);
public unsafe struct av_fifo_generic_write_func_func
{
public IntPtr Pointer;
public static implicit operator av_fifo_generic_write_func_func(av_fifo_generic_write_func func) => new av_fifo_generic_write_func_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void AVHWDeviceContext_free (AVHWDeviceContext* @ctx);
public unsafe struct AVHWDeviceContext_free_func
{
public IntPtr Pointer;
public static implicit operator AVHWDeviceContext_free_func(AVHWDeviceContext_free func) => new AVHWDeviceContext_free_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void AVHWFramesContext_free (AVHWFramesContext* @ctx);
public unsafe struct AVHWFramesContext_free_func
{
public IntPtr Pointer;
public static implicit operator AVHWFramesContext_free_func(AVHWFramesContext_free func) => new AVHWFramesContext_free_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVCodec_init_thread_copy (AVCodecContext* @p0);
public unsafe struct AVCodec_init_thread_copy_func
{
public IntPtr Pointer;
public static implicit operator AVCodec_init_thread_copy_func(AVCodec_init_thread_copy func) => new AVCodec_init_thread_copy_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVCodec_update_thread_context (AVCodecContext* @dst, AVCodecContext* @src);
public unsafe struct AVCodec_update_thread_context_func
{
public IntPtr Pointer;
public static implicit operator AVCodec_update_thread_context_func(AVCodec_update_thread_context func) => new AVCodec_update_thread_context_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void AVCodec_init_static_data (AVCodec* @codec);
public unsafe struct AVCodec_init_static_data_func
{
public IntPtr Pointer;
public static implicit operator AVCodec_init_static_data_func(AVCodec_init_static_data func) => new AVCodec_init_static_data_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVCodec_init (AVCodecContext* @p0);
public unsafe struct AVCodec_init_func
{
public IntPtr Pointer;
public static implicit operator AVCodec_init_func(AVCodec_init func) => new AVCodec_init_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVCodec_encode_sub (AVCodecContext* @p0, byte* @buf, int @buf_size, AVSubtitle* @sub);
public unsafe struct AVCodec_encode_sub_func
{
public IntPtr Pointer;
public static implicit operator AVCodec_encode_sub_func(AVCodec_encode_sub func) => new AVCodec_encode_sub_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVCodec_encode2 (AVCodecContext* @avctx, AVPacket* @avpkt, AVFrame* @frame, int* @got_packet_ptr);
public unsafe struct AVCodec_encode2_func
{
public IntPtr Pointer;
public static implicit operator AVCodec_encode2_func(AVCodec_encode2 func) => new AVCodec_encode2_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVCodec_decode (AVCodecContext* @p0, void* @outdata, int* @outdata_size, AVPacket* @avpkt);
public unsafe struct AVCodec_decode_func
{
public IntPtr Pointer;
public static implicit operator AVCodec_decode_func(AVCodec_decode func) => new AVCodec_decode_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVCodec_close (AVCodecContext* @p0);
public unsafe struct AVCodec_close_func
{
public IntPtr Pointer;
public static implicit operator AVCodec_close_func(AVCodec_close func) => new AVCodec_close_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVCodec_send_frame (AVCodecContext* @avctx, AVFrame* @frame);
public unsafe struct AVCodec_send_frame_func
{
public IntPtr Pointer;
public static implicit operator AVCodec_send_frame_func(AVCodec_send_frame func) => new AVCodec_send_frame_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVCodec_receive_packet (AVCodecContext* @avctx, AVPacket* @avpkt);
public unsafe struct AVCodec_receive_packet_func
{
public IntPtr Pointer;
public static implicit operator AVCodec_receive_packet_func(AVCodec_receive_packet func) => new AVCodec_receive_packet_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVCodec_receive_frame (AVCodecContext* @avctx, AVFrame* @frame);
public unsafe struct AVCodec_receive_frame_func
{
public IntPtr Pointer;
public static implicit operator AVCodec_receive_frame_func(AVCodec_receive_frame func) => new AVCodec_receive_frame_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void AVCodec_flush (AVCodecContext* @p0);
public unsafe struct AVCodec_flush_func
{
public IntPtr Pointer;
public static implicit operator AVCodec_flush_func(AVCodec_flush func) => new AVCodec_flush_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void AVCodecContext_draw_horiz_band (AVCodecContext* @s, AVFrame* @src, ref int_array8 @offset, int @y, int @type, int @height);
public unsafe struct AVCodecContext_draw_horiz_band_func
{
public IntPtr Pointer;
public static implicit operator AVCodecContext_draw_horiz_band_func(AVCodecContext_draw_horiz_band func) => new AVCodecContext_draw_horiz_band_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate AVPixelFormat AVCodecContext_get_format (AVCodecContext* @s, AVPixelFormat* @fmt);
public unsafe struct AVCodecContext_get_format_func
{
public IntPtr Pointer;
public static implicit operator AVCodecContext_get_format_func(AVCodecContext_get_format func) => new AVCodecContext_get_format_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVCodecContext_get_buffer2 (AVCodecContext* @s, AVFrame* @frame, int @flags);
public unsafe struct AVCodecContext_get_buffer2_func
{
public IntPtr Pointer;
public static implicit operator AVCodecContext_get_buffer2_func(AVCodecContext_get_buffer2 func) => new AVCodecContext_get_buffer2_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void AVCodecContext_rtp_callback (AVCodecContext* @avctx, void* @data, int @size, int @mb_nb);
public unsafe struct AVCodecContext_rtp_callback_func
{
public IntPtr Pointer;
public static implicit operator AVCodecContext_rtp_callback_func(AVCodecContext_rtp_callback func) => new AVCodecContext_rtp_callback_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVHWAccel_alloc_frame (AVCodecContext* @avctx, AVFrame* @frame);
public unsafe struct AVHWAccel_alloc_frame_func
{
public IntPtr Pointer;
public static implicit operator AVHWAccel_alloc_frame_func(AVHWAccel_alloc_frame func) => new AVHWAccel_alloc_frame_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVHWAccel_start_frame (AVCodecContext* @avctx, byte* @buf, uint @buf_size);
public unsafe struct AVHWAccel_start_frame_func
{
public IntPtr Pointer;
public static implicit operator AVHWAccel_start_frame_func(AVHWAccel_start_frame func) => new AVHWAccel_start_frame_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVHWAccel_decode_params (AVCodecContext* @avctx, int @type, byte* @buf, uint @buf_size);
public unsafe struct AVHWAccel_decode_params_func
{
public IntPtr Pointer;
public static implicit operator AVHWAccel_decode_params_func(AVHWAccel_decode_params func) => new AVHWAccel_decode_params_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVHWAccel_decode_slice (AVCodecContext* @avctx, byte* @buf, uint @buf_size);
public unsafe struct AVHWAccel_decode_slice_func
{
public IntPtr Pointer;
public static implicit operator AVHWAccel_decode_slice_func(AVHWAccel_decode_slice func) => new AVHWAccel_decode_slice_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVHWAccel_end_frame (AVCodecContext* @avctx);
public unsafe struct AVHWAccel_end_frame_func
{
public IntPtr Pointer;
public static implicit operator AVHWAccel_end_frame_func(AVHWAccel_end_frame func) => new AVHWAccel_end_frame_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void AVHWAccel_decode_mb (MpegEncContext* @s);
public unsafe struct AVHWAccel_decode_mb_func
{
public IntPtr Pointer;
public static implicit operator AVHWAccel_decode_mb_func(AVHWAccel_decode_mb func) => new AVHWAccel_decode_mb_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVHWAccel_init (AVCodecContext* @avctx);
public unsafe struct AVHWAccel_init_func
{
public IntPtr Pointer;
public static implicit operator AVHWAccel_init_func(AVHWAccel_init func) => new AVHWAccel_init_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVHWAccel_uninit (AVCodecContext* @avctx);
public unsafe struct AVHWAccel_uninit_func
{
public IntPtr Pointer;
public static implicit operator AVHWAccel_uninit_func(AVHWAccel_uninit func) => new AVHWAccel_uninit_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVHWAccel_frame_params (AVCodecContext* @avctx, AVBufferRef* @hw_frames_ctx);
public unsafe struct AVHWAccel_frame_params_func
{
public IntPtr Pointer;
public static implicit operator AVHWAccel_frame_params_func(AVHWAccel_frame_params func) => new AVHWAccel_frame_params_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVCodecContext_execute (AVCodecContext* @c, func_func @func, void* @arg2, int* @ret, int @count, int @size);
public unsafe struct AVCodecContext_execute_func
{
public IntPtr Pointer;
public static implicit operator AVCodecContext_execute_func(AVCodecContext_execute func) => new AVCodecContext_execute_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVCodecContext_execute2 (AVCodecContext* @c, func_func @func, void* @arg2, int* @ret, int @count);
public unsafe struct AVCodecContext_execute2_func
{
public IntPtr Pointer;
public static implicit operator AVCodecContext_execute2_func(AVCodecContext_execute2 func) => new AVCodecContext_execute2_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVCodecParser_parser_init (AVCodecParserContext* @s);
public unsafe struct AVCodecParser_parser_init_func
{
public IntPtr Pointer;
public static implicit operator AVCodecParser_parser_init_func(AVCodecParser_parser_init func) => new AVCodecParser_parser_init_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVCodecParser_parser_parse (AVCodecParserContext* @s, AVCodecContext* @avctx, byte** @poutbuf, int* @poutbuf_size, byte* @buf, int @buf_size);
public unsafe struct AVCodecParser_parser_parse_func
{
public IntPtr Pointer;
public static implicit operator AVCodecParser_parser_parse_func(AVCodecParser_parser_parse func) => new AVCodecParser_parser_parse_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void AVCodecParser_parser_close (AVCodecParserContext* @s);
public unsafe struct AVCodecParser_parser_close_func
{
public IntPtr Pointer;
public static implicit operator AVCodecParser_parser_close_func(AVCodecParser_parser_close func) => new AVCodecParser_parser_close_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVCodecParser_split (AVCodecContext* @avctx, byte* @buf, int @buf_size);
public unsafe struct AVCodecParser_split_func
{
public IntPtr Pointer;
public static implicit operator AVCodecParser_split_func(AVCodecParser_split func) => new AVCodecParser_split_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVBitStreamFilter_init (AVBSFContext* @ctx);
public unsafe struct AVBitStreamFilter_init_func
{
public IntPtr Pointer;
public static implicit operator AVBitStreamFilter_init_func(AVBitStreamFilter_init func) => new AVBitStreamFilter_init_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVBitStreamFilter_filter (AVBSFContext* @ctx, AVPacket* @pkt);
public unsafe struct AVBitStreamFilter_filter_func
{
public IntPtr Pointer;
public static implicit operator AVBitStreamFilter_filter_func(AVBitStreamFilter_filter func) => new AVBitStreamFilter_filter_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void AVBitStreamFilter_close (AVBSFContext* @ctx);
public unsafe struct AVBitStreamFilter_close_func
{
public IntPtr Pointer;
public static implicit operator AVBitStreamFilter_close_func(AVBitStreamFilter_close func) => new AVBitStreamFilter_close_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVInputFormat_read_probe (AVProbeData* @p0);
public unsafe struct AVInputFormat_read_probe_func
{
public IntPtr Pointer;
public static implicit operator AVInputFormat_read_probe_func(AVInputFormat_read_probe func) => new AVInputFormat_read_probe_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVInputFormat_read_header (AVFormatContext* @p0);
public unsafe struct AVInputFormat_read_header_func
{
public IntPtr Pointer;
public static implicit operator AVInputFormat_read_header_func(AVInputFormat_read_header func) => new AVInputFormat_read_header_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVInputFormat_read_packet (AVFormatContext* @p0, AVPacket* @pkt);
public unsafe struct AVInputFormat_read_packet_func
{
public IntPtr Pointer;
public static implicit operator AVInputFormat_read_packet_func(AVInputFormat_read_packet func) => new AVInputFormat_read_packet_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVInputFormat_read_close (AVFormatContext* @p0);
public unsafe struct AVInputFormat_read_close_func
{
public IntPtr Pointer;
public static implicit operator AVInputFormat_read_close_func(AVInputFormat_read_close func) => new AVInputFormat_read_close_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVInputFormat_read_seek (AVFormatContext* @p0, int @stream_index, long @timestamp, int @flags);
public unsafe struct AVInputFormat_read_seek_func
{
public IntPtr Pointer;
public static implicit operator AVInputFormat_read_seek_func(AVInputFormat_read_seek func) => new AVInputFormat_read_seek_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate long AVInputFormat_read_timestamp (AVFormatContext* @s, int @stream_index, long* @pos, long @pos_limit);
public unsafe struct AVInputFormat_read_timestamp_func
{
public IntPtr Pointer;
public static implicit operator AVInputFormat_read_timestamp_func(AVInputFormat_read_timestamp func) => new AVInputFormat_read_timestamp_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVInputFormat_read_play (AVFormatContext* @p0);
public unsafe struct AVInputFormat_read_play_func
{
public IntPtr Pointer;
public static implicit operator AVInputFormat_read_play_func(AVInputFormat_read_play func) => new AVInputFormat_read_play_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVInputFormat_read_pause (AVFormatContext* @p0);
public unsafe struct AVInputFormat_read_pause_func
{
public IntPtr Pointer;
public static implicit operator AVInputFormat_read_pause_func(AVInputFormat_read_pause func) => new AVInputFormat_read_pause_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVInputFormat_read_seek2 (AVFormatContext* @s, int @stream_index, long @min_ts, long @ts, long @max_ts, int @flags);
public unsafe struct AVInputFormat_read_seek2_func
{
public IntPtr Pointer;
public static implicit operator AVInputFormat_read_seek2_func(AVInputFormat_read_seek2 func) => new AVInputFormat_read_seek2_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVInputFormat_get_device_list (AVFormatContext* @s, AVDeviceInfoList* @device_list);
public unsafe struct AVInputFormat_get_device_list_func
{
public IntPtr Pointer;
public static implicit operator AVInputFormat_get_device_list_func(AVInputFormat_get_device_list func) => new AVInputFormat_get_device_list_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVInputFormat_create_device_capabilities (AVFormatContext* @s, AVDeviceCapabilitiesQuery* @caps);
public unsafe struct AVInputFormat_create_device_capabilities_func
{
public IntPtr Pointer;
public static implicit operator AVInputFormat_create_device_capabilities_func(AVInputFormat_create_device_capabilities func) => new AVInputFormat_create_device_capabilities_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVInputFormat_free_device_capabilities (AVFormatContext* @s, AVDeviceCapabilitiesQuery* @caps);
public unsafe struct AVInputFormat_free_device_capabilities_func
{
public IntPtr Pointer;
public static implicit operator AVInputFormat_free_device_capabilities_func(AVInputFormat_free_device_capabilities func) => new AVInputFormat_free_device_capabilities_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVIOContext_read_packet (void* @opaque, byte* @buf, int @buf_size);
public unsafe struct AVIOContext_read_packet_func
{
public IntPtr Pointer;
public static implicit operator AVIOContext_read_packet_func(AVIOContext_read_packet func) => new AVIOContext_read_packet_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVIOContext_write_packet (void* @opaque, byte* @buf, int @buf_size);
public unsafe struct AVIOContext_write_packet_func
{
public IntPtr Pointer;
public static implicit operator AVIOContext_write_packet_func(AVIOContext_write_packet func) => new AVIOContext_write_packet_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate long AVIOContext_seek (void* @opaque, long @offset, int @whence);
public unsafe struct AVIOContext_seek_func
{
public IntPtr Pointer;
public static implicit operator AVIOContext_seek_func(AVIOContext_seek func) => new AVIOContext_seek_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate ulong AVIOContext_update_checksum (ulong @checksum, byte* @buf, uint @size);
public unsafe struct AVIOContext_update_checksum_func
{
public IntPtr Pointer;
public static implicit operator AVIOContext_update_checksum_func(AVIOContext_update_checksum func) => new AVIOContext_update_checksum_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVIOContext_read_pause (void* @opaque, int @pause);
public unsafe struct AVIOContext_read_pause_func
{
public IntPtr Pointer;
public static implicit operator AVIOContext_read_pause_func(AVIOContext_read_pause func) => new AVIOContext_read_pause_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate long AVIOContext_read_seek (void* @opaque, int @stream_index, long @timestamp, int @flags);
public unsafe struct AVIOContext_read_seek_func
{
public IntPtr Pointer;
public static implicit operator AVIOContext_read_seek_func(AVIOContext_read_seek func) => new AVIOContext_read_seek_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVIOContext_write_data_type (void* @opaque, byte* @buf, int @buf_size, AVIODataMarkerType @type, long @time);
public unsafe struct AVIOContext_write_data_type_func
{
public IntPtr Pointer;
public static implicit operator AVIOContext_write_data_type_func(AVIOContext_write_data_type func) => new AVIOContext_write_data_type_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVIOContext_short_seek_get (void* @opaque);
public unsafe struct AVIOContext_short_seek_get_func
{
public IntPtr Pointer;
public static implicit operator AVIOContext_short_seek_get_func(AVIOContext_short_seek_get func) => new AVIOContext_short_seek_get_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVIOInterruptCB_callback (void* @p0);
public unsafe struct AVIOInterruptCB_callback_func
{
public IntPtr Pointer;
public static implicit operator AVIOInterruptCB_callback_func(AVIOInterruptCB_callback func) => new AVIOInterruptCB_callback_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVFormatContext_control_message_cb (AVFormatContext* @s, int @type, void* @data, ulong @data_size);
public unsafe struct AVFormatContext_control_message_cb_func
{
public IntPtr Pointer;
public static implicit operator AVFormatContext_control_message_cb_func(AVFormatContext_control_message_cb func) => new AVFormatContext_control_message_cb_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVFormatContext_open_cb (AVFormatContext* @s, AVIOContext** @p, [MarshalAs(UnmanagedType.LPStr)] string @url, int @flags, AVIOInterruptCB* @int_cb, AVDictionary** @options);
public unsafe struct AVFormatContext_open_cb_func
{
public IntPtr Pointer;
public static implicit operator AVFormatContext_open_cb_func(AVFormatContext_open_cb func) => new AVFormatContext_open_cb_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVFormatContext_io_open (AVFormatContext* @s, AVIOContext** @pb, [MarshalAs(UnmanagedType.LPStr)] string @url, int @flags, AVDictionary** @options);
public unsafe struct AVFormatContext_io_open_func
{
public IntPtr Pointer;
public static implicit operator AVFormatContext_io_open_func(AVFormatContext_io_open func) => new AVFormatContext_io_open_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void AVFormatContext_io_close (AVFormatContext* @s, AVIOContext* @pb);
public unsafe struct AVFormatContext_io_close_func
{
public IntPtr Pointer;
public static implicit operator AVFormatContext_io_close_func(AVFormatContext_io_close func) => new AVFormatContext_io_close_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVOutputFormat_write_header (AVFormatContext* @p0);
public unsafe struct AVOutputFormat_write_header_func
{
public IntPtr Pointer;
public static implicit operator AVOutputFormat_write_header_func(AVOutputFormat_write_header func) => new AVOutputFormat_write_header_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVOutputFormat_write_packet (AVFormatContext* @p0, AVPacket* @pkt);
public unsafe struct AVOutputFormat_write_packet_func
{
public IntPtr Pointer;
public static implicit operator AVOutputFormat_write_packet_func(AVOutputFormat_write_packet func) => new AVOutputFormat_write_packet_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVOutputFormat_write_trailer (AVFormatContext* @p0);
public unsafe struct AVOutputFormat_write_trailer_func
{
public IntPtr Pointer;
public static implicit operator AVOutputFormat_write_trailer_func(AVOutputFormat_write_trailer func) => new AVOutputFormat_write_trailer_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVOutputFormat_interleave_packet (AVFormatContext* @p0, AVPacket* @out, AVPacket* @in, int @flush);
public unsafe struct AVOutputFormat_interleave_packet_func
{
public IntPtr Pointer;
public static implicit operator AVOutputFormat_interleave_packet_func(AVOutputFormat_interleave_packet func) => new AVOutputFormat_interleave_packet_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVOutputFormat_query_codec (AVCodecID @id, int @std_compliance);
public unsafe struct AVOutputFormat_query_codec_func
{
public IntPtr Pointer;
public static implicit operator AVOutputFormat_query_codec_func(AVOutputFormat_query_codec func) => new AVOutputFormat_query_codec_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void AVOutputFormat_get_output_timestamp (AVFormatContext* @s, int @stream, long* @dts, long* @wall);
public unsafe struct AVOutputFormat_get_output_timestamp_func
{
public IntPtr Pointer;
public static implicit operator AVOutputFormat_get_output_timestamp_func(AVOutputFormat_get_output_timestamp func) => new AVOutputFormat_get_output_timestamp_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVOutputFormat_control_message (AVFormatContext* @s, int @type, void* @data, ulong @data_size);
public unsafe struct AVOutputFormat_control_message_func
{
public IntPtr Pointer;
public static implicit operator AVOutputFormat_control_message_func(AVOutputFormat_control_message func) => new AVOutputFormat_control_message_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVOutputFormat_write_uncoded_frame (AVFormatContext* @p0, int @stream_index, AVFrame** @frame, uint @flags);
public unsafe struct AVOutputFormat_write_uncoded_frame_func
{
public IntPtr Pointer;
public static implicit operator AVOutputFormat_write_uncoded_frame_func(AVOutputFormat_write_uncoded_frame func) => new AVOutputFormat_write_uncoded_frame_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVOutputFormat_get_device_list (AVFormatContext* @s, AVDeviceInfoList* @device_list);
public unsafe struct AVOutputFormat_get_device_list_func
{
public IntPtr Pointer;
public static implicit operator AVOutputFormat_get_device_list_func(AVOutputFormat_get_device_list func) => new AVOutputFormat_get_device_list_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVOutputFormat_create_device_capabilities (AVFormatContext* @s, AVDeviceCapabilitiesQuery* @caps);
public unsafe struct AVOutputFormat_create_device_capabilities_func
{
public IntPtr Pointer;
public static implicit operator AVOutputFormat_create_device_capabilities_func(AVOutputFormat_create_device_capabilities func) => new AVOutputFormat_create_device_capabilities_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVOutputFormat_free_device_capabilities (AVFormatContext* @s, AVDeviceCapabilitiesQuery* @caps);
public unsafe struct AVOutputFormat_free_device_capabilities_func
{
public IntPtr Pointer;
public static implicit operator AVOutputFormat_free_device_capabilities_func(AVOutputFormat_free_device_capabilities func) => new AVOutputFormat_free_device_capabilities_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVOutputFormat_init (AVFormatContext* @p0);
public unsafe struct AVOutputFormat_init_func
{
public IntPtr Pointer;
public static implicit operator AVOutputFormat_init_func(AVOutputFormat_init func) => new AVOutputFormat_init_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void AVOutputFormat_deinit (AVFormatContext* @p0);
public unsafe struct AVOutputFormat_deinit_func
{
public IntPtr Pointer;
public static implicit operator AVOutputFormat_deinit_func(AVOutputFormat_deinit func) => new AVOutputFormat_deinit_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVOutputFormat_check_bitstream (AVFormatContext* @p0, AVPacket* @pkt);
public unsafe struct AVOutputFormat_check_bitstream_func
{
public IntPtr Pointer;
public static implicit operator AVOutputFormat_check_bitstream_func(AVOutputFormat_check_bitstream func) => new AVOutputFormat_check_bitstream_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVFilter_preinit (AVFilterContext* @ctx);
public unsafe struct AVFilter_preinit_func
{
public IntPtr Pointer;
public static implicit operator AVFilter_preinit_func(AVFilter_preinit func) => new AVFilter_preinit_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVFilter_init (AVFilterContext* @ctx);
public unsafe struct AVFilter_init_func
{
public IntPtr Pointer;
public static implicit operator AVFilter_init_func(AVFilter_init func) => new AVFilter_init_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVFilter_init_dict (AVFilterContext* @ctx, AVDictionary** @options);
public unsafe struct AVFilter_init_dict_func
{
public IntPtr Pointer;
public static implicit operator AVFilter_init_dict_func(AVFilter_init_dict func) => new AVFilter_init_dict_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void AVFilter_uninit (AVFilterContext* @ctx);
public unsafe struct AVFilter_uninit_func
{
public IntPtr Pointer;
public static implicit operator AVFilter_uninit_func(AVFilter_uninit func) => new AVFilter_uninit_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVFilter_query_formats (AVFilterContext* @p0);
public unsafe struct AVFilter_query_formats_func
{
public IntPtr Pointer;
public static implicit operator AVFilter_query_formats_func(AVFilter_query_formats func) => new AVFilter_query_formats_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVFilter_process_command (AVFilterContext* @p0, [MarshalAs(UnmanagedType.LPStr)] string @cmd, [MarshalAs(UnmanagedType.LPStr)] string @arg, byte* @res, int @res_len, int @flags);
public unsafe struct AVFilter_process_command_func
{
public IntPtr Pointer;
public static implicit operator AVFilter_process_command_func(AVFilter_process_command func) => new AVFilter_process_command_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVFilter_init_opaque (AVFilterContext* @ctx, void* @opaque);
public unsafe struct AVFilter_init_opaque_func
{
public IntPtr Pointer;
public static implicit operator AVFilter_init_opaque_func(AVFilter_init_opaque func) => new AVFilter_init_opaque_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVFilter_activate (AVFilterContext* @ctx);
public unsafe struct AVFilter_activate_func
{
public IntPtr Pointer;
public static implicit operator AVFilter_activate_func(AVFilter_activate func) => new AVFilter_activate_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int func (AVFilterContext* @ctx, void* @arg, int @jobnr, int @nb_jobs);
public unsafe struct func_func
{
public IntPtr Pointer;
public static implicit operator func_func(func func) => new func_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int AVFilterGraph_execute (AVFilterContext* @ctx, func_func @func, void* @arg, int* @ret, int @nb_jobs);
public unsafe struct AVFilterGraph_execute_func
{
public IntPtr Pointer;
public static implicit operator AVFilterGraph_execute_func(AVFilterGraph_execute func) => new AVFilterGraph_execute_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void av_log_set_callback_callback (void* @p0, int @p1, [MarshalAs(UnmanagedType.LPStr)] string @p2, byte* @p3);
public unsafe struct av_log_set_callback_callback_func
{
public IntPtr Pointer;
public static implicit operator av_log_set_callback_callback_func(av_log_set_callback_callback func) => new av_log_set_callback_callback_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void av_buffer_create_free (void* @opaque, byte* @data);
public unsafe struct av_buffer_create_free_func
{
public IntPtr Pointer;
public static implicit operator av_buffer_create_free_func(av_buffer_create_free func) => new av_buffer_create_free_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate AVBufferRef* av_buffer_pool_init_alloc (int @size);
public unsafe struct av_buffer_pool_init_alloc_func
{
public IntPtr Pointer;
public static implicit operator av_buffer_pool_init_alloc_func(av_buffer_pool_init_alloc func) => new av_buffer_pool_init_alloc_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate AVBufferRef* av_buffer_pool_init2_alloc (void* @opaque, int @size);
public unsafe struct av_buffer_pool_init2_alloc_func
{
public IntPtr Pointer;
public static implicit operator av_buffer_pool_init2_alloc_func(av_buffer_pool_init2_alloc func) => new av_buffer_pool_init2_alloc_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void av_buffer_pool_init2_pool_free (void* @opaque);
public unsafe struct av_buffer_pool_init2_pool_free_func
{
public IntPtr Pointer;
public static implicit operator av_buffer_pool_init2_pool_free_func(av_buffer_pool_init2_pool_free func) => new av_buffer_pool_init2_pool_free_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int avcodec_default_execute_func (AVCodecContext* @c2, void* @arg2);
public unsafe struct avcodec_default_execute_func_func
{
public IntPtr Pointer;
public static implicit operator avcodec_default_execute_func_func(avcodec_default_execute_func func) => new avcodec_default_execute_func_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int avcodec_default_execute2_func (AVCodecContext* @c2, void* @arg2, int @p2, int @p3);
public unsafe struct avcodec_default_execute2_func_func
{
public IntPtr Pointer;
public static implicit operator avcodec_default_execute2_func_func(avcodec_default_execute2_func func) => new avcodec_default_execute2_func_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int av_lockmgr_register_cb (void** @mutex, AVLockOp @op);
public unsafe struct av_lockmgr_register_cb_func
{
public IntPtr Pointer;
public static implicit operator av_lockmgr_register_cb_func(av_lockmgr_register_cb func) => new av_lockmgr_register_cb_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int avio_alloc_context_read_packet (void* @opaque, byte* @buf, int @buf_size);
public unsafe struct avio_alloc_context_read_packet_func
{
public IntPtr Pointer;
public static implicit operator avio_alloc_context_read_packet_func(avio_alloc_context_read_packet func) => new avio_alloc_context_read_packet_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int avio_alloc_context_write_packet (void* @opaque, byte* @buf, int @buf_size);
public unsafe struct avio_alloc_context_write_packet_func
{
public IntPtr Pointer;
public static implicit operator avio_alloc_context_write_packet_func(avio_alloc_context_write_packet func) => new avio_alloc_context_write_packet_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate long avio_alloc_context_seek (void* @opaque, long @offset, int @whence);
public unsafe struct avio_alloc_context_seek_func
{
public IntPtr Pointer;
public static implicit operator avio_alloc_context_seek_func(avio_alloc_context_seek func) => new avio_alloc_context_seek_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int av_format_get_control_message_cb (AVFormatContext* @s, int @type, void* @data, ulong @data_size);
public unsafe struct av_format_get_control_message_cb_func
{
public IntPtr Pointer;
public static implicit operator av_format_get_control_message_cb_func(av_format_get_control_message_cb func) => new av_format_get_control_message_cb_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int av_format_set_control_message_cb_callback (AVFormatContext* @s, int @type, void* @data, ulong @data_size);
public unsafe struct av_format_set_control_message_cb_callback_func
{
public IntPtr Pointer;
public static implicit operator av_format_set_control_message_cb_callback_func(av_format_set_control_message_cb_callback func) => new av_format_set_control_message_cb_callback_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int av_format_get_open_cb (AVFormatContext* @s, AVIOContext** @pb, [MarshalAs(UnmanagedType.LPStr)] string @url, int @flags, AVIOInterruptCB* @int_cb, AVDictionary** @options);
public unsafe struct av_format_get_open_cb_func
{
public IntPtr Pointer;
public static implicit operator av_format_get_open_cb_func(av_format_get_open_cb func) => new av_format_get_open_cb_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int av_format_set_open_cb_callback (AVFormatContext* @s, AVIOContext** @pb, [MarshalAs(UnmanagedType.LPStr)] string @url, int @flags, AVIOInterruptCB* @int_cb, AVDictionary** @options);
public unsafe struct av_format_set_open_cb_callback_func
{
public IntPtr Pointer;
public static implicit operator av_format_set_open_cb_callback_func(av_format_set_open_cb_callback func) => new av_format_set_open_cb_callback_func { Pointer = func == null ? IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(func) };
}
}
| 60.858931 | 276 | 0.766221 | [
"MIT"
] | CommitteeOfZero/nitrosharp | third_party/FFmpeg.AutoGen/FFmpeg.delegates.g.cs | 53,495 | C# |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.Positions.Algo
File: PositionMessageAdapter.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo.Positions
{
using System;
using StockSharp.Messages;
/// <summary>
/// The message adapter, automatically calculating position.
/// </summary>
public class PositionMessageAdapter : MessageAdapterWrapper
{
/// <summary>
/// Initializes a new instance of the <see cref="PositionMessageAdapter"/>.
/// </summary>
/// <param name="innerAdapter">The adapter, to which messages will be directed.</param>
public PositionMessageAdapter(IMessageAdapter innerAdapter)
: base(innerAdapter)
{
}
private IPositionManager _positionManager = new PositionManager(true);
/// <summary>
/// The position manager.
/// </summary>
public IPositionManager PositionManager
{
get { return _positionManager; }
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
_positionManager = value;
}
}
/// <summary>
/// Send message.
/// </summary>
/// <param name="message">Message.</param>
public override void SendInMessage(Message message)
{
PositionManager.ProcessMessage(message);
base.SendInMessage(message);
}
/// <summary>
/// Process <see cref="MessageAdapterWrapper.InnerAdapter"/> output message.
/// </summary>
/// <param name="message">The message.</param>
protected override void OnInnerAdapterNewOutMessage(Message message)
{
var position = PositionManager.ProcessMessage(message);
if (position != null)
((ExecutionMessage)message).Position = position;
base.OnInnerAdapterNewOutMessage(message);
}
/// <summary>
/// Create a copy of <see cref="PositionMessageAdapter"/>.
/// </summary>
/// <returns>Copy.</returns>
public override IMessageChannel Clone()
{
return new PositionMessageAdapter((IMessageAdapter)InnerAdapter.Clone());
}
}
} | 28.517241 | 92 | 0.665054 | [
"Apache-2.0"
] | Alexander2k/Stock- | Algo/Positions/PositionMessageAdapter.cs | 2,481 | 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.AzureAD.Inputs
{
public sealed class ApplicationOptionalClaimsAccessTokenArgs : Pulumi.ResourceArgs
{
[Input("additionalProperties")]
private InputList<string>? _additionalProperties;
/// <summary>
/// List of additional properties of the claim. If a property exists in this list, it modifies the behaviour of the optional claim.
/// </summary>
public InputList<string> AdditionalProperties
{
get => _additionalProperties ?? (_additionalProperties = new InputList<string>());
set => _additionalProperties = value;
}
/// <summary>
/// Whether the claim specified by the client is necessary to ensure a smooth authorization experience.
/// </summary>
[Input("essential")]
public Input<bool>? Essential { get; set; }
/// <summary>
/// The name of the optional claim.
/// </summary>
[Input("name", required: true)]
public Input<string> Name { get; set; } = null!;
/// <summary>
/// The source of the claim. If `source` is absent, the claim is a predefined optional claim. If `source` is `user`, the value of `name` is the extension property from the user object.
/// </summary>
[Input("source")]
public Input<string>? Source { get; set; }
public ApplicationOptionalClaimsAccessTokenArgs()
{
}
}
}
| 35.5 | 192 | 0.63493 | [
"ECL-2.0",
"Apache-2.0"
] | AaronFriel/pulumi-azuread | sdk/dotnet/Inputs/ApplicationOptionalClaimsAccessTokenArgs.cs | 1,775 | C# |
using UnityEngine;
using System.Collections;
public class Firefly : MonoBehaviour
{
private float[] _hsl;
private float _currentValue = 0.0f;
private float _initialIntensity;
private Vector3 _basePosition;
public Light FireflyLight;
public float HueChange = 1.0f;
public float IntensityChange = 0.5f;
public float IntensityCyclesPerSecond = 1.0f;
public float RandomIntensityPerFrame = 0.3f;
public Vector3 WanderDistance = new Vector3(10.0f, 0.5f, 10.0f);
public bool AllowMovement = false;
public bool AllowColorChange = false;
public bool AllowIntensityChange = true;
void Start()
{
if( FireflyLight != null )
{
#region HSL
var rgb = FireflyLight.color;
_hsl = new float[3]{0,0,0};
var rl = rgb.r;
var gl = rgb.g;
var bl = rgb.b;
var Cmax = Mathf.Max(rl, gl, bl);
var Cmin = Mathf.Min(rl, gl, bl);
var delta = Cmax - Cmin;
// H
if( Cmax == rl )
{
_hsl[0] = 60 * (((gl - bl) / delta) % 6);
}
else if( Cmax == gl )
{
_hsl[0] = 60 * (((bl - rl) / delta) + 2);
}
else if(Cmax == bl)
{
_hsl[0] = 60 * (((rl - gl) / delta) + 4);
}
else
{
Debug.LogError("Invalid Cmax!");
}
// L
_hsl[2] = (Cmax + Cmin) / 2;
// S
if( delta == 0.0f )
{
_hsl[1] = 0.0f;
}
else
{
_hsl[1] = delta / (1 - Mathf.Abs(2 * _hsl[2] - 1));
}
#endregion HSL
_initialIntensity = FireflyLight.intensity;
_basePosition = transform.position;
}
}
void Update()
{
if( FireflyLight != null )
{
if (AllowColorChange)
{
#region Hue Change
_hsl[0] += (HueChange * Time.deltaTime);
if (_hsl[0] >= 360.0f) _hsl[0] -= 360.0f;
var C = (1 - Mathf.Abs(2 * _hsl[2] - 1)) * _hsl[1];
var X = C * (1 - Mathf.Abs(((_hsl[0] / 60.0f) % 2) - 1));
var m = _hsl[2] - C / 2.0f;
var rl = 0.0f;
var gl = 0.0f;
var bl = 0.0f;
if (0.0f <= _hsl[0] && _hsl[0] < 60.0f)
{
rl = C;
gl = X;
bl = 0.0f;
}
else if (60.0f <= _hsl[0] && _hsl[0] < 120.0f)
{
rl = X;
gl = C;
bl = 0.0f;
}
else if (120.0f <= _hsl[0] && _hsl[0] < 180.0f)
{
rl = 0.0f;
gl = C;
bl = X;
}
else if (180.0f <= _hsl[0] && _hsl[0] < 240.0f)
{
rl = 0.0f;
gl = X;
bl = C;
}
else if (240.0f <= _hsl[0] && _hsl[0] < 300.0f)
{
rl = X;
gl = 0.0f;
bl = C;
}
else if (300.0f <= _hsl[0] && _hsl[0] < 360.0f)
{
rl = C;
gl = 0.0f;
bl = X;
}
var newColor = new Color(rl + m, gl + m, bl + m);
FireflyLight.color = newColor;
#endregion Hue Change
}
if (AllowIntensityChange || AllowMovement)
{
_currentValue += (IntensityCyclesPerSecond * Time.deltaTime);
if (AllowIntensityChange)
{
var random = Random.Range(-RandomIntensityPerFrame, RandomIntensityPerFrame);
FireflyLight.intensity = _initialIntensity + Time.timeScale * ((Mathf.Cos(Mathf.PI * _currentValue) * IntensityChange) + random);
}
if (AllowMovement)
{
transform.position = _basePosition + new Vector3(WanderDistance.x * Mathf.Sin(_currentValue),
WanderDistance.y * Mathf.Tan(_currentValue),
WanderDistance.z * Mathf.Cos(_currentValue));
}
}
}
}
}
| 29.1125 | 149 | 0.385144 | [
"MIT"
] | DioMuller/quest-for-the-crown-3D | Game/Assets/Scripts/Entities/NPC/Firefly.cs | 4,658 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace System.Json
{
public class JsonArray : JsonValue, IList<JsonValue>
{
List<JsonValue> list;
public JsonArray (params JsonValue [] items)
{
list = new List<JsonValue> ();
AddRange (items);
}
public JsonArray (IEnumerable<JsonValue> items)
{
if (items == null)
throw new ArgumentNullException ("items");
list = new List<JsonValue> (items);
}
public override int Count {
get { return list.Count; }
}
public bool IsReadOnly {
get { return false; }
}
public override sealed JsonValue this [int index] {
get { return list [index]; }
set { list [index] = value; }
}
public override JsonType JsonType {
get { return JsonType.Array; }
}
public void Add (JsonValue item)
{
if (item == null)
throw new ArgumentNullException ("item");
list.Add (item);
}
public void AddRange (IEnumerable<JsonValue> items)
{
if (items == null)
throw new ArgumentNullException ("items");
list.AddRange (items);
}
public void AddRange (params JsonValue [] items)
{
if (items == null)
return;
list.AddRange (items);
}
public void Clear ()
{
list.Clear ();
}
public bool Contains (JsonValue item)
{
return list.Contains (item);
}
public void CopyTo (JsonValue [] array, int arrayIndex)
{
list.CopyTo (array, arrayIndex);
}
public int IndexOf (JsonValue item)
{
return list.IndexOf (item);
}
public void Insert (int index, JsonValue item)
{
list.Insert (index, item);
}
public bool Remove (JsonValue item)
{
return list.Remove (item);
}
public void RemoveAt (int index)
{
list.RemoveAt (index);
}
public override void Save (Stream stream)
{
if (stream == null)
throw new ArgumentNullException ("stream");
stream.WriteByte ((byte) '[');
for (int i = 0; i < list.Count; i++) {
list [i].Save (stream);
if (i < Count - 1) {
stream.WriteByte ((byte) ',');
stream.WriteByte ((byte) ' ');
}
}
stream.WriteByte ((byte) ']');
}
IEnumerator<JsonValue> IEnumerable<JsonValue>.GetEnumerator ()
{
return list.GetEnumerator ();
}
IEnumerator IEnumerable.GetEnumerator ()
{
return list.GetEnumerator ();
}
}
}
| 18.114504 | 64 | 0.635061 | [
"Apache-2.0"
] | CRivlaldo/mono | mcs/class/System.Json/System.Json/JsonArray.cs | 2,373 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProgrammingAssignment2
{
/// <summary>
/// A mutual fund
/// </summary>
public class MutualFund : InvestmentAccount
{
const float ServiceChargePercent = 0.01f;
private const float Growth = 6f;
#region Contructor
public MutualFund(float deposit) : base(deposit)
{
}
#endregion
#region Public methods
public override void AddMoney(float amount)
{
amount -= amount * ServiceChargePercent;
base.AddMoney(amount);
}
/// <summary>
/// Updates the balance by adding 6%
/// </summary>
public override void UpdateBalance()
{
balance += (balance / 100) * Growth;
}
/// <summary>
/// Provides balance with account type caption
/// </summary>
/// <returns>balance with caption</returns>
public override string ToString()
{
return "Mutual Fund Balance: " + balance;
}
#endregion
}
}
| 21.722222 | 56 | 0.564365 | [
"MIT"
] | VsIG-official/Study-Projects | Unity/Intermediate Object-Oriented Programming for Unity Games/2_week/ProgAss2/ProgrammingAssignment2/ProgrammingAssignment2/MutualFund.cs | 1,175 | C# |
using System;
using System.Linq.Expressions;
namespace BLToolkit.Data.Linq.Builder
{
using BLToolkit.Linq;
using Data.Sql;
class ContainsBuilder : MethodCallBuilder
{
protected override bool CanBuildMethodCall(ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo)
{
return methodCall.IsQueryable("Contains") && methodCall.Arguments.Count == 2;
}
protected override IBuildContext BuildMethodCall(ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo)
{
var sequence = builder.BuildSequence(new BuildInfo(buildInfo, methodCall.Arguments[0]));
return new ContainsContext(buildInfo.Parent, methodCall, sequence);
}
protected override SequenceConvertInfo Convert(
ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo, ParameterExpression param)
{
return null;
}
class ContainsContext : SequenceContextBase
{
readonly MethodCallExpression _methodCall;
public ContainsContext(IBuildContext parent, MethodCallExpression methodCall, IBuildContext sequence)
: base(parent, sequence, null)
{
_methodCall = methodCall;
}
public override void BuildQuery<T>(Query<T> query, ParameterExpression queryParameter)
{
var sql = GetSubQuery(null);
query.Queries[0].SqlQuery = new SqlQuery();
query.Queries[0].SqlQuery.Select.Add(sql);
var expr = Builder.BuildSql(typeof(bool), 0);
var mapper = Builder.BuildMapper<object>(expr);
query.SetElementQuery(mapper.Compile());
}
public override Expression BuildExpression(Expression expression, int level)
{
var idx = ConvertToIndex(expression, level, ConvertFlags.Field);
return Builder.BuildSql(typeof(bool), idx[0].Index);
}
public override SqlInfo[] ConvertToSql(Expression expression, int level, ConvertFlags flags)
{
if (expression == null)
{
var sql = GetSubQuery(null);
var query = SqlQuery;
if (Parent != null)
query = Parent.SqlQuery;
return new[] { new SqlInfo { Query = query, Sql = sql } };
}
throw new InvalidOperationException();
}
public override SqlInfo[] ConvertToIndex(Expression expression, int level, ConvertFlags flags)
{
var sql = ConvertToSql(expression, level, flags);
if (sql[0].Index < 0)
sql[0].Index = sql[0].Query.Select.Add(sql[0].Sql);
return sql;
}
public override IsExpressionResult IsExpression(Expression expression, int level, RequestFor requestFlag)
{
if (expression == null)
{
switch (requestFlag)
{
case RequestFor.Expression :
case RequestFor.Field : return IsExpressionResult.False;
}
}
throw new InvalidOperationException();
}
public override IBuildContext GetContext(Expression expression, int level, BuildInfo buildInfo)
{
throw new InvalidOperationException();
}
ISqlExpression _subQuerySql;
public override ISqlExpression GetSubQuery(IBuildContext context)
{
if (_subQuerySql == null)
{
var args = _methodCall.Method.GetGenericArguments();
var param = Expression.Parameter(args[0], "param");
var expr = _methodCall.Arguments[1];
var condition = Expression.Lambda(Expression.Equal(param, expr), param);
IBuildContext ctx = new ExpressionContext(Parent, Sequence, condition);
ctx = Builder.GetContext(ctx, expr) ?? ctx;
Builder.ReplaceParent(ctx, this);
SqlQuery.Condition cond;
if (Sequence.SqlQuery != SqlQuery &&
(ctx.IsExpression(expr, 0, RequestFor.Field). Result ||
ctx.IsExpression(expr, 0, RequestFor.Expression).Result))
{
Sequence.ConvertToIndex(null, 0, ConvertFlags.All);
var ex = Builder.ConvertToSql(ctx, _methodCall.Arguments[1], false);
cond = new SqlQuery.Condition(false, new SqlQuery.Predicate.InSubQuery(ex, false, SqlQuery));
}
else
{
var sequence = Builder.BuildWhere(Parent, Sequence, condition, true);
cond = new SqlQuery.Condition(false, new SqlQuery.Predicate.FuncLike(SqlFunction.CreateExists(sequence.SqlQuery)));
}
_subQuerySql = new SqlQuery.SearchCondition(cond);
}
return _subQuerySql;
}
}
}
}
| 30.594406 | 132 | 0.682971 | [
"MIT"
] | igor-tkachev/bltoolkit | Source/Data/Linq/Builder/ContainsBuilder.cs | 4,377 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Live.V20180801.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeLiveTranscodeDetailInfoResponse : AbstractModel
{
/// <summary>
/// Statistics list.
/// </summary>
[JsonProperty("DataInfoList")]
public TranscodeDetailInfo[] DataInfoList{ get; set; }
/// <summary>
/// Page number.
/// </summary>
[JsonProperty("PageNum")]
public ulong? PageNum{ get; set; }
/// <summary>
/// Number of entries per page.
/// </summary>
[JsonProperty("PageSize")]
public ulong? PageSize{ get; set; }
/// <summary>
/// Total number.
/// </summary>
[JsonProperty("TotalNum")]
public ulong? TotalNum{ get; set; }
/// <summary>
/// Total number of pages.
/// </summary>
[JsonProperty("TotalPage")]
public ulong? TotalPage{ get; set; }
/// <summary>
/// The unique request ID, which is returned for each request. RequestId is required for locating a problem.
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamArrayObj(map, prefix + "DataInfoList.", this.DataInfoList);
this.SetParamSimple(map, prefix + "PageNum", this.PageNum);
this.SetParamSimple(map, prefix + "PageSize", this.PageSize);
this.SetParamSimple(map, prefix + "TotalNum", this.TotalNum);
this.SetParamSimple(map, prefix + "TotalPage", this.TotalPage);
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 32.835443 | 116 | 0.611411 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet-intl-en | TencentCloud/Live/V20180801/Models/DescribeLiveTranscodeDetailInfoResponse.cs | 2,594 | 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.NotificationHub
{
/// <summary>
/// Manages an Authorization Rule associated with a Notification Hub within a Notification Hub Namespace.
/// </summary>
public partial class AuthorizationRule : Pulumi.CustomResource
{
/// <summary>
/// Does this Authorization Rule have Listen access to the Notification Hub? Defaults to `false`.
/// </summary>
[Output("listen")]
public Output<bool?> Listen { get; private set; } = null!;
/// <summary>
/// Does this Authorization Rule have Manage access to the Notification Hub? Defaults to `false`.
/// </summary>
[Output("manage")]
public Output<bool?> Manage { get; private set; } = null!;
/// <summary>
/// The name to use for this Authorization Rule. Changing this forces a new resource to be created.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The name of the Notification Hub Namespace in which the Notification Hub exists. Changing this forces a new resource to be created.
/// </summary>
[Output("namespaceName")]
public Output<string> NamespaceName { get; private set; } = null!;
/// <summary>
/// The name of the Notification Hub for which the Authorization Rule should be created. Changing this forces a new resource to be created.
/// </summary>
[Output("notificationHubName")]
public Output<string> NotificationHubName { get; private set; } = null!;
/// <summary>
/// The Primary Access Key associated with this Authorization Rule.
/// </summary>
[Output("primaryAccessKey")]
public Output<string> PrimaryAccessKey { get; private set; } = null!;
/// <summary>
/// The name of the Resource Group in which the Notification Hub Namespace exists. Changing this forces a new resource to be created.
/// </summary>
[Output("resourceGroupName")]
public Output<string> ResourceGroupName { get; private set; } = null!;
/// <summary>
/// The Secondary Access Key associated with this Authorization Rule.
/// </summary>
[Output("secondaryAccessKey")]
public Output<string> SecondaryAccessKey { get; private set; } = null!;
/// <summary>
/// Does this Authorization Rule have Send access to the Notification Hub? Defaults to `false`.
/// </summary>
[Output("send")]
public Output<bool?> Send { get; private set; } = null!;
/// <summary>
/// Create a AuthorizationRule resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public AuthorizationRule(string name, AuthorizationRuleArgs args, CustomResourceOptions? options = null)
: base("azure:notificationhub/authorizationRule:AuthorizationRule", name, args ?? new AuthorizationRuleArgs(), MakeResourceOptions(options, ""))
{
}
private AuthorizationRule(string name, Input<string> id, AuthorizationRuleState? state = null, CustomResourceOptions? options = null)
: base("azure:notificationhub/authorizationRule:AuthorizationRule", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing AuthorizationRule resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static AuthorizationRule Get(string name, Input<string> id, AuthorizationRuleState? state = null, CustomResourceOptions? options = null)
{
return new AuthorizationRule(name, id, state, options);
}
}
public sealed class AuthorizationRuleArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Does this Authorization Rule have Listen access to the Notification Hub? Defaults to `false`.
/// </summary>
[Input("listen")]
public Input<bool>? Listen { get; set; }
/// <summary>
/// Does this Authorization Rule have Manage access to the Notification Hub? Defaults to `false`.
/// </summary>
[Input("manage")]
public Input<bool>? Manage { get; set; }
/// <summary>
/// The name to use for this Authorization Rule. Changing this forces a new resource to be created.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The name of the Notification Hub Namespace in which the Notification Hub exists. Changing this forces a new resource to be created.
/// </summary>
[Input("namespaceName", required: true)]
public Input<string> NamespaceName { get; set; } = null!;
/// <summary>
/// The name of the Notification Hub for which the Authorization Rule should be created. Changing this forces a new resource to be created.
/// </summary>
[Input("notificationHubName", required: true)]
public Input<string> NotificationHubName { get; set; } = null!;
/// <summary>
/// The name of the Resource Group in which the Notification Hub Namespace exists. Changing this forces a new resource to be created.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// Does this Authorization Rule have Send access to the Notification Hub? Defaults to `false`.
/// </summary>
[Input("send")]
public Input<bool>? Send { get; set; }
public AuthorizationRuleArgs()
{
}
}
public sealed class AuthorizationRuleState : Pulumi.ResourceArgs
{
/// <summary>
/// Does this Authorization Rule have Listen access to the Notification Hub? Defaults to `false`.
/// </summary>
[Input("listen")]
public Input<bool>? Listen { get; set; }
/// <summary>
/// Does this Authorization Rule have Manage access to the Notification Hub? Defaults to `false`.
/// </summary>
[Input("manage")]
public Input<bool>? Manage { get; set; }
/// <summary>
/// The name to use for this Authorization Rule. Changing this forces a new resource to be created.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The name of the Notification Hub Namespace in which the Notification Hub exists. Changing this forces a new resource to be created.
/// </summary>
[Input("namespaceName")]
public Input<string>? NamespaceName { get; set; }
/// <summary>
/// The name of the Notification Hub for which the Authorization Rule should be created. Changing this forces a new resource to be created.
/// </summary>
[Input("notificationHubName")]
public Input<string>? NotificationHubName { get; set; }
/// <summary>
/// The Primary Access Key associated with this Authorization Rule.
/// </summary>
[Input("primaryAccessKey")]
public Input<string>? PrimaryAccessKey { get; set; }
/// <summary>
/// The name of the Resource Group in which the Notification Hub Namespace exists. Changing this forces a new resource to be created.
/// </summary>
[Input("resourceGroupName")]
public Input<string>? ResourceGroupName { get; set; }
/// <summary>
/// The Secondary Access Key associated with this Authorization Rule.
/// </summary>
[Input("secondaryAccessKey")]
public Input<string>? SecondaryAccessKey { get; set; }
/// <summary>
/// Does this Authorization Rule have Send access to the Notification Hub? Defaults to `false`.
/// </summary>
[Input("send")]
public Input<bool>? Send { get; set; }
public AuthorizationRuleState()
{
}
}
}
| 42.715556 | 156 | 0.61877 | [
"ECL-2.0",
"Apache-2.0"
] | AdminTurnedDevOps/pulumi-azure | sdk/dotnet/NotificationHub/AuthorizationRule.cs | 9,611 | C# |
using System;
namespace Scorpio.Modularity
{
/// <summary>
///
/// </summary>
public interface IDependedTypesProvider
{
/// <summary>
///
/// </summary>
/// <returns></returns>
Type[] GetDependedTypes();
}
}
| 14.631579 | 43 | 0.489209 | [
"MIT"
] | project-scorpio/Scorpio | src/Core/src/Scorpio/Scorpio/Modularity/IDependedTypesProvider.cs | 280 | C# |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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 QuantConnect.Data;
using QuantConnect.Orders.Fees;
using QuantConnect.Orders.Fills;
using QuantConnect.Orders.Slippage;
namespace QuantConnect.Securities.Equity
{
/// <summary>
/// Equity Security Type : Extension of the underlying Security class for equity specific behaviours.
/// </summary>
/// <seealso cref="Security"/>
public class Equity : Security
{
/// <summary>
/// The default number of days required to settle an equity sale
/// </summary>
public const int DefaultSettlementDays = 3;
/// <summary>
/// The default time of day for settlement
/// </summary>
public static readonly TimeSpan DefaultSettlementTime = new TimeSpan(8, 0, 0);
/// <summary>
/// Checks if the equity is a shortable asset. Note that this does not
/// take into account any open orders or existing holdings. To check if the asset
/// is currently shortable, use QCAlgorithm's ShortableQuantity property instead.
/// </summary>
/// <returns>True if the security is a shortable equity</returns>
public bool Shortable
{
get
{
var shortableQuantity = ShortableProvider.ShortableQuantity(Symbol, LocalTime);
return shortableQuantity == null || shortableQuantity == 0m;
}
}
/// <summary>
/// Gets the total quantity shortable for this security. This does not take into account
/// any open orders or existing holdings. To check the asset's currently shortable quantity,
/// use QCAlgorithm's ShortableQuantity property instead.
/// </summary>
/// <returns>Zero if not shortable, null if infinitely shortable, or a number greater than zero if shortable</returns>
public long? TotalShortableQuantity => ShortableProvider.ShortableQuantity(Symbol, LocalTime);
/// <summary>
/// Equity primary exchange.
/// </summary>
public PrimaryExchange PrimaryExchange;
/// <summary>
/// Construct the Equity Object
/// </summary>
public Equity(Symbol symbol,
SecurityExchangeHours exchangeHours,
Cash quoteCurrency,
SymbolProperties symbolProperties,
ICurrencyConverter currencyConverter,
IRegisteredSecurityDataTypesProvider registeredTypes,
SecurityCache securityCache,
PrimaryExchange primaryExchange=PrimaryExchange.UNKNOWN)
: base(symbol,
quoteCurrency,
symbolProperties,
new EquityExchange(exchangeHours),
securityCache,
new SecurityPortfolioModel(),
new EquityFillModel(),
new InteractiveBrokersFeeModel(),
new ConstantSlippageModel(0m),
new ImmediateSettlementModel(),
Securities.VolatilityModel.Null,
new SecurityMarginModel(2m),
new EquityDataFilter(),
new AdjustedPriceVariationModel(),
currencyConverter,
registeredTypes
)
{
Holdings = new EquityHolding(this, currencyConverter);
PrimaryExchange = primaryExchange;
}
/// <summary>
/// Construct the Equity Object
/// </summary>
public Equity(SecurityExchangeHours exchangeHours,
SubscriptionDataConfig config,
Cash quoteCurrency,
SymbolProperties symbolProperties,
ICurrencyConverter currencyConverter,
IRegisteredSecurityDataTypesProvider registeredTypes,
PrimaryExchange primaryExchange = PrimaryExchange.UNKNOWN)
: base(
config,
quoteCurrency,
symbolProperties,
new EquityExchange(exchangeHours),
new EquityCache(),
new SecurityPortfolioModel(),
new EquityFillModel(),
new InteractiveBrokersFeeModel(),
new ConstantSlippageModel(0m),
new ImmediateSettlementModel(),
Securities.VolatilityModel.Null,
new SecurityMarginModel(2m),
new EquityDataFilter(),
new AdjustedPriceVariationModel(),
currencyConverter,
registeredTypes
)
{
Holdings = new EquityHolding(this, currencyConverter);
PrimaryExchange = primaryExchange;
}
/// <summary>
/// Sets the data normalization mode to be used by this security
/// </summary>
public override void SetDataNormalizationMode(DataNormalizationMode mode)
{
base.SetDataNormalizationMode(mode);
if (mode == DataNormalizationMode.Adjusted)
{
PriceVariationModel = new AdjustedPriceVariationModel();
}
else
{
PriceVariationModel = new EquityPriceVariationModel();
}
}
}
}
| 38.822368 | 126 | 0.612269 | [
"Apache-2.0"
] | BuildJet/Lean | Common/Securities/Equity/Equity.cs | 5,903 | C# |
using NBitcoin;
using NBitcoin.RPC;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Crypto;
using WalletWasabi.Crypto.Randomness;
using WalletWasabi.Crypto.ZeroKnowledge;
using WalletWasabi.Tests.UnitTests;
using WalletWasabi.WabiSabi.Backend;
using WalletWasabi.WabiSabi.Backend.Banning;
using WalletWasabi.WabiSabi.Backend.Models;
using WalletWasabi.WabiSabi.Backend.Rounds;
using WalletWasabi.WabiSabi.Crypto;
using WalletWasabi.WabiSabi.Crypto.CredentialRequesting;
using WalletWasabi.WabiSabi.Models;
using WalletWasabi.WabiSabi;
using WalletWasabi.Tests.UnitTests.WabiSabi.Backend.PhaseStepping;
namespace WalletWasabi.Tests.Helpers
{
public static class WabiSabiFactory
{
private static readonly int MaxVsizeAllocationPerAlice = (1 << 8) - 1;
public static Coin CreateCoin(OutPoint? prevout = null, Key? key = null, Money? value = null)
=> new(prevout ?? BitcoinFactory.CreateOutPoint(), new TxOut(value ?? Money.Coins(1), BitcoinFactory.CreateScript(key)));
public static OwnershipProof CreateOwnershipProof(Key? key = null, uint256? roundHash = null)
{
var rh = roundHash ?? BitcoinFactory.CreateUint256();
var coinJoinInputCommitmentData = new CoinJoinInputCommitmentData("CoinJoinCoordinatorIdentifier", rh);
return OwnershipProof.GenerateCoinJoinInputProof(key ?? new(), coinJoinInputCommitmentData);
}
public static Round CreateRound(WabiSabiConfig cfg)
=> new(new RoundParameters(
cfg,
Network.Main,
new InsecureRandom(),
new(100m)));
public static async Task<Arena> CreateAndStartArenaAsync(WabiSabiConfig cfg, params Round[] rounds)
=> await CreateAndStartArenaAsync(cfg, null, rounds);
public static async Task<Arena> CreateAndStartArenaAsync(WabiSabiConfig? cfg = null, MockRpcClient? mockRpc = null, params Round[] rounds)
{
mockRpc ??= new MockRpcClient();
mockRpc.OnEstimateSmartFeeAsync ??= async (target, _) =>
await Task.FromResult(new EstimateSmartFeeResponse
{
Blocks = target,
FeeRate = new FeeRate(10m)
});
mockRpc.OnSendRawTransactionAsync ??= (tx) => tx.GetHash();
mockRpc.OnGetTxOutAsync ??= (_, _, _) => new()
{
Confirmations = 1,
ScriptPubKeyType = "witness_v0_keyhash",
TxOut = new(Money.Coins(1), Script.Empty)
};
Arena arena = new(TimeSpan.FromHours(1), rounds.FirstOrDefault()?.Network ?? Network.Main, cfg ?? new WabiSabiConfig(), mockRpc, new Prison());
foreach (var round in rounds)
{
arena.Rounds.Add(round.Id, round);
}
await arena.StartAsync(CancellationToken.None).ConfigureAwait(false);
return arena;
}
public static Alice CreateAlice(Key? key = null, OutPoint? prevout = null, Coin? coin = null, OwnershipProof? ownershipProof = null, Money? value = null)
{
key ??= new();
coin ??= CreateCoin(prevout, key, value);
ownershipProof ??= CreateOwnershipProof(key);
var alice = new Alice(coin, ownershipProof);
alice.Deadline = DateTimeOffset.UtcNow + TimeSpan.FromHours(1);
return alice;
}
public static InputRegistrationRequest CreateInputRegistrationRequest(Key? key = null, Round? round = null, OutPoint? prevout = null)
=> CreateInputRegistrationRequest(prevout ?? BitcoinFactory.CreateOutPoint(), CreateOwnershipProof(key, round?.Id), round);
public static InputRegistrationRequest CreateInputRegistrationRequest(OutPoint prevout, OwnershipProof ownershipProof, Round? round = null)
{
var roundId = round?.Id ?? uint256.Zero;
(var amClient, var vsClient, _, _) = CreateWabiSabiClientsAndIssuers(round);
var (zeroAmountCredentialRequest, _) = amClient.CreateRequestForZeroAmount();
var (zeroVsizeCredentialRequest, _) = vsClient.CreateRequestForZeroAmount();
return new(
roundId,
prevout,
ownershipProof,
zeroAmountCredentialRequest,
zeroVsizeCredentialRequest);
}
public static (WabiSabiClient amountClient, WabiSabiClient vsizeClient, CredentialIssuer amountIssuer, CredentialIssuer vsizeIssuer) CreateWabiSabiClientsAndIssuers(Round? round)
{
var rnd = new InsecureRandom();
var ai = round?.AmountCredentialIssuer ?? new CredentialIssuer(new CredentialIssuerSecretKey(rnd), rnd, 4300000000000);
var wi = round?.VsizeCredentialIssuer ?? new CredentialIssuer(new CredentialIssuerSecretKey(rnd), rnd, 2000ul);
var ac = new WabiSabiClient(
ai.CredentialIssuerSecretKey.ComputeCredentialIssuerParameters(),
rnd,
ai.MaxAmount,
new ZeroCredentialPool());
var wc = new WabiSabiClient(
wi.CredentialIssuerSecretKey.ComputeCredentialIssuerParameters(),
rnd,
wi.MaxAmount,
new ZeroCredentialPool());
return (ac, wc, ai, wi);
}
public static (Credential[] amountCredentials, IEnumerable<Credential> vsizeCredentials) CreateZeroCredentials(Round? round)
{
(var amClient, var vsClient, var amIssuer, var vsIssuer) = CreateWabiSabiClientsAndIssuers(round);
return CreateZeroCredentials(amClient, vsClient, amIssuer, vsIssuer);
}
private static (Credential[] amountCredentials, IEnumerable<Credential> vsizeCredentials) CreateZeroCredentials(WabiSabiClient amClient, WabiSabiClient vsClient, CredentialIssuer amIssuer, CredentialIssuer vsIssuer)
{
var (zeroAmountCredentialRequest, amVal) = amClient.CreateRequestForZeroAmount();
var (zeroVsizeCredentialRequest, vsVal) = vsClient.CreateRequestForZeroAmount();
var amCredResp = amIssuer.HandleRequest(zeroAmountCredentialRequest);
var vsCredResp = vsIssuer.HandleRequest(zeroVsizeCredentialRequest);
amClient.HandleResponse(amCredResp, amVal);
vsClient.HandleResponse(vsCredResp, vsVal);
return (
Array.Empty<Credential>(),
Array.Empty<Credential>());
}
public static (RealCredentialsRequest amountReq, RealCredentialsRequest vsizeReq) CreateRealCredentialRequests(Round? round = null, Money? amount = null, long? vsize = null)
{
var (amClient, vsClient, amIssuer, vsIssuer) = CreateWabiSabiClientsAndIssuers(round);
var zeroPresentables = CreateZeroCredentials(amClient, vsClient, amIssuer, vsIssuer);
var alice = round?.Alices.FirstOrDefault();
var (realAmountCredentialRequest, _) = amClient.CreateRequest(
new[] { amount?.Satoshi ?? alice?.CalculateRemainingAmountCredentials(round!.FeeRate).Satoshi ?? MaxVsizeAllocationPerAlice },
zeroPresentables.amountCredentials,
CancellationToken.None);
var (realVsizeCredentialRequest, _) = vsClient.CreateRequest(
new[] { vsize ?? alice?.CalculateRemainingVsizeCredentials(round!.MaxVsizeAllocationPerAlice) ?? MaxVsizeAllocationPerAlice },
zeroPresentables.vsizeCredentials,
CancellationToken.None);
return (realAmountCredentialRequest, realVsizeCredentialRequest);
}
public static ConnectionConfirmationRequest CreateConnectionConfirmationRequest(Round? round = null)
{
var (amClient, vsClient, amIssuer, vsIssuer) = CreateWabiSabiClientsAndIssuers(round);
var zeroPresentables = CreateZeroCredentials(amClient, vsClient, amIssuer, vsIssuer);
var alice = round?.Alices.FirstOrDefault();
var (realAmountCredentialRequest, _) = amClient.CreateRequest(
new[] { alice?.CalculateRemainingAmountCredentials(round!.FeeRate).Satoshi ?? MaxVsizeAllocationPerAlice },
zeroPresentables.amountCredentials,
CancellationToken.None);
var (realVsizeCredentialRequest, _) = vsClient.CreateRequest(
new[] { alice?.CalculateRemainingVsizeCredentials(round!.MaxVsizeAllocationPerAlice) ?? MaxVsizeAllocationPerAlice },
zeroPresentables.vsizeCredentials,
CancellationToken.None);
var (zeroAmountCredentialRequest, _) = amClient.CreateRequestForZeroAmount();
var (zeroVsizeCredentialRequest, _) = vsClient.CreateRequestForZeroAmount();
return new ConnectionConfirmationRequest(
round?.Id ?? BitcoinFactory.CreateUint256(),
alice?.Id ?? BitcoinFactory.CreateUint256(),
zeroAmountCredentialRequest,
realAmountCredentialRequest,
zeroVsizeCredentialRequest,
realVsizeCredentialRequest);
}
public static IEnumerable<(ConnectionConfirmationRequest request, WabiSabiClient amountClient, WabiSabiClient vsizeClient, CredentialsResponseValidation amountValidation, CredentialsResponseValidation vsizeValidation)> CreateConnectionConfirmationRequests(Round round, params InputRegistrationResponse[] responses)
{
var requests = new List<(ConnectionConfirmationRequest request, WabiSabiClient amountClient, WabiSabiClient vsizeClient, CredentialsResponseValidation amountValidation, CredentialsResponseValidation vsizeValidation)>();
foreach (var resp in responses)
{
requests.Add(CreateConnectionConfirmationRequest(round, resp));
}
return requests.ToArray();
}
public static (ConnectionConfirmationRequest request, WabiSabiClient amountClient, WabiSabiClient vsizeClient, CredentialsResponseValidation amountValidation, CredentialsResponseValidation vsizeValidation) CreateConnectionConfirmationRequest(Round round, InputRegistrationResponse response)
{
var (amClient, vsClient, amIssuer, vsIssuer) = CreateWabiSabiClientsAndIssuers(round);
var zeroPresentables = CreateZeroCredentials(amClient, vsClient, amIssuer, vsIssuer);
var alice = round.Alices.First(x => x.Id == response.AliceId);
var (realAmountCredentialRequest, amVal) = amClient.CreateRequest(
new[] { alice.CalculateRemainingAmountCredentials(round.FeeRate).Satoshi },
zeroPresentables.amountCredentials,
CancellationToken.None);
var (realVsizeCredentialRequest, weVal) = vsClient.CreateRequest(
new[] { alice.CalculateRemainingVsizeCredentials(round.MaxVsizeAllocationPerAlice) },
zeroPresentables.vsizeCredentials,
CancellationToken.None);
var (zeroAmountCredentialRequest, _) = amClient.CreateRequestForZeroAmount();
var (zeroVsizeCredentialRequest, _) = vsClient.CreateRequestForZeroAmount();
return (
new ConnectionConfirmationRequest(
round.Id,
response.AliceId,
zeroAmountCredentialRequest,
realAmountCredentialRequest,
zeroVsizeCredentialRequest,
realVsizeCredentialRequest),
amClient,
vsClient,
amVal,
weVal);
}
public static OutputRegistrationRequest CreateOutputRegistrationRequest(Round? round = null, Script? script = null, int? vsize = null)
{
(var amClient, var vsClient, var amIssuer, var vsIssuer) = CreateWabiSabiClientsAndIssuers(round);
var zeroPresentables = CreateZeroCredentials(amClient, vsClient, amIssuer, vsIssuer);
var alice = round?.Alices.FirstOrDefault();
var (amCredentialRequest, amValid) = amClient.CreateRequest(
new[] { alice?.CalculateRemainingAmountCredentials(round!.FeeRate).Satoshi ?? MaxVsizeAllocationPerAlice },
zeroPresentables.amountCredentials,
CancellationToken.None);
long startingVsizeCredentialAmount = alice?.CalculateRemainingVsizeCredentials(round!.MaxVsizeAllocationPerAlice) ?? MaxVsizeAllocationPerAlice;
var (vsCredentialRequest, weValid) = vsClient.CreateRequest(
new[] { startingVsizeCredentialAmount },
zeroPresentables.vsizeCredentials,
CancellationToken.None);
var amResp = amIssuer.HandleRequest(amCredentialRequest);
var weResp = vsIssuer.HandleRequest(vsCredentialRequest);
var amountCredentials = amClient.HandleResponse(amResp, amValid);
var vsizeCredentials = vsClient.HandleResponse(weResp, weValid);
script ??= BitcoinFactory.CreateScript();
var (realAmountCredentialRequest, _) = amClient.CreateRequest(
Array.Empty<long>(),
amountCredentials,
CancellationToken.None);
try
{
vsize ??= script.EstimateOutputVsize();
}
catch (NotImplementedException)
{
vsize = 25;
}
var (realVsizeCredentialRequest, _) = vsClient.CreateRequest(
new[] { startingVsizeCredentialAmount - (long)vsize },
vsizeCredentials,
CancellationToken.None);
return new OutputRegistrationRequest(
round?.Id ?? uint256.Zero,
script,
realAmountCredentialRequest,
realVsizeCredentialRequest);
}
public static IEnumerable<OutputRegistrationRequest> CreateOutputRegistrationRequests(Round round, IEnumerable<(ConnectionConfirmationResponse resp, WabiSabiClient amountClient, WabiSabiClient vsizeClient, uint256 aliceId, IEnumerable<Credential> amountCredentials, IEnumerable<Credential> vsizeCredentials)> ccresps)
{
var ret = new List<OutputRegistrationRequest>();
foreach (var ccresp in ccresps)
{
var alice = round.Alices.First(x => x.Id == ccresp.aliceId);
var startingVsizeCredentialAmount = alice.CalculateRemainingVsizeCredentials(round!.MaxVsizeAllocationPerAlice);
var script = BitcoinFactory.CreateScript();
var vsize = script.EstimateOutputVsize();
var amountCredentialRequestData = ccresp.amountClient.CreateRequest(Array.Empty<long>(), ccresp.amountCredentials, CancellationToken.None);
var vsizeCredentialRequestData = ccresp.vsizeClient.CreateRequest(new[] { startingVsizeCredentialAmount - vsize }, ccresp.vsizeCredentials, CancellationToken.None);
ret.Add(new OutputRegistrationRequest(
round.Id,
script,
amountCredentialRequestData.CredentialsRequest,
vsizeCredentialRequestData.CredentialsRequest));
}
return ret;
}
public static Round CreateBlameRound(Round round, WabiSabiConfig cfg)
{
RoundParameters parameters = new(cfg, round.Network, new InsecureRandom(), round.FeeRate, blameOf: round);
return new(parameters);
}
public static MockRpcClient CreateMockRpc(Key? key = null)
{
MockRpcClient rpc = new();
rpc.OnGetTxOutAsync = (_, _, _) => new()
{
Confirmations = 1,
ScriptPubKeyType = "witness_v0_keyhash",
TxOut = new(Money.Coins(1), key?.PubKey.GetSegwitAddress(Network.Main).ScriptPubKey ?? Script.Empty)
};
return rpc;
}
}
}
| 42.872671 | 319 | 0.769794 | [
"MIT"
] | kristapsk/WalletWasabi | WalletWasabi.Tests/Helpers/WabiSabiFactory.cs | 13,805 | C# |
// Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.0.6365, generator: {generator})
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Commvault.Powershell.Models
{
using Commvault.Powershell.Runtime.PowerShell;
/// <summary>
/// A PowerShell PSTypeConverter to support converting to an instance of <see cref="UserNamePassword" />
/// </summary>
public partial class UserNamePasswordTypeConverter : global::System.Management.Automation.PSTypeConverter
{
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>.
/// </returns>
public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue);
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="UserNamePassword"
/// /> type.</param>
/// <returns>
/// <c>true</c> if the instance could be converted to a <see cref="UserNamePassword" /> type, otherwise <c>false</c>
/// </returns>
public static bool CanConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return true;
}
global::System.Type type = sourceValue.GetType();
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
// we say yest to PSObjects
return true;
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
// we say yest to Hashtables/dictionaries
return true;
}
try
{
if (null != sourceValue.ToJsonString())
{
return true;
}
}
catch
{
// Not one of our objects
}
try
{
string text = sourceValue.ToString()?.Trim();
return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Commvault.Powershell.Runtime.Json.JsonNode.Parse(text).Type == Commvault.Powershell.Runtime.Json.JsonType.Object;
}
catch
{
// Doesn't look like it can be treated as JSON
}
return false;
}
/// <summary>
/// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>
/// </returns>
public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false;
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>
/// an instance of <see cref="UserNamePassword" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the value to convert into an instance of <see cref="UserNamePassword" />.</param>
/// <returns>
/// an instance of <see cref="UserNamePassword" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public static Commvault.Powershell.Models.IUserNamePassword ConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return null;
}
global::System.Type type = sourceValue.GetType();
if (typeof(Commvault.Powershell.Models.IUserNamePassword).IsAssignableFrom(type))
{
return sourceValue;
}
try
{
return UserNamePassword.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());;
}
catch
{
// Unable to use JSON pattern
}
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
return UserNamePassword.DeserializeFromPSObject(sourceValue);
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
return UserNamePassword.DeserializeFromDictionary(sourceValue);
}
return null;
}
/// <summary>NotImplemented -- this will return <c>null</c></summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>will always return <c>null</c>.</returns>
public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null;
}
} | 49.441379 | 200 | 0.591017 | [
"MIT"
] | Commvault/CVPowershellSDKV2 | generated/api/Models/UserNamePassword.TypeConverter.cs | 7,169 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace GF.Common
{
public class PropDef : IDisposable
{
//-----------------------------------------------------------------------------
public bool CollectDirty { get; private set; }
private string mPropKey;
private Type mValueType;
//-----------------------------------------------------------------------------
public PropDef(string key, Type value_type, bool collect_dirty = true)
{
mPropKey = key;
mValueType = value_type;
CollectDirty = collect_dirty;
}
//-----------------------------------------------------------------------------
~PropDef()
{
this.Dispose(false);
}
//-----------------------------------------------------------------------------
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
//-----------------------------------------------------------------------------
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
}
}
//-----------------------------------------------------------------------------
public string getKey()
{
return mPropKey;
}
//-----------------------------------------------------------------------------
public Type getValueType()
{
return mValueType;
}
}
}
| 28.25 | 87 | 0.309102 | [
"MIT"
] | corefan/Fishing | Client/Assets/Plugins/GF.Common/Entity/PropDef.cs | 1,584 | C# |
using NKnife.Storages.SQL.Common;
using NKnife.Storages.SQL.Linq;
using NKnife.Storages.SQL.Realisations.Queries;
using NKnife.Storages.UnitTests.SQL.DataBase;
using Xunit;
namespace NKnife.Storages.UnitTests.SQL.Tests.Linq
{
public class LinqDelete
{
[Fact]
public void LinqDeleteSimple()
{
SuperSql.DefaultFormatter = FormatterLibrary.MsSql;
var q1 = new Delete<Author>();
var result = q1.GetSql();
var sql = "DELETE FROM [tab_authors];";
Assert.Equal(result, sql);
}
[Fact]
public void LinqDeleteSimpleWhere()
{
SuperSql.DefaultFormatter = FormatterLibrary.MsSql;
var q1 = new Delete<Author>();
q1.Where(x => x.Equal("a").IsNULL("b"));
var result = q1.GetSql();
var sql = "DELETE FROM [tab_authors] WHERE [a]=@a AND [b] IS NULL;";
Assert.Equal(result, sql);
}
[Fact]
public void LinqDeleteTableAlias()
{
SuperSql.DefaultFormatter = FormatterLibrary.MsSql;
var result = Query<Author>.CreateDelete("t").Where(x => x.Equal("a")).GetSql();
var sql = "DELETE FROM [tab_authors] as [t] WHERE [t].[a]=@a;";
Assert.Equal(result, sql);
}
[Fact]
public void LinqQueryDeleteSimpleWhere()
{
SuperSql.DefaultFormatter = FormatterLibrary.MsSql;
var result = Query<Author>.CreateDelete().Where(x => x.Equal("a")).GetSql();
var sql = "DELETE FROM [tab_authors] WHERE [a]=@a;";
Assert.Equal(result, sql);
}
}
} | 30.981481 | 91 | 0.567842 | [
"MIT"
] | xknife-erian/nknife | UnitTests/NKnife.Storages.UnitTests/SQL/Tests/Linq/LinqDelete.cs | 1,675 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.