content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
namespace JdSharp.JarDecompiler.JavaAttributes
{
public class ConstantValueAttribute : BaseAttribute
{
public string ConstantValue { get; }
public ConstantValueAttribute(string constantValue)
{
ConstantValue = constantValue;
}
}
} | 24 | 59 | 0.659722 | [
"Apache-2.0"
] | guilhermerochas/JdSharp | JdSharp.JarDecompiler/JavaAttributes/ConstantValueAttribute.cs | 290 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using RestEase;
using Bitmovin.Api.Sdk.Common;
using Bitmovin.Api.Sdk.Encoding.Encodings.Muxings.ChunkedText.Customdata;
namespace Bitmovin.Api.Sdk.Encoding.Encodings.Muxings.ChunkedText
{
public class ChunkedTextApi
{
private readonly IChunkedTextApiClient _apiClient;
public ChunkedTextApi(IBitmovinApiClientFactory apiClientFactory)
{
_apiClient = apiClientFactory.CreateClient<IChunkedTextApiClient>();
Customdata = new CustomdataApi(apiClientFactory);
}
/// <summary>
/// Fluent builder for creating an instance of ChunkedTextApi
/// </summary>
public static BitmovinApiBuilder<ChunkedTextApi> Builder => new BitmovinApiBuilder<ChunkedTextApi>();
public CustomdataApi Customdata { get; }
/// <summary>
/// Add Chunked Text muxing
/// </summary>
/// <param name="encodingId">Id of the encoding. (required)</param>
/// <param name="chunkedTextMuxing">The Chunked Text muxing to be created</param>
public async Task<Models.ChunkedTextMuxing> CreateAsync(string encodingId, Models.ChunkedTextMuxing chunkedTextMuxing)
{
return await _apiClient.CreateAsync(encodingId, chunkedTextMuxing);
}
/// <summary>
/// Delete Chunked Text muxing
/// </summary>
/// <param name="encodingId">Id of the encoding. (required)</param>
/// <param name="muxingId">Id of the Chunked Text muxing (required)</param>
public async Task<Models.BitmovinResponse> DeleteAsync(string encodingId, string muxingId)
{
return await _apiClient.DeleteAsync(encodingId, muxingId);
}
/// <summary>
/// Chunked Text muxing details
/// </summary>
/// <param name="encodingId">Id of the encoding. (required)</param>
/// <param name="muxingId">Id of the Chunked Text muxing (required)</param>
public async Task<Models.ChunkedTextMuxing> GetAsync(string encodingId, string muxingId)
{
return await _apiClient.GetAsync(encodingId, muxingId);
}
/// <summary>
/// List Chunked Text muxings
/// </summary>
/// <param name="encodingId">Id of the encoding. (required)</param>
/// <param name="queryParams">The query parameters for sorting, filtering and paging options (optional)</param>
public async Task<Models.PaginationResponse<Models.ChunkedTextMuxing>> ListAsync(string encodingId, params Func<ListQueryParams, ListQueryParams>[] queryParams)
{
ListQueryParams q = new ListQueryParams();
foreach (var builderFunc in queryParams)
{
builderFunc(q);
}
return await _apiClient.ListAsync(encodingId, q);
}
internal interface IChunkedTextApiClient
{
[Post("/encoding/encodings/{encoding_id}/muxings/chunked-text")]
[AllowAnyStatusCode]
Task<Models.ChunkedTextMuxing> CreateAsync([Path("encoding_id")] string encodingId, [Body] Models.ChunkedTextMuxing chunkedTextMuxing);
[Delete("/encoding/encodings/{encoding_id}/muxings/chunked-text/{muxing_id}")]
[AllowAnyStatusCode]
Task<Models.BitmovinResponse> DeleteAsync([Path("encoding_id")] string encodingId, [Path("muxing_id")] string muxingId);
[Get("/encoding/encodings/{encoding_id}/muxings/chunked-text/{muxing_id}")]
[AllowAnyStatusCode]
Task<Models.ChunkedTextMuxing> GetAsync([Path("encoding_id")] string encodingId, [Path("muxing_id")] string muxingId);
[Get("/encoding/encodings/{encoding_id}/muxings/chunked-text")]
[AllowAnyStatusCode]
Task<Models.PaginationResponse<Models.ChunkedTextMuxing>> ListAsync([Path("encoding_id")] string encodingId, [QueryMap(SerializationMethod = QuerySerializationMethod.Serialized)] IDictionary<String, Object> queryParams);
}
public class ListQueryParams : Dictionary<string,Object>
{
/// <summary>
/// Index of the first item to return, starting at 0. Default is 0
/// </summary>
public ListQueryParams Offset(int? offset) => SetQueryParam("offset", offset);
/// <summary>
/// Maximum number of items to return. Default is 25, maximum is 100
/// </summary>
public ListQueryParams Limit(int? limit) => SetQueryParam("limit", limit);
private ListQueryParams SetQueryParam<T>(string key, T value)
{
if (value != null)
{
this[key] = value;
}
return this;
}
}
}
}
| 41.618644 | 232 | 0.634698 | [
"MIT"
] | bitmovin/bitmovin-api-sdk-dotnet | src/Bitmovin.Api.Sdk/Encoding/Encodings/Muxings/ChunkedText/ChunkedTextApi.cs | 4,911 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace ClusterAnalysis.AnalysisCore.Callback
{
using System;
using System.Globalization;
using System.Runtime.Serialization;
/// <summary>
/// Describe the filter for notify
/// </summary>
[DataContract]
public class NotifyFilter
{
/// <summary>
/// Create an instance of <see cref="NotifyFilter"/>
/// </summary>
/// <param name="targetScenario"></param>
/// <param name="signalAvailableForAtLeastDuration"></param>
public NotifyFilter(Scenario targetScenario, TimeSpan signalAvailableForAtLeastDuration)
{
this.TargetScenario = targetScenario;
this.SignalAvailableForAtLeastDuration = signalAvailableForAtLeastDuration;
}
/// <summary>
/// Scenario for this filter
/// </summary>
[DataMember(IsRequired = true)]
public Scenario TargetScenario { get; private set; }
/// <summary>
/// How long should a signal be available for before we report it.
/// </summary>
[DataMember(IsRequired = true)]
public TimeSpan SignalAvailableForAtLeastDuration { get; private set; }
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"Scenario: '{0}', SignalAvailableForAtLeastDuration: '{1}'",
this.TargetScenario,
this.SignalAvailableForAtLeastDuration);
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked
{
int hash = 17;
hash = (hash * 23) + this.TargetScenario.ToString().GetHashCode();
hash = (hash * 23) + this.SignalAvailableForAtLeastDuration.GetHashCode();
return hash;
}
}
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
var other = obj as NotifyFilter;
if (other == null)
{
return false;
}
return this.TargetScenario == other.TargetScenario && this.SignalAvailableForAtLeastDuration == other.SignalAvailableForAtLeastDuration;
}
}
} | 33.384615 | 148 | 0.547235 | [
"MIT"
] | AndreyTretyak/service-fabric | src/prod/src/managed/ClusterAnalysis/AnalysisCore/Callback/NotifyFilter.cs | 2,606 | C# |
using System.Linq;
using Xunit;
using System.Threading.Tasks;
namespace IntegrationTests
{
public partial class ValuesApiIntegration
{
[Fact]
public void TestValuesGet()
{
//var task = authorizedClient.GetStringAsync(new Uri(baseUri, "api/Values"));
//var text = task.Result;
//var array = JArray.Parse(text);
var array = api.Get();
Assert.Equal("value2", array[1]);
}
[Fact]
public void TestValuesGetId()
{
//UriBuilder builder = new UriBuilder(new Uri(baseUri, "api/Values"));
//var query = System.Web.HttpUtility.ParseQueryString(builder.Query);
//query.Add("id", "1");
//query.Add("name", "something to say");
//builder.Query = query.ToString();
//var task = authorizedClient.GetStringAsync(builder.ToString());
//var text = task.Result;
//var jObject = JValue.Parse(text);
var r = api.Get(1, "something to say中文\\`-=|~!@#$%^&*()_+/|?[]{},.';<>:\"");
Assert.Equal("something to say中文\\`-=|~!@#$%^&*()_+/|?[]{},.';<>:\"1", r);
}
[Fact]
public void TestGetName()
{
Assert.Equal("ABC", api.Get("Abc"));
}
[Fact]
public void TestValuesPost()
{
//var t = authorizedClient.PostAsync(new Uri(baseUri, "api/Values")
// , new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("", "value") }));
//var ok = t.Result.IsSuccessStatusCode;
//Assert.True(ok);
//var text = t.Result.Content.ReadAsStringAsync().Result;
//var jObject = JValue.Parse(text);
//Assert.Equal("VALUE", jObject.ToObject<string>());
var t = api.Post("value");
Assert.Equal("VALUE", t);
}
[Fact]
public async Task TestValuesPostAsync()
{
var t = await api.PostAsync("value");
Assert.Equal("VALUE", t);
}
[Fact]
public void TestValuesPut2()
{
//var t = authorizedClient.PutAsync(new Uri(baseUri, "api/Values?id=1"), new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("", "value") }));
//var ok = t.Result.IsSuccessStatusCode;
//Assert.True(ok);
api.Put(1, "value");
}
[Fact]
public void TestValuesDelete()
{
//var t = authorizedClient.DeleteAsync(new Uri(baseUri, "api/Values/1"));
//var ok = t.Result.IsSuccessStatusCode;
//Assert.True(ok);
api.Delete(1);
}
}
}
| 27.268293 | 160 | 0.629696 | [
"MIT"
] | Niklas007CR7/webapiclientgen | Tests/IntegrationTestsShared/ValuesApiIntegration.cs | 2,246 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main()
{
List<int> numbers = Console.ReadLine()
.Split()
.Select(int.Parse)
.ToList();
string command = Console.ReadLine();
while (command != "end")
{
int number = int.Parse(command);
int index = int.Parse(command[0].ToString());
numbers.Insert(index,number);
command = Console.ReadLine();
}
Console.WriteLine($"{string.Join(" ",numbers)}");
}
}
| 21.333333 | 57 | 0.551563 | [
"MIT"
] | radoslavvv/Programming-Fundamentals-Extended-May-2017 | Exercises/08.ListsMoreExercises/02.IntegerInsertion/02.IntegerInsertion.cs | 642 | C# |
using Domain;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace Persistence
{
public class DataContext : IdentityDbContext<AppUser>
{
public DataContext(DbContextOptions options) : base(options)
{
}
public DbSet<Value> Values { get; set; }
public DbSet<Activity> Activities { get; set; }
public DbSet<UserActivity> UserActivities { get; set; }
public DbSet<Photo> Photos { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<UserFollowing> Followings { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Value>()
.HasData(
new Value {Id = 1, Name = "Jinnat Morol"},
new Value {Id = 2, Name = "Farhana"}
);
builder.Entity<UserActivity>()
.HasKey(x => new {
x.ActivityId,
x.AppUserId
});
builder.Entity<UserActivity>()
.HasOne(user => user.AppUser)
.WithMany(activity => activity.UserActivities)
.HasForeignKey(user => user.AppUserId);
builder.Entity<UserActivity>()
.HasOne(activity => activity.Activity)
.WithMany(user => user.UserActivities)
.HasForeignKey(activity => activity.ActivityId);
builder.Entity<UserFollowing>(b =>
{
b.HasKey(k => new {k.ObserverId, k.TargetId});
b.HasOne(o => o.Observer)
.WithMany(f => f.Followings)
.HasForeignKey(o => o.ObserverId)
.OnDelete(DeleteBehavior.Restrict);
b.HasOne(o => o.Target)
.WithMany(f => f.Followers)
.HasForeignKey(o => o.TargetId)
.OnDelete(DeleteBehavior.Restrict);
});
}
}
}
| 32.761194 | 70 | 0.502506 | [
"MIT"
] | jinnatul/e-Activities | Persistence/DataContext.cs | 2,197 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.Azure.IIoT.OpcUa.Twin.Models {
using System.Collections.Generic;
/// <summary>
/// Result of batch calls
/// </summary>
public class BatchServiceCallResultModel :
List<ServiceCallResultModel> {
}
}
| 33.9375 | 99 | 0.53407 | [
"MIT"
] | Azure/Industrial-IoT | components/opc-ua/src/Microsoft.Azure.IIoT.OpcUa/src/Twin/Models/BatchServiceCallResultModel.cs | 543 | C# |
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Skoruba.IdentityServer4.Admin.BusinessLogic.Dtos.Configuration;
using Skoruba.IdentityServer4.Admin.BusinessLogic.Helpers;
using Skoruba.IdentityServer4.Admin.BusinessLogic.Services.Interfaces;
using Skoruba.IdentityServer4.Admin.UI.Configuration.Constants;
using Skoruba.IdentityServer4.Admin.UI.ExceptionHandling;
using Skoruba.IdentityServer4.Admin.UI.Helpers;
namespace Skoruba.IdentityServer4.Admin.UI.Areas.AdminUI.Controllers
{
[TypeFilter(typeof(ControllerExceptionFilterAttribute))]
[Area(CommonConsts.AdminUIArea)]
public class ConfigurationController : BaseController
{
private readonly IIdentityResourceService _identityResourceService;
private readonly IApiResourceService _apiResourceService;
private readonly IClientService _clientService;
private readonly IStringLocalizer<ConfigurationController> _localizer;
private readonly IApiScopeService _apiScopeService;
public ConfigurationController(IIdentityResourceService identityResourceService,
IApiResourceService apiResourceService,
IClientService clientService,
IStringLocalizer<ConfigurationController> localizer,
ILogger<ConfigurationController> logger,
IApiScopeService apiScopeService)
: base(logger)
{
_identityResourceService = identityResourceService;
_apiResourceService = apiResourceService;
_clientService = clientService;
_localizer = localizer;
_apiScopeService = apiScopeService;
}
public async Task<IActionResult> Client(string id)
{
if (id.IsNotPresentedValidNumber())
{
return NotFound();
}
if (id == default)
{
var clientDto = _clientService.BuildClientViewModel();
return View(clientDto);
}
int.TryParse(id, out var clientId);
var client = await _clientService.GetClientAsync(clientId);
client = _clientService.BuildClientViewModel(client);
return View(client);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Client(ClientDto client)
{
client = _clientService.BuildClientViewModel(client);
if (!ModelState.IsValid)
{
return View(client);
}
//Add new client
if (client.Id == 0)
{
var clientId = await _clientService.AddClientAsync(client);
SuccessNotification(string.Format(_localizer["SuccessAddClient"], client.ClientId), _localizer["SuccessTitle"]);
return RedirectToAction(nameof(Client), new { Id = clientId });
}
//Update client
await _clientService.UpdateClientAsync(client);
SuccessNotification(string.Format(_localizer["SuccessUpdateClient"], client.ClientId), _localizer["SuccessTitle"]);
return RedirectToAction(nameof(Client), new { client.Id });
}
[HttpGet]
public async Task<IActionResult> ClientClone(int id)
{
if (id == 0) return NotFound();
var clientDto = await _clientService.GetClientAsync(id);
var client = _clientService.BuildClientCloneViewModel(id, clientDto);
return View(client);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ClientClone(ClientCloneDto client)
{
if (!ModelState.IsValid)
{
return View(client);
}
var newClientId = await _clientService.CloneClientAsync(client);
SuccessNotification(string.Format(_localizer["SuccessClientClone"], client.ClientId), _localizer["SuccessTitle"]);
return RedirectToAction(nameof(Client), new { Id = newClientId });
}
[HttpGet]
public async Task<IActionResult> ClientDelete(int id)
{
if (id == 0) return NotFound();
var client = await _clientService.GetClientAsync(id);
return View(client);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ClientDelete(ClientDto client)
{
await _clientService.RemoveClientAsync(client);
SuccessNotification(_localizer["SuccessClientDelete"], _localizer["SuccessTitle"]);
return RedirectToAction(nameof(Clients));
}
[HttpGet]
public async Task<IActionResult> ClientClaims(int id, int? page)
{
if (id == 0) return NotFound();
var claims = await _clientService.GetClientClaimsAsync(id, page ?? 1);
return View(claims);
}
[HttpGet]
public async Task<IActionResult> ClientProperties(int id, int? page)
{
if (id == 0) return NotFound();
var properties = await _clientService.GetClientPropertiesAsync(id, page ?? 1);
return View(properties);
}
[HttpGet]
public async Task<IActionResult> ApiResourceProperties(int id, int? page)
{
if (id == 0) return NotFound();
var properties = await _apiResourceService.GetApiResourcePropertiesAsync(id, page ?? 1);
return View(properties);
}
[HttpGet]
public async Task<IActionResult> ApiScopeProperties(int id, int? page)
{
if (id == 0) return NotFound();
var properties = await _apiScopeService.GetApiScopePropertiesAsync(id, page ?? 1);
return View(properties);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ApiScopeProperties(ApiScopePropertiesDto apiScopeProperty)
{
if (!ModelState.IsValid)
{
return View(apiScopeProperty);
}
await _apiScopeService.AddApiScopePropertyAsync(apiScopeProperty);
SuccessNotification(string.Format(_localizer["SuccessAddApiScopeProperty"], apiScopeProperty.Key, apiScopeProperty.ApiScopeName), _localizer["SuccessTitle"]);
return RedirectToAction(nameof(ApiScopeProperties), new { Id = apiScopeProperty.ApiScopeId });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ApiResourceProperties(ApiResourcePropertiesDto apiResourceProperty)
{
if (!ModelState.IsValid)
{
return View(apiResourceProperty);
}
await _apiResourceService.AddApiResourcePropertyAsync(apiResourceProperty);
SuccessNotification(string.Format(_localizer["SuccessAddApiResourceProperty"], apiResourceProperty.Key, apiResourceProperty.ApiResourceName), _localizer["SuccessTitle"]);
return RedirectToAction(nameof(ApiResourceProperties), new { Id = apiResourceProperty.ApiResourceId });
}
[HttpGet]
public async Task<IActionResult> IdentityResourceProperties(int id, int? page)
{
if (id == 0) return NotFound();
var properties = await _identityResourceService.GetIdentityResourcePropertiesAsync(id, page ?? 1);
return View(properties);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> IdentityResourceProperties(IdentityResourcePropertiesDto identityResourceProperty)
{
if (!ModelState.IsValid)
{
return View(identityResourceProperty);
}
await _identityResourceService.AddIdentityResourcePropertyAsync(identityResourceProperty);
SuccessNotification(string.Format(_localizer["SuccessAddIdentityResourceProperty"], identityResourceProperty.Value, identityResourceProperty.IdentityResourceName), _localizer["SuccessTitle"]);
return RedirectToAction(nameof(IdentityResourceProperties), new { Id = identityResourceProperty.IdentityResourceId });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ClientProperties(ClientPropertiesDto clientProperty)
{
if (!ModelState.IsValid)
{
return View(clientProperty);
}
await _clientService.AddClientPropertyAsync(clientProperty);
SuccessNotification(string.Format(_localizer["SuccessAddClientProperty"], clientProperty.ClientId, clientProperty.ClientName), _localizer["SuccessTitle"]);
return RedirectToAction(nameof(ClientProperties), new { Id = clientProperty.ClientId });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ClientClaims(ClientClaimsDto clientClaim)
{
if (!ModelState.IsValid)
{
return View(clientClaim);
}
await _clientService.AddClientClaimAsync(clientClaim);
SuccessNotification(string.Format(_localizer["SuccessAddClientClaim"], clientClaim.Value, clientClaim.ClientName), _localizer["SuccessTitle"]);
return RedirectToAction(nameof(ClientClaims), new { Id = clientClaim.ClientId });
}
[HttpGet]
public async Task<IActionResult> ClientClaimDelete(int id)
{
if (id == 0) return NotFound();
var clientClaim = await _clientService.GetClientClaimAsync(id);
return View(nameof(ClientClaimDelete), clientClaim);
}
[HttpGet]
public async Task<IActionResult> ClientPropertyDelete(int id)
{
if (id == 0) return NotFound();
var clientProperty = await _clientService.GetClientPropertyAsync(id);
return View(nameof(ClientPropertyDelete), clientProperty);
}
[HttpGet]
public async Task<IActionResult> ApiResourcePropertyDelete(int id)
{
if (id == 0) return NotFound();
var apiResourceProperty = await _apiResourceService.GetApiResourcePropertyAsync(id);
return View(nameof(ApiResourcePropertyDelete), apiResourceProperty);
}
[HttpGet]
public async Task<IActionResult> ApiScopePropertyDelete(int id)
{
if (id == 0) return NotFound();
var apiScopeProperty = await _apiScopeService.GetApiScopePropertyAsync(id);
return View(nameof(ApiScopePropertyDelete), apiScopeProperty);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ApiScopePropertyDelete(ApiScopePropertiesDto apiScopeProperty)
{
await _apiScopeService.DeleteApiScopePropertyAsync(apiScopeProperty);
SuccessNotification(_localizer["SuccessDeleteApiScopeProperty"], _localizer["SuccessTitle"]);
return RedirectToAction(nameof(ApiScopeProperties), new { Id = apiScopeProperty.ApiScopeId });
}
[HttpGet]
public async Task<IActionResult> IdentityResourcePropertyDelete(int id)
{
if (id == 0) return NotFound();
var identityResourceProperty = await _identityResourceService.GetIdentityResourcePropertyAsync(id);
return View(nameof(IdentityResourcePropertyDelete), identityResourceProperty);
}
[HttpPost]
public async Task<IActionResult> ClientClaimDelete(ClientClaimsDto clientClaim)
{
await _clientService.DeleteClientClaimAsync(clientClaim);
SuccessNotification(_localizer["SuccessDeleteClientClaim"], _localizer["SuccessTitle"]);
return RedirectToAction(nameof(ClientClaims), new { Id = clientClaim.ClientId });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ClientPropertyDelete(ClientPropertiesDto clientProperty)
{
await _clientService.DeleteClientPropertyAsync(clientProperty);
SuccessNotification(_localizer["SuccessDeleteClientProperty"], _localizer["SuccessTitle"]);
return RedirectToAction(nameof(ClientProperties), new { Id = clientProperty.ClientId });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ApiResourcePropertyDelete(ApiResourcePropertiesDto apiResourceProperty)
{
await _apiResourceService.DeleteApiResourcePropertyAsync(apiResourceProperty);
SuccessNotification(_localizer["SuccessDeleteApiResourceProperty"], _localizer["SuccessTitle"]);
return RedirectToAction(nameof(ApiResourceProperties), new { Id = apiResourceProperty.ApiResourceId });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> IdentityResourcePropertyDelete(IdentityResourcePropertiesDto identityResourceProperty)
{
await _identityResourceService.DeleteIdentityResourcePropertyAsync(identityResourceProperty);
SuccessNotification(_localizer["SuccessDeleteIdentityResourceProperty"], _localizer["SuccessTitle"]);
return RedirectToAction(nameof(IdentityResourceProperties), new { Id = identityResourceProperty.IdentityResourceId });
}
[HttpGet]
public async Task<IActionResult> ClientSecrets(int id, int? page)
{
if (id == 0) return NotFound();
var clientSecrets = await _clientService.GetClientSecretsAsync(id, page ?? 1);
_clientService.BuildClientSecretsViewModel(clientSecrets);
return View(clientSecrets);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ClientSecrets(ClientSecretsDto clientSecret)
{
await _clientService.AddClientSecretAsync(clientSecret);
SuccessNotification(string.Format(_localizer["SuccessAddClientSecret"], clientSecret.ClientName), _localizer["SuccessTitle"]);
return RedirectToAction(nameof(ClientSecrets), new { Id = clientSecret.ClientId });
}
[HttpGet]
public async Task<IActionResult> ClientSecretDelete(int id)
{
if (id == 0) return NotFound();
var clientSecret = await _clientService.GetClientSecretAsync(id);
return View(nameof(ClientSecretDelete), clientSecret);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ClientSecretDelete(ClientSecretsDto clientSecret)
{
await _clientService.DeleteClientSecretAsync(clientSecret);
SuccessNotification(_localizer["SuccessDeleteClientSecret"], _localizer["SuccessTitle"]);
return RedirectToAction(nameof(ClientSecrets), new { Id = clientSecret.ClientId });
}
[HttpGet]
public async Task<IActionResult> SearchScopes(string scope, int limit = 0)
{
var scopes = await _clientService.GetScopesAsync(scope, limit);
return Ok(scopes);
}
[HttpGet]
public async Task<IActionResult> SearchApiScopes(string scope, int limit = 0)
{
var scopes = await _apiScopeService.GetApiScopesNameAsync(scope, limit);
return Ok(scopes.ToList());
}
[HttpGet]
public IActionResult SearchClaims(string claim, int limit = 0)
{
var claims = _clientService.GetStandardClaims(claim, limit);
return Ok(claims);
}
[HttpGet]
public IActionResult SearchSigningAlgorithms(string algorithm, int limit = 0)
{
var signingAlgorithms = _clientService.GetSigningAlgorithms(algorithm, limit);
return Ok(signingAlgorithms);
}
[HttpGet]
public IActionResult SearchGrantTypes(string grant, int limit = 0)
{
var grants = _clientService.GetGrantTypes(grant, limit);
return Ok(grants);
}
[HttpGet]
public async Task<IActionResult> Clients(int? page, string search)
{
ViewBag.Search = search;
return View(await _clientService.GetClientsAsync(search, page ?? 1));
}
[HttpGet]
public async Task<IActionResult> IdentityResourceDelete(int id)
{
if (id == 0) return NotFound();
var identityResource = await _identityResourceService.GetIdentityResourceAsync(id);
return View(identityResource);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> IdentityResourceDelete(IdentityResourceDto identityResource)
{
await _identityResourceService.DeleteIdentityResourceAsync(identityResource);
SuccessNotification(_localizer["SuccessDeleteIdentityResource"], _localizer["SuccessTitle"]);
return RedirectToAction(nameof(IdentityResources));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> IdentityResource(IdentityResourceDto identityResource)
{
if (!ModelState.IsValid)
{
return View(identityResource);
}
identityResource = _identityResourceService.BuildIdentityResourceViewModel(identityResource);
int identityResourceId;
if (identityResource.Id == 0)
{
identityResourceId = await _identityResourceService.AddIdentityResourceAsync(identityResource);
}
else
{
identityResourceId = identityResource.Id;
await _identityResourceService.UpdateIdentityResourceAsync(identityResource);
}
SuccessNotification(string.Format(_localizer["SuccessAddIdentityResource"], identityResource.Name), _localizer["SuccessTitle"]);
return RedirectToAction(nameof(IdentityResource), new { Id = identityResourceId });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ApiResource(ApiResourceDto apiResource)
{
if (!ModelState.IsValid)
{
return View(apiResource);
}
ComboBoxHelpers.PopulateValuesToList(apiResource.UserClaimsItems, apiResource.UserClaims);
ComboBoxHelpers.PopulateValuesToList(apiResource.ScopesItems, apiResource.Scopes);
ComboBoxHelpers.PopulateValuesToList(apiResource.AllowedAccessTokenSigningAlgorithmsItems, apiResource.AllowedAccessTokenSigningAlgorithms);
int apiResourceId;
if (apiResource.Id == 0)
{
apiResourceId = await _apiResourceService.AddApiResourceAsync(apiResource);
}
else
{
apiResourceId = apiResource.Id;
await _apiResourceService.UpdateApiResourceAsync(apiResource);
}
SuccessNotification(string.Format(_localizer["SuccessAddApiResource"], apiResource.Name), _localizer["SuccessTitle"]);
return RedirectToAction(nameof(ApiResource), new { Id = apiResourceId });
}
[HttpGet]
public async Task<IActionResult> ApiResourceDelete(int id)
{
if (id == 0) return NotFound();
var apiResource = await _apiResourceService.GetApiResourceAsync(id);
return View(apiResource);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ApiResourceDelete(ApiResourceDto apiResource)
{
await _apiResourceService.DeleteApiResourceAsync(apiResource);
SuccessNotification(_localizer["SuccessDeleteApiResource"], _localizer["SuccessTitle"]);
return RedirectToAction(nameof(ApiResources));
}
[HttpGet]
public async Task<IActionResult> ApiResource(string id)
{
if (id.IsNotPresentedValidNumber())
{
return NotFound();
}
if (id == default)
{
var apiResourceDto = new ApiResourceDto();
return View(apiResourceDto);
}
int.TryParse(id, out var apiResourceId);
var apiResource = await _apiResourceService.GetApiResourceAsync(apiResourceId);
return View(apiResource);
}
[HttpGet]
public async Task<IActionResult> ApiSecrets(int id, int? page)
{
if (id == 0) return NotFound();
var apiSecrets = await _apiResourceService.GetApiSecretsAsync(id, page ?? 1);
_apiResourceService.BuildApiSecretsViewModel(apiSecrets);
return View(apiSecrets);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ApiSecrets(ApiSecretsDto apiSecret)
{
if (!ModelState.IsValid)
{
return View(apiSecret);
}
await _apiResourceService.AddApiSecretAsync(apiSecret);
SuccessNotification(_localizer["SuccessAddApiSecret"], _localizer["SuccessTitle"]);
return RedirectToAction(nameof(ApiSecrets), new { Id = apiSecret.ApiResourceId });
}
[HttpGet]
public async Task<IActionResult> ApiScopes(string search, int? page)
{
ViewBag.Search = search;
var apiScopesDto = await _apiScopeService.GetApiScopesAsync(search, page ?? 1);
return View(apiScopesDto);
}
[HttpGet]
public async Task<IActionResult> ApiScope(string id)
{
if (id.IsNotPresentedValidNumber())
{
return NotFound();
}
if (id == default)
{
var apiScopeDto = new ApiScopeDto();
return View(apiScopeDto);
}
else
{
int.TryParse(id, out var apiScopeId);
var apiScopeDto = await _apiScopeService.GetApiScopeAsync(apiScopeId);
return View(apiScopeDto);
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ApiScope(ApiScopeDto apiScope)
{
if (!ModelState.IsValid)
{
return View(apiScope);
}
_apiScopeService.BuildApiScopeViewModel(apiScope);
int apiScopeId;
if (apiScope.Id == 0)
{
apiScopeId = await _apiScopeService.AddApiScopeAsync(apiScope);
}
else
{
apiScopeId = apiScope.Id;
await _apiScopeService.UpdateApiScopeAsync(apiScope);
}
SuccessNotification(string.Format(_localizer["SuccessAddApiScope"], apiScope.Name), _localizer["SuccessTitle"]);
return RedirectToAction(nameof(ApiScope), new { id = apiScopeId });
}
[HttpGet]
public async Task<IActionResult> ApiScopeDelete(int id)
{
if (id == 0) return NotFound();
var apiScope = await _apiScopeService.GetApiScopeAsync(id);
return View(nameof(ApiScopeDelete), apiScope);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ApiScopeDelete(ApiScopeDto apiScope)
{
await _apiScopeService.DeleteApiScopeAsync(apiScope);
SuccessNotification(_localizer["SuccessDeleteApiScope"], _localizer["SuccessTitle"]);
return RedirectToAction(nameof(ApiScopes));
}
[HttpGet]
public async Task<IActionResult> ApiResources(int? page, string search)
{
ViewBag.Search = search;
var apiResources = await _apiResourceService.GetApiResourcesAsync(search, page ?? 1);
return View(apiResources);
}
[HttpGet]
public async Task<IActionResult> IdentityResources(int? page, string search)
{
ViewBag.Search = search;
var identityResourcesDto = await _identityResourceService.GetIdentityResourcesAsync(search, page ?? 1);
return View(identityResourcesDto);
}
[HttpGet]
public async Task<IActionResult> ApiSecretDelete(int id)
{
if (id == 0) return NotFound();
var clientSecret = await _apiResourceService.GetApiSecretAsync(id);
return View(nameof(ApiSecretDelete), clientSecret);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ApiSecretDelete(ApiSecretsDto apiSecret)
{
await _apiResourceService.DeleteApiSecretAsync(apiSecret);
SuccessNotification(_localizer["SuccessDeleteApiSecret"], _localizer["SuccessTitle"]);
return RedirectToAction(nameof(ApiSecrets), new { Id = apiSecret.ApiResourceId });
}
[HttpGet]
public async Task<IActionResult> IdentityResource(string id)
{
if (id.IsNotPresentedValidNumber())
{
return NotFound();
}
if (id == default)
{
var identityResourceDto = new IdentityResourceDto();
return View(identityResourceDto);
}
int.TryParse(id, out var identityResourceId);
var identityResource = await _identityResourceService.GetIdentityResourceAsync(identityResourceId);
return View(identityResource);
}
}
} | 35.615068 | 204 | 0.634832 | [
"MIT"
] | vbegroup/IdentityServer4.Admin | src/Skoruba.IdentityServer4.Admin.UI/Areas/AdminUI/Controllers/ConfigurationController.cs | 26,001 | C# |
using System.Threading.Tasks;
using System.Web.Mvc;
using AlexaTVInfoSkill.Service;
namespace AlexaTVInfoSkill.Controllers
{
public class ShowsController : Controller
{
public ActionResult Index()
{
var model = TvInfoService.GetShows();
return View(model);
}
}
} | 20.3125 | 49 | 0.643077 | [
"MIT"
] | kmcoulson/AlexaTvInfoSkill | AlexaTVInfoSkill/Controllers/ShowsController.cs | 327 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace _01.RabbitHole
{
class RabbitHole
{
static void Main()
{
List<string> ways = Console.ReadLine().Split().ToList();
int lifePoints = int.Parse(Console.ReadLine());
int step = 0;
string result = string.Empty;
List<string> comand = ways[step].Split('|').ToList();
while (lifePoints > 0)
{
if (comand[0] == "Left")
{
lifePoints -= int.Parse(comand[1]);
step = (int.Parse(comand[1]) - step) % ways.Count;
}
else if (comand[0] == "Right")
{
lifePoints -= int.Parse(comand[1]);
step = (int.Parse(comand[1]) + step) % ways.Count;
}
else if (comand[0] == "Bomb")
{
lifePoints -= int.Parse(comand[1]);
if (lifePoints <= 0)
{
result = "You are dead due to bomb explosion!";
break;
}
ways.RemoveAt(step);
step = 0;
}
else if (comand[0] == "RabbitHole")
{
result = "You have 5 years to save Kennedy!";
break;
}
if (lifePoints <= 0)
{
result = "You are tired. You can't continue the mission.";
break;
}
List<string> last = ways[ways.Count - 1].Split('|').ToList();
if (last[0] != "RabbitHole")
{
ways.RemoveAt(ways.Count - 1);
ways.Add($"Bomb|{lifePoints}");
}
else
{
ways.Add($"Bomb|{lifePoints}");
}
comand = ways[step].Split('|').ToList();
}
Console.WriteLine(result);
}
}
} | 32.469697 | 78 | 0.380308 | [
"MIT"
] | spzvtbg/02-Tech-modul | Fundamental task solutions/09.ArrayAndListAlgorithms-MoreExercises/01.RabbitHole/RabbitHole.cs | 2,145 | C# |
using AzureDeveloperCN.Demo.Server.HelloWorld.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AzureDeveloperCN.Demo.Server.HelloWorld
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
}
| 32.967213 | 143 | 0.642466 | [
"Apache-2.0"
] | hylinux/AzureDeveloperCN | AzureDeveloperCN.Demo.Server.HelloWorld/Startup.cs | 2,011 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gator : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
// if(Input.GetKeyDown(KeyCode.LeftArrow)){
// rb.AddForce(-transform.right * 100f, ForceMode.Force);
// }
}
}
| 19.222222 | 60 | 0.693642 | [
"Unlicense"
] | paosalcedo/PrototypeStudio_Week1 | Paolo_Salcedo_Week1/Assets/Scripts/Week02/Gator.cs | 348 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.DocumentDB.V20150401.Inputs
{
/// <summary>
/// Cosmos DB capability object
/// </summary>
public sealed class CapabilityArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Name of the Cosmos DB capability. For example, "name": "EnableCassandra". Current values also include "EnableTable" and "EnableGremlin".
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
public CapabilityArgs()
{
}
}
}
| 28.551724 | 148 | 0.653382 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/DocumentDB/V20150401/Inputs/CapabilityArgs.cs | 828 | C# |
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
namespace Microsoft.Research.MultiWorldTesting.JoinUploader
{
public delegate void EventUploaderSuccessEventHandler(object source, int eventCount, int sumSize, int inputQueueSize);
public delegate void EventUploaderErrorEventHandler(object source, Exception e);
/// <summary>
/// Represents a collection of batching criteria.
/// </summary>
/// <remarks>
/// A batch is created whenever a criterion is met.
/// </remarks>
public class BatchingConfiguration
{
/// <summary>
/// Constructor with default configuration values set.
/// </summary>
public BatchingConfiguration(bool developmentMode = false)
{
if (developmentMode)
{
this.MaxBufferSizeInBytes = 1;
this.MaxDuration = TimeSpan.FromMilliseconds(1);
this.MaxEventCount = 1;
// the number of events buffered is MaxEventCount * MaxUploadQueueCapacity * MaxDegreeOfSerializationParallelism
this.MaxUploadQueueCapacity = 1;
this.PartitionCount = 1;
this.UploadRetryPolicy = BatchUploadRetryPolicy.ExponentialRetry;
this.MaxDegreeOfSerializationParallelism = 1;
this.DroppingPolicy = new DroppingPolicy();
this.ReUseTcpConnection = true;
}
else
{
this.MaxBufferSizeInBytes = 4 * 1024 * 1024;
this.MaxDuration = TimeSpan.FromSeconds(5);
this.MaxEventCount = 1024;
// the number of events buffered is MaxEventCount * MaxUploadQueueCapacity * MaxDegreeOfSerializationParallelism
this.MaxUploadQueueCapacity = 512;
this.PartitionCount = 16;
this.UploadRetryPolicy = BatchUploadRetryPolicy.ExponentialRetry;
this.MaxDegreeOfSerializationParallelism = Environment.ProcessorCount;
this.DroppingPolicy = new DroppingPolicy();
this.ReUseTcpConnection = true;
}
}
/// <summary>
/// Period of time where events are grouped in one batch.
/// </summary>
public TimeSpan MaxDuration { get; set; }
/// <summary>
/// Maximum number of events in a batch.
/// </summary>
public int MaxEventCount { get; set; }
/// <summary>
/// Maximum size (in bytes) of a batch.
/// </summary>
public int MaxBufferSizeInBytes { get; set; }
/// <summary>
/// Max size of queue for processing/uploading.
/// </summary>
public int MaxUploadQueueCapacity { get; set; }
public int? PartitionCount { get; set; }
/// <summary>
/// Gets or sets the retry policy in case of upload failure.
/// </summary>
public BatchUploadRetryPolicy UploadRetryPolicy { get; set; }
/// <summary>
/// Gets or sets the reference resolver to be used with JSON.NET.
/// </summary>
public IReferenceResolver ReferenceResolver { get; set; }
/// <summary>
/// Gets or sets the maxium degree of parallelism employed when serializing events.
/// </summary>
public int MaxDegreeOfSerializationParallelism { get; set; }
/// <summary>
/// Gets or sets the data dropping policy which controls which events are sent to the upload queue.
/// </summary>
public DroppingPolicy DroppingPolicy { get; set; }
/// <summary>
/// If set to true, the TCP connection for the specified event hub will be re-used.
/// Otherwise MessageFactory will be used to create separate connections.
/// </summary>
/// <remarks>Defaults to true.</remarks>
public bool ReUseTcpConnection { get; set; }
/// <summary>
/// Invoked if an error happened during the upload pipeline.
/// </summary>
public event EventUploaderErrorEventHandler ErrorHandler;
/// <summary>
/// Invoked after the batch was successfully uploaded.
/// </summary>
public event EventUploaderSuccessEventHandler SuccessHandler;
internal void FireErrorHandler(Exception e)
{
var handler = this.ErrorHandler;
if (handler != null)
handler(this, e);
}
internal void FireSuccessHandler(int eventCount, int sumSize, int inputQueueSize)
{
var handler = this.SuccessHandler;
if (handler != null)
handler(this, eventCount, sumSize, inputQueueSize);
}
}
/// <summary>
/// Represents a retry policy for uploading events.
/// </summary>
public enum BatchUploadRetryPolicy
{
/// <summary>
/// No retry when upload fails, data is dropped.
/// </summary>
None = 0,
/// <summary>
/// Perform an exponential-backoff retry strategy with the upload.
/// </summary>
ExponentialRetry
}
/// <summary>
/// Represents settings which control how data can be dropped at high load.
/// </summary>
public class DroppingPolicy
{
/// <summary>
/// Constructor using default settings to not drop any data.
/// </summary>
public DroppingPolicy()
{
// By default don't drop anything
this.MaxQueueLevelBeforeDrop = 1f;
this.ProbabilityOfDrop = 0f;
}
/// <summary>
/// Gets or sets the threshold level (measured in % of total queue size) at which point
/// data are randomly dropped by the probability specified in <see cref="ProbabilityOfDrop"/>.
/// </summary>
public float MaxQueueLevelBeforeDrop { get; set; }
/// <summary>
/// Gets or sets the probability of dropping an event. This is used to reduce the system load.
/// </summary>
public float ProbabilityOfDrop { get; set; }
}
}
| 37.123529 | 129 | 0.580415 | [
"BSD-3-Clause"
] | Bhaskers-Blu-Org2/mwt-ds-decision-deprecated- | JoinServerUploader/BatchingConfiguration.cs | 6,313 | C# |
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace WinFormMarkup.Extensions
{
/// <summary>
/// Fluent extensions for FileDialogs
/// <para>Inherits: <see cref="WinFormMarkup.Extensions.CommonDialogExtensions"/></para>
/// </summary>
public static class FileDialogExtensions
{
public static TFileDialog CheckFileExists<TFileDialog>(
this TFileDialog dialog,
bool checkExists)
where TFileDialog : FileDialog
{
dialog.CheckFileExists = checkExists;
return dialog;
}
public static TFileDialog CheckPathExists<TFileDialog>(
this TFileDialog dialog,
bool checkExists)
where TFileDialog : FileDialog
{
dialog.CheckPathExists = checkExists;
return dialog;
}
public static TFileDialog CustomPlaces<TFileDialog>(
this TFileDialog dialog,
params string[] places)
where TFileDialog : FileDialog
{
foreach (var place in places) dialog.CustomPlaces.Add(place);
return dialog;
}
public static TFileDialog CustomPlaces<TFileDialog>(
this TFileDialog dialog,
params Guid[] places)
where TFileDialog : FileDialog
{
foreach (var place in places) dialog.CustomPlaces.Add(place);
return dialog;
}
public static TFileDialog CustomPlaces<TFileDialog>(
this TFileDialog dialog,
params FileDialogCustomPlace[] places)
where TFileDialog : FileDialog
{
foreach (var place in places) dialog.CustomPlaces.Add(place);
return dialog;
}
public static TFileDialog DefaultExt<TFileDialog>(
this TFileDialog dialog,
string defaultExt)
where TFileDialog : FileDialog
{
dialog.DefaultExt = defaultExt;
return dialog;
}
public static TFileDialog FileName<TFileDialog>(
this TFileDialog dialog,
string fileName)
where TFileDialog : FileDialog
{
dialog.FileName = fileName;
return dialog;
}
public static TFileDialog FileOk<TFileDialog>(
this TFileDialog dialog,
Action<TFileDialog, CancelEventArgs> action)
where TFileDialog : FileDialog
{
dialog.FileOk += (sender, args) => action.Invoke((sender as TFileDialog)!, args);
return dialog;
}
public static TFileDialog Filter<TFileDialog>(
this TFileDialog dialog,
string filter)
where TFileDialog : FileDialog
{
dialog.Filter = filter;
return dialog;
}
public static TFileDialog InitialDirectory<TFileDialog>(
this TFileDialog dialog,
string initialPath)
where TFileDialog : FileDialog
{
dialog.InitialDirectory = initialPath;
return dialog;
}
public static TFileDialog RestoreDirectory<TFileDialog>(
this TFileDialog dialog,
bool restore)
where TFileDialog : FileDialog
{
dialog.RestoreDirectory = restore;
return dialog;
}
public static TFileDialog ShowHelp<TFileDialog>(
this TFileDialog dialog,
bool showHelp)
where TFileDialog : FileDialog
{
dialog.ShowHelp = showHelp;
return dialog;
}
public static TFileDialog SupportMultiDottedExtensions<TFileDialog>(
this TFileDialog dialog,
bool multiDot)
where TFileDialog : FileDialog
{
dialog.SupportMultiDottedExtensions = multiDot;
return dialog;
}
public static TFileDialog Title<TFileDialog>(
this TFileDialog dialog,
string title)
where TFileDialog : FileDialog
{
dialog.Title = title;
return dialog;
}
public static TFileDialog ValidateNames<TFileDialog>(
this TFileDialog dialog,
bool validate)
where TFileDialog : FileDialog
{
dialog.ValidateNames = validate;
return dialog;
}
}
} | 29.123377 | 93 | 0.573467 | [
"MIT"
] | bigtlb/WinFormMarkup | src/Extensions/FileDialogExtensions.cs | 4,487 | C# |
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// 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 Castle.Windsor.Configuration.Interpreters
{
using System;
using System.Xml;
using Castle.Core;
using Castle.Core.Configuration;
using Castle.Core.Configuration.Xml;
using Castle.Core.Resource;
using Castle.MicroKernel;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.MicroKernel.SubSystems.Conversion;
using Castle.MicroKernel.SubSystems.Resource;
using Castle.Windsor.Configuration.Interpreters.XmlProcessor;
/// <summary>
/// Reads the configuration from a XmlFile. Sample structure:
/// <code>
/// <configuration>
/// <facilities>
/// <facility>
///
/// </facility>
/// </facilities>
///
/// <components>
/// <component id="component1">
///
/// </component>
/// </components>
/// </configuration>
/// </code>
/// </summary>
public class XmlInterpreter : AbstractInterpreter
{
#if FEATURE_SYSTEM_CONFIGURATION
/// <summary>
/// Initializes a new instance of the <see cref = "XmlInterpreter" /> class.
/// </summary>
public XmlInterpreter()
{
}
#endif
/// <summary>
/// Initializes a new instance of the <see cref = "XmlInterpreter" /> class.
/// </summary>
/// <param name = "filename">The filename.</param>
public XmlInterpreter(String filename) : base(filename)
{
}
/// <summary>
/// Initializes a new instance of the <see cref = "XmlInterpreter" /> class.
/// </summary>
/// <param name = "source">The source.</param>
public XmlInterpreter(IResource source) : base(source)
{
}
public override void ProcessResource(IResource source, IConfigurationStore store, IKernel kernel)
{
var resourceSubSystem = kernel.GetSubSystem(SubSystemConstants.ResourceKey) as IResourceSubSystem;
var processor = new XmlProcessor.XmlProcessor(EnvironmentName, resourceSubSystem);
try
{
var element = processor.Process(source);
var converter = kernel.GetConversionManager();
Deserialize(element, store, converter);
}
catch (XmlProcessorException e)
{
throw new ConfigurationProcessingException("Unable to process xml resource.", e);
}
}
protected static void Deserialize(XmlNode section, IConfigurationStore store, IConversionManager converter)
{
foreach (XmlNode node in section)
{
if (XmlConfigurationDeserializer.IsTextNode(node))
{
throw new ConfigurationProcessingException(String.Format("{0} cannot contain text nodes", node.Name));
}
if (node.NodeType == XmlNodeType.Element)
{
DeserializeElement(node, store, converter);
}
}
}
private static void AssertNodeName(XmlNode node, IEquatable<string> expectedName)
{
if (expectedName.Equals(node.Name))
{
return;
}
var message = String.Format("Unexpected node under '{0}': Expected '{1}' but found '{2}'", expectedName,
expectedName, node.Name);
throw new ConfigurationProcessingException(message);
}
private static void DeserializeComponent(XmlNode node, IConfigurationStore store, IConversionManager converter)
{
var config = XmlConfigurationDeserializer.GetDeserializedNode(node);
var id = config.Attributes["id"];
if (string.IsNullOrEmpty(id))
{
var type = converter.PerformConversion<Type>(config.Attributes["type"]);
id = ComponentName.DefaultNameFor(type);
config.Attributes["id"] = id;
config.Attributes.Add("id-automatic", bool.TrueString);
}
AddComponentConfig(id, config, store);
}
private static void DeserializeComponents(XmlNodeList nodes, IConfigurationStore store, IConversionManager converter)
{
foreach (XmlNode node in nodes)
{
if (node.NodeType != XmlNodeType.Element)
{
continue;
}
AssertNodeName(node, ComponentNodeName);
DeserializeComponent(node, store, converter);
}
}
private static void DeserializeContainer(XmlNode node, IConfigurationStore store)
{
var config = XmlConfigurationDeserializer.GetDeserializedNode(node);
IConfiguration newConfig = new MutableConfiguration(config.Name, node.InnerXml);
// Copy all attributes
var allKeys = config.Attributes.AllKeys;
foreach (var key in allKeys)
{
newConfig.Attributes.Add(key, config.Attributes[key]);
}
// Copy all children
newConfig.Children.AddRange(config.Children);
var name = GetRequiredAttributeValue(config, "name");
AddChildContainerConfig(name, newConfig, store);
}
private static void DeserializeContainers(XmlNodeList nodes, IConfigurationStore store)
{
foreach (XmlNode node in nodes)
{
if (node.NodeType != XmlNodeType.Element)
{
continue;
}
AssertNodeName(node, ContainerNodeName);
DeserializeContainer(node, store);
}
}
private static void DeserializeElement(XmlNode node, IConfigurationStore store, IConversionManager converter)
{
if (ContainersNodeName.Equals(node.Name))
{
DeserializeContainers(node.ChildNodes, store);
}
else if (FacilitiesNodeName.Equals(node.Name))
{
DeserializeFacilities(node.ChildNodes, store, converter);
}
else if (InstallersNodeName.Equals(node.Name))
{
DeserializeInstallers(node.ChildNodes, store);
}
else if (ComponentsNodeName.Equals(node.Name))
{
DeserializeComponents(node.ChildNodes, store, converter);
}
else
{
var message = string.Format(
"Configuration parser encountered <{0}>, but it was expecting to find " +
"<{1}>, <{2}> or <{3}>. There might be either a typo on <{0}> or " +
"you might have forgotten to nest it properly.",
node.Name, InstallersNodeName, FacilitiesNodeName, ComponentsNodeName);
throw new ConfigurationProcessingException(message);
}
}
private static void DeserializeFacilities(XmlNodeList nodes, IConfigurationStore store, IConversionManager converter)
{
foreach (XmlNode node in nodes)
{
if (node.NodeType != XmlNodeType.Element)
{
continue;
}
AssertNodeName(node, FacilityNodeName);
DeserializeFacility(node, store, converter);
}
}
private static void DeserializeFacility(XmlNode node, IConfigurationStore store, IConversionManager converter)
{
var config = XmlConfigurationDeserializer.GetDeserializedNode(node);
ThrowIfFacilityConfigurationHasIdAttribute(config);
var typeName = GetRequiredAttributeValue(config, "type");
var type = converter.PerformConversion<Type>(typeName);
AddFacilityConfig(type.FullName, config, store);
}
private static void DeserializeInstaller(XmlNode node, IConfigurationStore store)
{
var config = XmlConfigurationDeserializer.GetDeserializedNode(node);
var type = config.Attributes["type"];
var assembly = config.Attributes["assembly"];
var directory = config.Attributes["directory"];
var attributesCount = 0;
if ((string.IsNullOrEmpty(type)) == false)
{
attributesCount++;
}
if (string.IsNullOrEmpty(assembly) == false)
{
attributesCount++;
}
if (string.IsNullOrEmpty(directory) == false)
{
attributesCount++;
}
if (attributesCount != 1)
{
throw new ConfigurationProcessingException(
"install must have exactly one of the following attributes defined: 'type', 'assembly' or 'directory'.");
}
AddInstallerConfig(config, store);
}
private static void DeserializeInstallers(XmlNodeList nodes, IConfigurationStore store)
{
foreach (XmlNode node in nodes)
{
if (node.NodeType != XmlNodeType.Element)
{
continue;
}
AssertNodeName(node, InstallNodeName);
DeserializeInstaller(node, store);
}
}
private static string GetRequiredAttributeValue(IConfiguration configuration, string attributeName)
{
var value = configuration.Attributes[attributeName];
if (string.IsNullOrEmpty(value))
{
var message = String.Format("{0} elements expects required non blank attribute {1}",
configuration.Name, attributeName);
throw new ConfigurationProcessingException(message);
}
return value;
}
private static void ThrowIfFacilityConfigurationHasIdAttribute(IConfiguration config)
{
if (config.Attributes["id"] != null)
{
throw new ConfigurationProcessingException("The 'id' attribute has been removed from facility configurations, please remove it from your configuration.");
}
}
}
}
| 30.237458 | 158 | 0.706117 | [
"Apache-2.0"
] | 111cctv19/Windsor | src/Castle.Windsor/Windsor/Configuration/Interpreters/XmlInterpreter.cs | 9,041 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class HUDController : Singleton<HUDController> {
#region Fields
[SerializeField] private Text scoreLabel;
[SerializeField] private GameObject[] livesLabels;
#endregion
#region Public Behaviour
public static void UpdateScore(int score) {
Instance.scoreLabel.text = (score).ToString();
}
public static void UpdateLives(int lives) {
for (int i = 0; i < Instance.livesLabels.Length; i++) {
Instance.livesLabels[i].SetActive(false);
if(i < lives)
Instance.livesLabels[i].SetActive(true);
}
}
#endregion
}
| 20.757576 | 59 | 0.708029 | [
"MIT"
] | gonzaloiv/alteroids | Assets/Scripts/UI/HUDController.cs | 687 | 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.SecretManager.V1Beta1.Snippets
{
// [START secretmanager_v1beta1_generated_SecretManagerService_EnableSecretVersion_sync_flattened]
using Google.Cloud.SecretManager.V1Beta1;
public sealed partial class GeneratedSecretManagerServiceClientSnippets
{
/// <summary>Snippet for EnableSecretVersion</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void EnableSecretVersion()
{
// Create client
SecretManagerServiceClient secretManagerServiceClient = SecretManagerServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/secrets/[SECRET]/versions/[SECRET_VERSION]";
// Make the request
SecretVersion response = secretManagerServiceClient.EnableSecretVersion(name);
}
}
// [END secretmanager_v1beta1_generated_SecretManagerService_EnableSecretVersion_sync_flattened]
}
| 42.512195 | 104 | 0.723465 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.SecretManager.V1Beta1/Google.Cloud.SecretManager.V1Beta1.GeneratedSnippets/SecretManagerServiceClient.EnableSecretVersionSnippet.g.cs | 1,743 | C# |
using MatterHackers.Agg;
using MatterHackers.Agg.UI;
using MatterHackers.VectorMath;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace MatterHackers.MatterControl
{
public class SlidePanel : GuiWidget
{
public List<GuiWidget> panels = new List<GuiWidget>();
private int currentPanelIndex = -1;
private int desiredPanelIndex = 0;
private Stopwatch timeHasBeenChanging = new Stopwatch();
public SlidePanel(int count)
{
this.AnchorAll();
for (int i = 0; i < count; i++)
{
GuiWidget newPanel = new FlowLayoutWidget(FlowDirection.TopToBottom);
panels.Add(newPanel);
AddChild(newPanel);
}
}
public int PanelIndex
{
get
{
return currentPanelIndex;
}
set
{
if (currentPanelIndex != value)
{
desiredPanelIndex = value;
timeHasBeenChanging.Restart();
SetSlidePosition();
}
}
}
public void SetPanelIndexImmediate(int index)
{
desiredPanelIndex = index;
SetSlidePosition();
}
public GuiWidget GetPanel(int index)
{
return panels[index];
}
public override void OnBoundsChanged(EventArgs e)
{
for (int i = 0; i < panels.Count; i++)
{
panels[i].LocalBounds = LocalBounds;
}
SetSlidePosition();
base.OnBoundsChanged(e);
}
public override void OnDraw(Graphics2D graphics2D)
{
base.OnDraw(graphics2D);
if (currentPanelIndex != desiredPanelIndex)
{
SetSlidePosition();
Invalidate();
}
}
private void SetSlidePosition()
{
if (currentPanelIndex != desiredPanelIndex)
{
// set this based on the time that has elapsed and it should give us a nice result (we can even ease in ease out)
double maxOffsetPerDraw = timeHasBeenChanging.ElapsedMilliseconds;
double desiredOffset = desiredPanelIndex * -Width;
double currentOffset = panels[0].OriginRelativeParent.X;
double delta = desiredOffset - currentOffset;
if (delta < 0)
{
delta = Math.Max(-maxOffsetPerDraw, delta);
}
else
{
delta = Math.Min(maxOffsetPerDraw, delta);
}
double offsetThisDraw = currentOffset + delta;
for (int i = 0; i < panels.Count; i++)
{
panels[i].OriginRelativeParent = new Vector2(offsetThisDraw, 0);
offsetThisDraw += Width;
}
if (currentOffset + delta == desiredOffset)
{
currentPanelIndex = desiredPanelIndex;
}
}
else
{
double desiredOffset = desiredPanelIndex * -Width;
for (int i = 0; i < panels.Count; i++)
{
panels[i].OriginRelativeParent = new Vector2(desiredOffset, 0);
desiredOffset += Width;
}
}
}
}
} | 21.540984 | 117 | 0.665145 | [
"BSD-2-Clause"
] | Bhalddin/MatterControl | MatterControlLib/CustomWidgets/SlidePanelWidget.cs | 2,630 | C# |
/***************************************************************************/
// Copyright 2013-2019 Riley White
//
// 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;
namespace Bix.Core
{
/// <summary>
/// Marks a type as the root of an aggregate, or as the item that can be saved to
/// or retreived from a <see cref="IRepository{TIdentity, TItem}"/>.
/// </summary>
/// <remarks>
/// Aggregates are alway retrieved/saved as a unit by way of the repository of the root of
/// the aggregate.
///
/// See https://martinfowler.com/bliki/DDD_Aggregate.html.
///
/// This interface does not add any explicit functional contract.
/// </remarks>
public interface IAggregateRoot { }
}
| 38.114286 | 94 | 0.609445 | [
"Apache-2.0"
] | rileywhite/Bix | src/Bix/Core/IAggregateRoot.cs | 1,336 | 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.Compute.V20190701.Outputs
{
/// <summary>
/// Specifies the hardware settings for the virtual machine.
/// </summary>
[OutputType]
public sealed class HardwareProfileResponse
{
/// <summary>
/// Specifies the size of the virtual machine. For more information about virtual machine sizes, see [Sizes for virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-sizes?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). <br><br> The available VM sizes depend on region and availability set. For a list of available sizes use these APIs: <br><br> [List all available virtual machine sizes in an availability set](https://docs.microsoft.com/rest/api/compute/availabilitysets/listavailablesizes) <br><br> [List all available virtual machine sizes in a region](https://docs.microsoft.com/rest/api/compute/virtualmachinesizes/list) <br><br> [List all available virtual machine sizes for resizing](https://docs.microsoft.com/rest/api/compute/virtualmachines/listavailablesizes)
/// </summary>
public readonly string? VmSize;
[OutputConstructor]
private HardwareProfileResponse(string? vmSize)
{
VmSize = vmSize;
}
}
}
| 52.645161 | 874 | 0.727328 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Compute/V20190701/Outputs/HardwareProfileResponse.cs | 1,632 | C# |
using System.Collections.Generic;
using System.Net;
namespace Jane.ENode
{
public interface IEQueueConfiguration
{
IPEndPoint BrokerAdminEndPoint { get; }
string BrokerAdminHost { get; set; }
int BrokerAdminPort { get; set; }
IPEndPoint BrokerConsumerEndPoint { get; }
string BrokerConsumerHost { get; set; }
int BrokerConsumerPort { get; set; }
string BrokerGroupName { get; set; }
string BrokerName { get; set; }
IPEndPoint BrokerProducerEndPoint { get; }
string BrokerProducerHost { get; set; }
int BrokerProducerPort { get; set; }
string BrokerStorePath { get; set; }
string NameServerAddress { get; set; }
List<IPEndPoint> NameServerEndPoints { get; }
int NameServerPort { get; set; }
}
} | 22.702703 | 53 | 0.627381 | [
"Apache-2.0"
] | Caskia/Jane | src/Jane.ENode/ENode/IEQueueConfiguration.cs | 842 | C# |
using System;
using FluentAssertions;
using Xer.DomainDriven.Tests.Entities;
using Xunit;
namespace Xer.DomainDriven.Tests
{
public class ValueObjectTests
{
public class Equality
{
[Fact]
public void EqualityOperatorShouldBeTrueIfValueObjectsMatchByValue()
{
TestValueObject valueObject1 = new TestValueObject("Test", 123);
TestValueObject valueObject2 = new TestValueObject("Test", 123);
(valueObject1 == valueObject2).Should().BeTrue();
}
[Fact]
public void EqualityOperatorShouldBeTrueIfValueObjectsAreTheSameReference()
{
TestValueObject valueObject1 = new TestValueObject("Test", 123);
TestValueObject sameReference = valueObject1;
(valueObject1 == sameReference).Should().BeTrue();
}
[Fact]
public void EqualityOperatorShouldBeFalseIfValueObjectsDoNotMatchByValue()
{
TestValueObject valueObject1 = new TestValueObject("Test", 123);
TestValueObject valueObject2 = new TestValueObject("Test2", 1234);
(valueObject1 == valueObject2).Should().BeFalse();
}
[Fact]
public void EqualityOperatorShouldBeFalseIfComparedWithNull()
{
TestValueObject valueObject1 = new TestValueObject("Test", 123);
TestValueObject valueObject2 = null;
(valueObject1 == valueObject2).Should().BeFalse();
}
[Fact]
public void EqualsShouldBeTrueIfValueObjectsMatchByValue()
{
TestValueObject valueObject1 = new TestValueObject("Test", 123);
TestValueObject valueObject2 = new TestValueObject("Test", 123);
valueObject1.Equals(valueObject2).Should().BeTrue();
}
[Fact]
public void EqualsShouldBeTrueIfValueObjectsAreTheSameReference()
{
TestValueObject valueObject1 = new TestValueObject("Test", 123);
TestValueObject sameReference = valueObject1;
valueObject1.Equals(sameReference).Should().BeTrue();
}
[Fact]
public void EqualsShouldNotBeTrueIfValueObjectsDoNotMatchByValue()
{
TestValueObject valueObject1 = new TestValueObject("Test", 123);
TestValueObject valueObject2 = new TestValueObject("Test2", 1234);
valueObject1.Equals(valueObject2).Should().BeFalse();
}
[Fact]
public void EqualsOperatorShouldNotBeTrueIfComparedWithNull()
{
TestValueObject valueObject1 = new TestValueObject("Test", 123);
TestValueObject valueObject2 = null;
valueObject1.Equals(valueObject2).Should().BeFalse();
}
[Fact]
public void ObjectEqualsShouldBeTrueIfValueObjectsMatchByValue()
{
TestValueObject valueObject1 = new TestValueObject("Test", 123);
TestValueObject valueObject2 = new TestValueObject("Test", 123);
valueObject1.Equals((object)valueObject2).Should().BeTrue();
}
[Fact]
public void ObjectEqualsShouldBeTrueIfValueObjectsAreTheSameReference()
{
TestValueObject valueObject1 = new TestValueObject("Test", 123);
TestValueObject sameReference = valueObject1;
valueObject1.Equals((object)sameReference).Should().BeTrue();
}
[Fact]
public void ObjectEqualsShouldNotBeTrueIfValueObjectsDoNotMatchByValue()
{
TestValueObject valueObject1 = new TestValueObject("Test", 123);
TestValueObject valueObject2 = new TestValueObject("Test2", 1234);
valueObject1.Equals((object)valueObject2).Should().BeFalse();
}
[Fact]
public void ObjectEqualsOperatorShouldNotBeTrueIfComparedWithNull()
{
TestValueObject valueObject1 = new TestValueObject("Test", 123);
TestValueObject valueObject2 = null;
valueObject1.Equals((object)valueObject2).Should().BeFalse();
}
[Fact]
public void ShouldNotBeEqualIfValueObjectsMatchByValueButDifferentType()
{
var valueObject1 = new TestValueObject("Test", 123);
var valueObject2 = new TestValueObjectSecond("Test", 123);
// Same value, should be equal.
valueObject1.Should().NotBe(valueObject2);
}
}
public class GetHashCodeMethod
{
[Fact]
public void ShouldBeSameForTheSameInstance()
{
TestValueObject valueObject1 = new TestValueObject("Test", 123);
int hashCode1 = valueObject1.GetHashCode();
int hashCode2 = valueObject1.GetHashCode();
hashCode1.Should().Be(hashCode2);
}
[Fact]
public void ShouldBeSameForTheDifferentInstancesWithSameValues()
{
TestValueObject valueObject1 = new TestValueObject("Test", 123);
TestValueObject valueObject2 = new TestValueObject("Test", 123);
int hashCode1 = valueObject1.GetHashCode();
int hashCode2 = valueObject2.GetHashCode();
hashCode1.Should().Be(hashCode2);
}
[Fact]
public void ShouldNotBeSameForTheDifferentInstancesWithDifferentValues()
{
TestValueObject valueObject1 = new TestValueObject("Test", 123);
TestValueObject valueObject2 = new TestValueObject("Test2", 1234);
int hashCode1 = valueObject1.GetHashCode();
int hashCode2 = valueObject2.GetHashCode();
hashCode1.Should().NotBe(hashCode2);
}
}
}
} | 36.491124 | 87 | 0.583104 | [
"MIT"
] | XerProjects/Xer.DomainDriven | Tests/Xer.DomainDriven.Tests/ValueObjectTests.cs | 6,167 | C# |
// Copyright (c) 2015 - 2019 Doozy Entertainment / Marlink Trading SRL. All Rights Reserved.
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using DG.Tweening;
using Doozy.PlayMaker;
using Doozy.PlayMaker.Actions;
using UnityEngine;
namespace HutongGames.PlayMaker.Actions
{
[ActionCategory("DOTween")]
[Tooltip("Rotates the target so that it will look towards the given GameObject's position.")]
[HelpUrl("http://dotween.demigiant.com/documentation.php")]
public class DOTweenRigidbodyLookAtGameObject : FsmStateAction
{
[RequiredField]
[CheckForComponent(typeof(Rigidbody))]
public FsmOwnerDefault gameObject;
[RequiredField]
[UIHint(UIHint.FsmGameObject)]
[Tooltip("The GameObject to look at")]
public FsmGameObject target;
[UIHint(UIHint.FsmBool)]
[Tooltip("If setRelative is TRUE sets the tween as relative (the endValue will be calculated as startValue + endValue instead of being used directly). In case of Sequences, sets all the nested tweens as relative. IMPORTANT: Has no effect on Reverse Options, since in that case you directly choose if the tween isRelative or not in the settings below")]
public FsmBool setRelative;
[Tooltip("Eventual axis constraint for the rotation")]
public AxisConstraint axisConstraint;
[UIHint(UIHint.FsmVector3)]
[Tooltip("The vector that defines in which direction up is (default: Vector3.up)")]
public FsmVector3 up;
[RequiredField]
[UIHint(UIHint.FsmFloat)]
[Tooltip("The duration of the tween")]
public FsmFloat duration;
[UIHint(UIHint.FsmBool)]
[Tooltip("If isSpeedBased is TRUE sets the tween as speed based (the duration will represent the number of units/degrees the tween moves x second). NOTE: if you want your speed to be constant, also set the ease to Ease.Linear.")]
public FsmBool setSpeedBased;
[UIHint(UIHint.FsmFloat)]
[Tooltip("Set a delayed startup for the tween")]
public FsmFloat startDelay;
[ActionSection("Reverse Options")]
[UIHint(UIHint.FsmBool)]
[Tooltip("Play in reverse. Changes a TO tween into a FROM tween: sets the current target's startValue as the tween's endValue then immediately sends the target to the previously set endValue.")]
public FsmBool playInReverse;
[UIHint(UIHint.FsmBool)]
[Tooltip("If TRUE the FROM value will be calculated as relative to the current one")]
public FsmBool setReverseRelative;
[ActionSection("Events")]
[UIHint(UIHint.FsmEvent)]
public FsmEvent startEvent;
[UIHint(UIHint.FsmEvent)]
public FsmEvent finishEvent;
[UIHint(UIHint.FsmBool)]
[Tooltip("If TRUE this action will finish immediately, if FALSE it will finish when the tween is complete.")]
public FsmBool finishImmediately;
[ActionSection("Tween ID")]
[UIHint(UIHint.Description)]
public string tweenIdDescription = "Set an ID for the tween, which can then be used as a filter with DOTween's Control Methods";
[Tooltip("Select the source for the tween ID")]
public Doozy.PlayMaker.Actions.TweenId tweenIdType;
[UIHint(UIHint.FsmString)]
[Tooltip("Use a String as the tween ID")]
public FsmString stringAsId;
[UIHint(UIHint.Tag)]
[Tooltip("Use a Tag as the tween ID")]
public FsmString tagAsId;
[ActionSection("Ease Settings")]
public Doozy.PlayMaker.Actions.SelectedEase selectedEase;
[Tooltip("Sets the ease of the tween. If applied to a Sequence instead of a Tweener, the ease will be applied to the whole Sequence as if it was a single animated timeline.Sequences always have Ease.Linear by default, independently of the global default ease settings.")]
public Ease easeType;
public FsmAnimationCurve animationCurve;
[ActionSection("Loop Settings")]
[UIHint(UIHint.Description)]
public string loopsDescriptionArea = "Setting loops to -1 will make the tween loop infinitely.";
[UIHint(UIHint.FsmInt)]
[Tooltip("Setting loops to -1 will make the tween loop infinitely.")]
public FsmInt loops;
[Tooltip("Sets the looping options (Restart, Yoyo, Incremental) for the tween. LoopType.Restart: When a loop ends it will restart from the beginning. LoopType.Yoyo: When a loop ends it will play backwards until it completes another loop, then forward again, then backwards again, and so on and on and on. LoopType.Incremental: Each time a loop ends the difference between its endValue and its startValue will be added to the endValue, thus creating tweens that increase their values with each loop cycle. Has no effect if the tween has already started.Also, infinite loops will not be applied if the tween is inside a Sequence.")]
public DG.Tweening.LoopType loopType = DG.Tweening.LoopType.Restart;
[ActionSection("Special Settings")]
[UIHint(UIHint.FsmBool)]
[Tooltip("If autoKillOnCompletion is set to TRUE the tween will be killed as soon as it completes, otherwise it will stay in memory and you'll be able to reuse it.")]
public FsmBool autoKillOnCompletion;
[UIHint(UIHint.FsmBool)]
[Tooltip("Sets the recycling behaviour for the tween. If you don't set it then the default value (set either via DOTween.Init or DOTween.defaultRecyclable) will be used.")]
public FsmBool recyclable;
[Tooltip("Sets the type of update (Normal, Late or Fixed) for the tween and eventually tells it to ignore Unity's timeScale. UpdateType.Normal: Updates every frame during Update calls. UpdateType.Late: Updates every frame during LateUpdate calls. UpdateType.Fixed: Updates using FixedUpdate calls. ")]
public UpdateType updateType = UpdateType.Normal;
[UIHint(UIHint.FsmBool)]
[Tooltip(" If TRUE the tween will ignore Unity's Time.timeScale. NOTE: independentUpdate works also with UpdateType.Fixed but is not recommended in that case (because at timeScale 0 FixedUpdate won't run).")]
public FsmBool isIndependentUpdate;
[ActionSection("Debug Options")]
[UIHint(UIHint.FsmBool)]
public FsmBool debugThis;
private Tweener tween;
public override void Reset()
{
base.Reset();
gameObject = null;
target = null;
duration = new FsmFloat { UseVariable = false };
setSpeedBased = new FsmBool { UseVariable = false, Value = false };
axisConstraint = AxisConstraint.None;
up = new FsmVector3 { UseVariable = false, Value = Vector3.up };
setRelative = new FsmBool { UseVariable = false, Value = false };
playInReverse = new FsmBool { UseVariable = false, Value = false };
setReverseRelative = new FsmBool { UseVariable = false, Value = false };
startEvent = null;
finishEvent = null;
finishImmediately = new FsmBool { UseVariable = false, Value = false };
stringAsId = new FsmString { UseVariable = false };
tagAsId = new FsmString { UseVariable = false };
startDelay = new FsmFloat { Value = 0 };
selectedEase = Doozy.PlayMaker.Actions.SelectedEase.EaseType;
easeType = Ease.Linear;
loops = new FsmInt { Value = 0 };
loopType = DG.Tweening.LoopType.Restart;
autoKillOnCompletion = new FsmBool { Value = true };
recyclable = new FsmBool { Value = false };
updateType = UpdateType.Normal;
isIndependentUpdate = new FsmBool { Value = false };
debugThis = new FsmBool { Value = false };
}
public override void OnEnter()
{
tween = Fsm.GetOwnerDefaultTarget(gameObject).GetComponent<Rigidbody>().DOLookAt(target.Value.transform.position, duration.Value, axisConstraint, up.Value);
if (setSpeedBased.Value) tween.SetSpeedBased();
tween.SetRelative(setRelative.Value);
tween.SetTweenId(tweenIdType, stringAsId, tagAsId, Fsm.GetOwnerDefaultTarget(gameObject));
tween.SetDelay(startDelay.Value);
tween.SetSelectedEase(selectedEase, easeType, animationCurve);
tween.SetLoops(loops.Value, loopType);
tween.SetAutoKill(autoKillOnCompletion.Value);
tween.SetRecyclable(recyclable.Value);
tween.SetUpdate(updateType, isIndependentUpdate.Value);
if (playInReverse.Value) tween.From(setReverseRelative.Value);
if (startEvent != null) tween.OnStart(() => { Fsm.Event(startEvent); });
if (finishImmediately.Value == false) // This allows Action Sequences of this action.
{
if (finishEvent != null)
tween.OnComplete(() => { Fsm.Event(finishEvent); });
else
tween.OnComplete(Finish);
}
tween.Play();
if (debugThis.Value) State.Debug("DOTween RigidBody Look At GameObject");
if (finishImmediately.Value) Finish();
}
}
}
| 51.972376 | 638 | 0.672584 | [
"Unlicense"
] | rachel2386/BoilingCorn | Corn/Assets/DOTweenPlaymakerActions/Actions/DOTween/DOTweenRigidbodyLookAtGameObject.cs | 9,407 | C# |
// IPA Cores.NET
//
// Copyright (c) 2019- IPA CyberLab.
// Copyright (c) 2003-2018 Daiyuu Nobori.
// Copyright (c) 2013-2018 SoftEther VPN Project, University of Tsukuba, Japan.
// All Rights Reserved.
//
// License: The Apache License, Version 2.0
// https://www.apache.org/licenses/LICENSE-2.0
//
// THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// THIS SOFTWARE IS DEVELOPED IN JAPAN, AND DISTRIBUTED FROM JAPAN, UNDER
// JAPANESE LAWS. YOU MUST AGREE IN ADVANCE TO USE, COPY, MODIFY, MERGE, PUBLISH,
// DISTRIBUTE, SUBLICENSE, AND/OR SELL COPIES OF THIS SOFTWARE, THAT ANY
// JURIDICAL DISPUTES WHICH ARE CONCERNED TO THIS SOFTWARE OR ITS CONTENTS,
// AGAINST US (IPA CYBERLAB, DAIYUU NOBORI, SOFTETHER VPN PROJECT OR OTHER
// SUPPLIERS), OR ANY JURIDICAL DISPUTES AGAINST US WHICH ARE CAUSED BY ANY KIND
// OF USING, COPYING, MODIFYING, MERGING, PUBLISHING, DISTRIBUTING, SUBLICENSING,
// AND/OR SELLING COPIES OF THIS SOFTWARE SHALL BE REGARDED AS BE CONSTRUED AND
// CONTROLLED BY JAPANESE LAWS, AND YOU MUST FURTHER CONSENT TO EXCLUSIVE
// JURISDICTION AND VENUE IN THE COURTS SITTING IN TOKYO, JAPAN. YOU MUST WAIVE
// ALL DEFENSES OF LACK OF PERSONAL JURISDICTION AND FORUM NON CONVENIENS.
// PROCESS MAY BE SERVED ON EITHER PARTY IN THE MANNER AUTHORIZED BY APPLICABLE
// LAW OR COURT RULE.
// Author: Daiyuu Nobori
// Description
#if CORES_CODES_THINCONTROLLER
using System;
using System.Buffers;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
using System.Net;
using System.Net.Sockets;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using IPA.Cores.Basic;
using IPA.Cores.Helper.Basic;
using static IPA.Cores.Globals.Basic;
using IPA.Cores.Codes;
using IPA.Cores.Helper.Codes;
using static IPA.Cores.Globals.Codes;
using Newtonsoft.Json;
namespace IPA.Cores.Codes
{
public class ThinDbVar : INormalizable // 注意! MemDb ファイル保存するため、むやみに [JsonIgnore] を書かないこと!!
{
[EasyKey]
public int VAR_ID { get; set; }
public string VAR_NAME { get; set; } = "";
public string VAR_VALUE1 { get; set; } = "";
public string? VAR_VALUE2 { get; set; }
public string? VAR_VALUE3 { get; set; }
public string? VAR_VALUE4 { get; set; }
public string? VAR_VALUE5 { get; set; }
public string? VAR_VALUE6 { get; set; }
public void Normalize()
{
this.VAR_NAME = this.VAR_NAME._NonNullTrim();
this.VAR_VALUE1 = this.VAR_VALUE1._NonNullTrim();
this.VAR_VALUE2 = this.VAR_VALUE2._TrimIfNonNull();
this.VAR_VALUE3 = this.VAR_VALUE3._TrimIfNonNull();
this.VAR_VALUE4 = this.VAR_VALUE4._TrimIfNonNull();
this.VAR_VALUE5 = this.VAR_VALUE5._TrimIfNonNull();
this.VAR_VALUE6 = this.VAR_VALUE6._TrimIfNonNull();
}
}
public class ThinDbSvc // 注意! MemDb ファイル保存するため、むやみに [JsonIgnore] を書かないこと!!
{
[EasyManualKey]
public string SVC_NAME { get; set; } = "";
public string SVC_TITLE { get; set; } = "";
}
public class ThinDbMachine // 注意! MemDb ファイル保存するため、むやみに [JsonIgnore] を書かないこと!!
{
[SimpleTableOrder(1)]
public int MACHINE_ID { get; set; }
[SimpleTableIgnore]
public string SVC_NAME { get; set; } = "";
[EasyManualKey]
[SimpleTableOrder(3)]
public string MSID { get; set; } = "";
[SimpleTableOrder(2)]
public string PCID { get; set; } = "";
[SimpleTableIgnore]
public int PCID_VER { get; set; }
[SimpleTableIgnore]
public DateTime PCID_UPDATE_DATE { get; set; } = Util.ZeroDateTimeValue;
[SimpleTableIgnore]
public string CERT_HASH { get; set; } = "";
[SimpleTableIgnore]
[NoDebugDump]
public string HOST_SECRET2 { get; set; } = "";
[SimpleTableOrder(5)]
public DateTime CREATE_DATE { get; set; } = Util.ZeroDateTimeValue;
[SimpleTableIgnore]
public DateTime UPDATE_DATE { get; set; } = Util.ZeroDateTimeValue;
[SimpleTableOrder(7)]
public DateTime LAST_SERVER_DATE { get; set; } = Util.ZeroDateTimeValue;
[SimpleTableOrder(8)]
public DateTime LAST_CLIENT_DATE { get; set; } = Util.ZeroDateTimeValue;
[SimpleTableOrder(9)]
public int NUM_SERVER { get; set; }
[SimpleTableOrder(10)]
public int NUM_CLIENT { get; set; }
[SimpleTableOrder(4)]
public string CREATE_IP { get; set; } = "";
[SimpleTableIgnore]
public string CREATE_HOST { get; set; } = "";
[SimpleTableOrder(6)]
public string LAST_IP { get; set; } = "";
[SimpleTableOrder(6.1)]
public string LAST_CLIENT_IP { get; set; } = "";
[SimpleTableIgnore]
public string REAL_PROXY_IP { get; set; } = "";
[SimpleTableIgnore]
public string LAST_FLAG { get; set; } = "";
[SimpleTableIgnore]
public DateTime FIRST_CLIENT_DATE { get; set; } = Util.ZeroDateTimeValue;
[SimpleTableIgnore]
public string WOL_MACLIST { get; set; } = "";
[SimpleTableIgnore]
public long SERVERMASK64 { get; set; }
[SimpleTableIgnore]
public string JSON_ATTRIBUTES { get; set; } = "";
}
public class ThinMemoryDb // 注意! MemDb ファイル保存するため、むやみに [JsonIgnore] を書かないこと!!
{
// データベースからもらってきたデータ
public List<ThinDbSvc> SvcList = new List<ThinDbSvc>();
public List<ThinDbVar> VarList = new List<ThinDbVar>();
public List<ThinDbMachine> MachineList = new List<ThinDbMachine>();
// 以下は [JsonIgnore] を付けること!!
// 上記データをもとにハッシュ化したデータ
[JsonIgnore]
public Dictionary<string, ThinDbSvc> SvcBySvcName = new Dictionary<string, ThinDbSvc>(StrComparer.IgnoreCaseComparer);
[JsonIgnore]
public Dictionary<string, List<ThinDbVar>> VarByName = new Dictionary<string, List<ThinDbVar>>(StrComparer.IgnoreCaseComparer);
[JsonIgnore]
public Dictionary<string, ThinDbMachine> MachineByPcidAndSvcName = new Dictionary<string, ThinDbMachine>(StrComparer.IgnoreCaseComparer);
[JsonIgnore]
public Dictionary<string, ThinDbMachine> MachineByMsid = new Dictionary<string, ThinDbMachine>(StrComparer.IgnoreCaseComparer);
[JsonIgnore]
public Dictionary<string, ThinDbMachine> MachineByCertHashAndHostSecret2 = new Dictionary<string, ThinDbMachine>(StrComparer.IgnoreCaseComparer);
[JsonIgnore]
public int MaxSessionsPerGate;
[JsonIgnore]
public string ControllerGateSecretKey = "";
[JsonIgnore]
public int ControllerMaxConcurrentWpcRequestProcessingForUsers;
[JsonIgnore]
public int ControllerDbFullReloadIntervalMsecs;
[JsonIgnore]
public int ControllerDbWriteUpdateIntervalMsecs;
[JsonIgnore]
public int ControllerDbBackupFileWriteIntervalMsecs;
[JsonIgnore]
public int ControllerRecordStatIntervalMsecs;
[JsonIgnore]
public string WildCardDnsDomainName = "";
public ThinMemoryDb() { }
// データベースから構築
public ThinMemoryDb(IEnumerable<ThinDbSvc> svcTable, IEnumerable<ThinDbMachine> machineTable, IEnumerable<ThinDbVar> varTable, IEnumerable<ThinDatabasePcidChangeHistory?>? pcidChangeHistory = null)
{
this.SvcList = svcTable.OrderBy(x => x.SVC_NAME, StrComparer.IgnoreCaseComparer).ToList();
this.VarList = varTable.OrderBy(x => x.VAR_NAME).ThenBy(x => x.VAR_ID).ToList();
this.MachineList = machineTable.OrderBy(x => x.MACHINE_ID).ToList();
BuildOnMemoryData(pcidChangeHistory);
}
// ファイルから復元
public ThinMemoryDb(string filePath)
{
ThinMemoryDb? tmp = Lfs.ReadJsonFromFile<ThinMemoryDb>(filePath, nullIfError: true);
if (tmp == null)
{
tmp = Lfs.ReadJsonFromFile<ThinMemoryDb>(filePath + ".bak", nullIfError: false);
}
this.SvcList = tmp.SvcList;
this.MachineList = tmp.MachineList;
this.VarList = tmp.VarList;
BuildOnMemoryData();
}
// オンメモリデータの構築
void BuildOnMemoryData(IEnumerable<ThinDatabasePcidChangeHistory?>? pcidChangeHistory = null)
{
this.SvcList.ForEach(x => this.SvcBySvcName.TryAdd(x.SVC_NAME, x));
this.VarList.ForEach(v =>
{
v.Normalize();
this.VarByName._GetOrNew(v.VAR_NAME, () => new List<ThinDbVar>()).Add(v);
});
// MSID または認証キーによるハッシュを生成
this.MachineList.ForEach(x =>
{
this.MachineByMsid.TryAdd(x.MSID, x);
this.MachineByCertHashAndHostSecret2.TryAdd(x.CERT_HASH + "@" + x.HOST_SECRET2, x);
});
if (pcidChangeHistory != null)
{
// PCID 変更履歴を適用
foreach (var hist in pcidChangeHistory)
{
if (hist != null)
{
var machine = this.MachineByMsid._GetOrDefault(hist.Msid);
if (machine != null)
{
if (hist.Ver > machine.PCID_VER)
{
// PCID 変更履歴のほうがより新しいので、メモリ上の PCID を書換える
machine.PCID = hist.Pcid;
machine.PCID_VER = hist.Ver;
machine.PCID_UPDATE_DATE = hist.UpdateDateTime;
}
}
}
}
}
// PCID 名によるハッシュを生成
RebuildPcidListOnMemory();
// 頻繁にアクセスされる変数を予め読み出しておく
this.MaxSessionsPerGate = this.VarByName._GetOrDefault("MaxSessionsPerGate")?.FirstOrDefault()?.VAR_VALUE1._ToInt() ?? 0;
this.ControllerGateSecretKey = this.VarByName._GetOrDefault("ControllerGateSecretKey")?.FirstOrDefault()?.VAR_VALUE1._NonNullTrim() ?? "";
this.ControllerMaxConcurrentWpcRequestProcessingForUsers = this.VarByName._GetOrDefault("ControllerMaxConcurrentWpcRequestProcessingForUsers")?.FirstOrDefault()?.VAR_VALUE1._ToInt() ?? 0;
this.ControllerDbFullReloadIntervalMsecs = this.VarByName._GetOrDefault("ControllerDbFullReloadIntervalMsecs")?.FirstOrDefault()?.VAR_VALUE1._ToInt() ?? 0;
this.ControllerDbWriteUpdateIntervalMsecs = this.VarByName._GetOrDefault("ControllerDbWriteUpdateIntervalMsecs")?.FirstOrDefault()?.VAR_VALUE1._ToInt() ?? 0;
this.ControllerDbBackupFileWriteIntervalMsecs = this.VarByName._GetOrDefault("ControllerDbBackupFileWriteIntervalMsecs")?.FirstOrDefault()?.VAR_VALUE1._ToInt() ?? 0;
this.ControllerRecordStatIntervalMsecs = this.VarByName._GetOrDefault("ControllerRecordStatIntervalMsecs")?.FirstOrDefault()?.VAR_VALUE1._ToInt() ?? 0;
this.WildCardDnsDomainName = this.VarByName._GetOrDefault("WildCardDnsDomainName")?.FirstOrDefault()?.VAR_VALUE1._NonNullTrim() ?? ThinControllerConsts.Default_WildCardDnsDomainName;
}
// PCID 一覧のリビルド (PCID に変更が発生したので Dictionary をリビルドする)
public void RebuildPcidListOnMemory()
{
Dictionary<string, ThinDbMachine> tmp = new Dictionary<string, ThinDbMachine>(StrComparer.IgnoreCaseComparer);
// 重複発生時は PCID_UPDATE_DATE が大きいほど優先
this.MachineList.OrderByDescending(x => x.PCID_UPDATE_DATE).ThenBy(x => x.MACHINE_ID)._DoForEach(x =>
{
var svc = this.SvcBySvcName[x.SVC_NAME];
tmp.TryAdd(x.PCID + "@" + svc.SVC_NAME, x);
});
this.MachineByPcidAndSvcName = tmp;
}
public long SaveToFile(string filePath)
{
string backupPath = filePath + ".bak";
try
{
if (Lfs.IsFileExists(filePath))
{
Lfs.CopyFile(filePath, backupPath);
}
}
catch (Exception ex)
{
ex._Error();
}
return Lfs.WriteJsonToFile(filePath, this, flags: FileFlags.AutoCreateDirectory | FileFlags.OnCreateSetCompressionFlag);
}
}
public class ThinDatabaseUpdateJob
{
public Func<Database, CancellationToken, Task> ProcAsync { get; }
public ThinDatabaseUpdateJob(Func<Database, CancellationToken, Task> procAsync)
{
ProcAsync = procAsync;
}
}
public class ThinDatabasePcidChangeHistory
{
public string Msid { get; }
public int Ver { get; }
public string Pcid { get; } = "";
public DateTime UpdateDateTime { get; } = ZeroDateTimeValue;
public ThinDatabasePcidChangeHistory(string msid, int ver, string pcid, DateTime dt)
{
Msid = msid;
Ver = ver;
Pcid = pcid;
UpdateDateTime = dt;
}
}
public class ThinDatabase : AsyncServiceWithMainLoop
{
Task ReadMainLoopTask, WriteMainLoopTask;
public ThinController Controller { get; }
public ThinMemoryDb? MemDb { get; private set; }
public bool IsLoaded => MemDb != null; // 一度でもメモリロードされたら true
public bool IsDatabaseConnected { get; private set; } // 読み出しメインループからの最後のデータベース接続に成功していれば true、それ以外の場合は false。DB で不具合が発生していることを検出するため
public string BackupFileName { get; }
readonly FastCache<string, ThinDatabasePcidChangeHistory> PcidChangeHistoryCache = new FastCache<string, ThinDatabasePcidChangeHistory>(ThinControllerConsts.Max_ControllerDbReadFullReloadIntervalMsecs * 4, comparer: StrComparer.IgnoreCaseComparer);
readonly CriticalSection PcidChangeLock = new CriticalSection<ThinDatabasePcidChangeHistory>();
readonly ConcurrentQueue<ThinDatabaseUpdateJob> LazyUpdateJobQueue = new ConcurrentQueue<ThinDatabaseUpdateJob>();
public int LazyUpdateJobQueueLength => LazyUpdateJobQueue.Count;
public bool IsStarted { get; private set; }
public ThinDatabase(ThinController controller)
{
try
{
this.BackupFileName = PP.Combine(Env.AppLocalDir, "Config", "ThinControllerDatabaseBackupCache", "DatabaseBackupCache.json");
this.Controller = controller;
this.ReadMainLoopTask = ReadMainLoopAsync(this.GrandCancel)._LeakCheck();
this.WriteMainLoopTask = WriteMainLoopAsync(this.GrandCancel)._LeakCheck();
}
catch
{
this._DisposeSafe();
throw;
}
}
public void StartLoop()
{
this.IsStarted = true;
}
public void EnqueueUpdateJob(Func<Database, CancellationToken, Task> proc)
{
int maxQueueLength = Math.Max(ThinControllerConsts.ControllerMaxDatabaseWriteQueueLength, 1);
// キューがいっぱいの場合は古いものから削除する
while (LazyUpdateJobQueue.Count >= maxQueueLength)
{
LazyUpdateJobQueue.TryDequeue(out _);
}
LazyUpdateJobQueue.Enqueue(new ThinDatabaseUpdateJob(proc));
Controller.StatMan?.AddReport("EnqueueUpdateJob_Total", 1);
}
public async Task<Database> OpenDatabaseForReadAsync(CancellationToken cancel = default)
{
Database db = new Database(this.Controller.SettingsFastSnapshot.DbConnectionString_Read, defaultIsolationLevel: IsolationLevel.Snapshot);
try
{
await db.EnsureOpenAsync(cancel);
Controller.StatMan?.AddReport("OpenDatabaseForReadAsync_Total", 1);
return db;
}
catch
{
await db._DisposeSafeAsync();
throw;
}
}
public async Task<Database> OpenDatabaseForWriteAsync(CancellationToken cancel = default)
{
Database db = new Database(this.Controller.SettingsFastSnapshot.DbConnectionString_Write, defaultIsolationLevel: IsolationLevel.Serializable);
try
{
await db.EnsureOpenAsync(cancel);
Controller.StatMan?.AddReport("OpenDatabaseForWriteAsync_Total", 1);
return db;
}
catch
{
await db._DisposeSafeAsync();
throw;
}
}
long LastBackupSaveTick = 0;
// データベースから最新の情報取得メイン
async Task ReadCoreAsync(CancellationToken cancel)
{
try
{
IEnumerable<ThinDbSvc> allSvcs = null!;
IEnumerable<ThinDbMachine> allMachines = null!;
IEnumerable<ThinDbVar> allVars = null!;
try
{
await using var db = await OpenDatabaseForReadAsync(cancel);
Controller.Throughput_DatabaseRead.Add(1);
await db.TranReadSnapshotIfNecessaryAsync(async () =>
{
allSvcs = await db.EasySelectAsync<ThinDbSvc>("select * from SVC", cancel: cancel);
allMachines = await db.EasySelectAsync<ThinDbMachine>("select * from MACHINE", cancel: cancel);
allVars = await db.EasySelectAsync<ThinDbVar>("select * from VAR", cancel: cancel);
});
IsDatabaseConnected = true;
$"ThinDatabase.ReadCoreAsync Read All Records from DB: {allMachines.Count()}"._Debug();
}
catch (Exception ex)
{
IsDatabaseConnected = false;
$"ThinDatabase.ReadCoreAsync Database Connect Error: {ex.ToString()}"._Error();
throw;
}
ThinMemoryDb mem = null!;
// 最近このサーバーで PCID 変更がなされた履歴のほうが新しい場合はダウンロードしたデータ中における PCID の変更を行なう
// この処理は PCID 変更処理と排他である
using (await RenamePcidAsyncLock.LockWithAwait(cancel))
{
// PCID 変更履歴ヒストリを取得
IEnumerable<ThinDatabasePcidChangeHistory?> historyItems = PcidChangeHistoryCache.GetValues();
// メモリデータベースを構築
mem = new ThinMemoryDb(allSvcs, allMachines, allVars, historyItems);
this.MemDb = mem;
}
// 構築したメモリデータベースをバックアップファイルに保存
long now = TickNow;
if (LastBackupSaveTick == 0 || now >= (LastBackupSaveTick + Controller.CurrentValue_ControllerDbBackupFileWriteIntervalMsecs))
{
try
{
long size = mem.SaveToFile(this.BackupFileName);
$"ThinDatabase.ReadCoreAsync Save to the backup file: {size._ToString3()} bytes, filename = '{this.BackupFileName}'"._Debug();
LastBackupSaveTick = now;
}
catch (Exception ex)
{
ex._Error();
}
}
Controller.StatMan?.AddReport("ReadFromDb_OK_Total", 1);
}
catch
{
// データベースからもバックアップファイルからもまだデータが読み込まれていない場合は、バックアップファイルから読み込む
if (this.MemDb == null)
{
this.MemDb = new ThinMemoryDb(this.BackupFileName);
}
Controller.StatMan?.AddReport("ReadFromDb_Error_Total", 1);
// バックアップファイルの読み込みを行なった上で、DB 例外はちゃんと throw する
throw;
}
}
public int LastDbReadTookMsecs { get; private set; } = 0;
// データベースから最新の情報を取得するタスク
async Task ReadMainLoopAsync(CancellationToken cancel)
{
int numCycle = 0;
int numError = 0;
$"ThinDatabase.ReadMainLoopAsync: Waiting for start."._Debug();
await TaskUtil.AwaitWithPollAsync(10000, 1000, () => this.IsStarted, cancel); //初期化時に止まるため、Timeout.Infinite→10000に変更。とりあえず動かすための緊急避難。
$"ThinDatabase.ReadMainLoopAsync: Started."._Debug();
while (cancel.IsCancellationRequested == false)
{
numCycle++;
$"ThinDatabase.ReadMainLoopAsync numCycle={numCycle}, numError={numError} Start."._Debug();
long startTick = Time.HighResTick64;
bool ok = false;
try
{
await ReadCoreAsync(cancel);
ok = true;
}
catch (Exception ex)
{
ex._Error();
}
long endTick = Time.HighResTick64;
if (ok)
{
LastDbReadTookMsecs = (int)(endTick - startTick);
}
else
{
LastDbReadTookMsecs = 0;
}
$"ThinDatabase.ReadMainLoopAsync numCycle={numCycle}, numError={numError} End. Took time: {endTick - startTick}"._Debug();
await cancel._WaitUntilCanceledAsync(Util.GenRandInterval(Controller.CurrentValue_ControllerDbFullReloadIntervalMsecs));
}
}
// データベース更新メイン
async Task<int> WriteCoreAsync(CancellationToken cancel)
{
int num = 0;
await using var db = await OpenDatabaseForWriteAsync(cancel);
await db.EnsureOpenAsync(cancel);
// キューが空になるまで 実施 いたします
while (cancel.IsCancellationRequested == false)
{
ThinDatabaseUpdateJob? queue = null;
if (LazyUpdateJobQueue.TryDequeue(out queue) == false)
{
break;
}
Controller.Throughput_DatabaseWrite.Add(1);
RetryHelper<int> r = new RetryHelper<int>(100, 10);
await r.RunAsync(async c =>
{
await queue.ProcAsync(db, c);
return 0;
}, cancel: cancel);
num++;
}
return num;
}
// データベースを更新するタスク
async Task WriteMainLoopAsync(CancellationToken cancel)
{
int numCycle = 0;
int numError = 0;
$"ThinDatabase.WriteMainLoopAsync: Waiting for start."._Debug();
await TaskUtil.AwaitWithPollAsync(10000, 1000, () => this.IsStarted, cancel);//初期化時に止まるため、Timeout.Infinite→10000に変更。とりあえず動かすための緊急避難。
$"ThinDatabase.WriteMainLoopAsync: Started."._Debug();
while (cancel.IsCancellationRequested == false)
{
if (this.LazyUpdateJobQueue.Count >= 1)
{
numCycle++;
$"ThinDatabase.WriteMainLoopAsync numCycle={numCycle}, numError={numError} Start."._Debug();
long startTick = Time.HighResTick64;
int num = 0;
try
{
num = await WriteCoreAsync(cancel);
}
catch (Exception ex)
{
ex._Error();
}
long endTick = Time.HighResTick64;
$"ThinDatabase.WriteMainLoopAsync numCycle={numCycle}, numError={numError} End. Written items: {num}, Took time: {endTick - startTick}"._Debug();
}
await cancel._WaitUntilCanceledAsync(Util.GenRandInterval(Controller.CurrentValue_ControllerDbWriteUpdateIntervalMsecs));
}
}
// 便利な Var 取得ルーチン集
public IEnumerable<ThinDbVar>? GetVars(string name)
{
var db = this.MemDb;
if (db == null) return null;
if (db.VarByName.TryGetValue(name, out List<ThinDbVar>? list) == false)
{
return new ThinDbVar[0];
}
return list;
}
public ThinDbVar? GetVar(string name)
=> GetVars(name)?.FirstOrDefault();
[return: NotNullIfNotNull("defaultValue")]
public string? GetVarString(string name, string? defaultValue = null)
=> GetVar(name)?.VAR_VALUE1 ?? defaultValue;
public int GetVarInt(string name, int defaultValue = 0)
=> GetVarString(name)?._ToInt() ?? defaultValue;
public bool GetVarBool(string name, bool defaultValue = false)
=> GetVarString(name)?._ToBool(defaultValue) ?? defaultValue;
protected override async Task CleanupImplAsync(Exception? ex)
{
try
{
await this.ReadMainLoopTask._TryWaitAsync();
await this.WriteMainLoopTask._TryWaitAsync();
}
finally
{
await base.CleanupImplAsync(ex);
}
}
readonly AsyncLock RenamePcidAsyncLock = new AsyncLock();
// WoL MAC の即時更新
public async Task UpdateDbForWolMac(string msid, string wolMacList, long serverMask64, DateTime now, CancellationToken cancel)
{
msid = msid._NonNullTrim();
now = now._NormalizeDateTime();
wolMacList = wolMacList._NonNull();
if (this.IsDatabaseConnected == false)
{
// データベースエラー発生中はこの処理は実行できない (スキップいたします)
return;
}
await using var db = await OpenDatabaseForWriteAsync(cancel);
Controller.Throughput_DatabaseWrite.Add(1);
await db.QueryWithNoReturnAsync("UPDATE MACHINE SET LAST_SERVER_DATE = @, WOL_MACLIST = @, SERVERMASK64 = @ WHERE MSID = @",
now, wolMacList, serverMask64, msid);
}
// ClientConnect によるデータベース情報更新
public void UpdateDbForClientConnect(string msid, DateTime now, string lastClientIp)
{
msid = msid._NonNullTrim();
now = now._NormalizeDateTime();
lastClientIp = lastClientIp._NonNullTrim();
EnqueueUpdateJob(async (db, c) =>
{
await db.QueryWithNoReturnAsync(
"UPDATE MACHINE SET NUM_CLIENT = NUM_CLIENT + 1, LAST_CLIENT_DATE = @, LAST_CLIENT_IP = @ WHERE MSID = @ " +
"UPDATE MACHINE SET FIRST_CLIENT_DATE = @ WHERE MSID = @ AND (FIRST_CLIENT_DATE IS NULL OR FIRST_CLIENT_DATE <= '1900/01/01')",
now, lastClientIp, msid,
now, msid);
});
}
// ServerConnect によるデータベース情報更新
public void UpdateDbForServerConnect(string msid, DateTime now, string lastIp, string realProxyIp, string lastFlag, string wolMacList, long serverMask64)
{
msid = msid._NonNullTrim();
now = now._NormalizeDateTime();
lastIp = lastIp._NonNullTrim();
realProxyIp = realProxyIp._NonNullTrim();
lastFlag = lastFlag._NonNullTrim();
wolMacList = wolMacList._NonNull();
EnqueueUpdateJob(async (db, c) =>
{
await db.QueryWithNoReturnAsync("UPDATE MACHINE SET NUM_SERVER = NUM_SERVER + 1, LAST_SERVER_DATE = @, LAST_IP = @, REAL_PROXY_IP = @, LAST_FLAG = @, WOL_MACLIST = @, SERVERMASK64 = @ WHERE MSID = @",
now, lastIp, realProxyIp, lastFlag, wolMacList, serverMask64, msid);
});
}
// PCID 変更実行
public async Task<VpnError> RenamePcidAsync(string msid, string newPcid, DateTime now, CancellationToken cancel = default)
{
// この関数は同時に 1 ユーザーからしか実行されないようにする
// (ローカルメモリデータベースをいじるため)
using var asyncLock = await RenamePcidAsyncLock.LockWithAwait(cancel);
msid = msid._NonNullTrim();
newPcid = newPcid._NonNullTrim();
VpnError err2 = ThinController.CheckPCID(newPcid);
if (err2 != VpnError.ERR_NO_ERROR) return err2;
VpnError err = VpnError.ERR_INTERNAL_ERROR;
// ローカルメモリデータベース上の PCID 情報を確認
var memDb = this.MemDb!;
if (memDb.MachineList.Where(x => x.PCID._IsSamei(newPcid)).Any())
{
// ローカルメモリデータベース上で重複
return VpnError.ERR_PCID_ALREADY_EXISTS;
}
if (this.IsDatabaseConnected == false)
{
// データベースエラー発生中はこの処理は実行できない
return VpnError.ERR_TEMP_ERROR;
}
await using var db = await OpenDatabaseForWriteAsync(cancel);
Controller.Throughput_DatabaseWrite.Add(1);
ThinDbMachine? updatedMachine = null;
// トランザクションを確立し厳格なチェックを実施
// (DB サーバー側で一意インデックスによりチェックするが、インデックスが間違っていた場合に備えて、トランザクションでも厳密にチェックするのである)
if (await db.TranAsync(async () =>
{
// MACHINE を取得
var machine = await db.EasySelectSingleAsync<ThinDbMachine>("SELECT * FROM MACHINE WHERE MSID = @MSID", new { MSID = msid }, false, true, cancel);
if (machine == null)
{
// おかしいな
err = VpnError.ERR_SECURITY_ERROR;
return false;
}
// 同一 PCID が存在しないかどうかチェック
if ((await db.QueryWithValueAsync("SELECT COUNT(MACHINE_ID) FROM MACHINE WHERE PCID = @ AND SVC_NAME = @", newPcid, machine.SVC_NAME)).Int != 0)
{
err = VpnError.ERR_PCID_ALREADY_EXISTS;
return false;
}
// 変更の実行
await db.QueryWithNoReturnAsync("UPDATE MACHINE SET PCID = @, UPDATE_DATE = @, PCID_UPDATE_DATE = @, PCID_VER = PCID_VER + 1 WHERE MSID = @",
newPcid, now, now, msid);
// 変更した結果を取得
updatedMachine = await db.EasySelectSingleAsync<ThinDbMachine>("SELECT * FROM MACHINE WHERE MSID = @MSID", new { MSID = msid }, false, true, cancel);
if (updatedMachine == null)
{
// おかしいな
err = VpnError.ERR_SECURITY_ERROR;
return false;
}
return true;
}) == false)
{
return err;
}
updatedMachine._MarkNotNull();
Controller.AddPcidToRecentPcidCandidateCache(newPcid);
// ローカルメモリデータベース上の PCID 情報を変更
var machine = memDb.MachineByMsid._GetOrDefault(msid);
if (machine != null)
{
machine.PCID = newPcid;
machine.PCID_UPDATE_DATE = updatedMachine.PCID_UPDATE_DATE;
machine.PCID_VER = updatedMachine.PCID_VER;
// メモリ上の PCID Dictionary をリビルド
memDb.RebuildPcidListOnMemory();
// PCID 変更履歴の更新
this.PcidChangeHistoryCache.Add(machine.MSID, new ThinDatabasePcidChangeHistory(machine.MSID, machine.PCID_VER, newPcid, updatedMachine.PCID_UPDATE_DATE));
}
return VpnError.ERR_NO_ERROR;
}
// サーバー登録実行
public async Task<VpnError> RegisterMachineAsync(string svcName, string msid, string pcid, string hostKey, string hostSecret2, DateTime now, string ip, string fqdn, string initialJsonAttributes, CancellationToken cancel = default)
{
svcName = svcName._NonNullTrim();
msid = msid._NonNullTrim();
pcid = pcid._NonNullTrim();
hostKey = hostKey._NonNullTrim();
hostSecret2 = hostSecret2._NonNullTrim();
ip = ip._NonNullTrim();
fqdn = fqdn._NonNullTrim();
initialJsonAttributes = initialJsonAttributes._NonNullTrim();
VpnError err2 = ThinController.CheckPCID(pcid);
if (err2 != VpnError.ERR_NO_ERROR) return err2;
// データベースエラー時は処理禁止
if (IsDatabaseConnected == false)
{
return VpnError.ERR_TEMP_ERROR;
}
VpnError err = VpnError.ERR_INTERNAL_ERROR;
await using var db = await OpenDatabaseForWriteAsync(cancel);
Controller.Throughput_DatabaseWrite.Add(1);
// トランザクションを確立し厳格なチェックを実施
// (DB サーバー側で一意インデックスによりチェックするが、インデックスが間違っていた場合に備えて、トランザクションでも厳密にチェックするのである)
if (await db.TranAsync(async () =>
{
// 同一 hostKey が存在しないかどうか確認
if ((await db.QueryWithValueAsync("SELECT COUNT(MACHINE_ID) FROM MACHINE WHERE CERT_HASH = @", hostKey)).Int != 0)
{
err = VpnError.ERR_SECURITY_ERROR;
return false;
}
// 同一シークレットが存在しないかどうかチェック
if ((await db.QueryWithValueAsync("SELECT COUNT(MACHINE_ID) FROM MACHINE WHERE HOST_SECRET2 = @", hostSecret2)).Int != 0)
{
err = VpnError.ERR_SECURITY_ERROR;
return false;
}
// 同一 PCID が存在しないかどうかチェック
if ((await db.QueryWithValueAsync("SELECT COUNT(MACHINE_ID) FROM MACHINE WHERE PCID = @ AND SVC_NAME = @", pcid, svcName)).Int != 0)
{
err = VpnError.ERR_PCID_ALREADY_EXISTS;
return false;
}
// 登録の実行
await db.QueryWithNoReturnAsync("INSERT INTO MACHINE (SVC_NAME, MSID, PCID, CERT_HASH, CREATE_DATE, UPDATE_DATE, LAST_SERVER_DATE, LAST_CLIENT_DATE, NUM_SERVER, NUM_CLIENT, CREATE_IP, CREATE_HOST, HOST_SECRET2, PCID_UPDATE_DATE, JSON_ATTRIBUTES) " +
"VALUES (@, @, @, @, @, @, @, @, @, @, @, @, @, @, @)",
svcName, msid, pcid, hostKey,
now, now, now, now,
0, 0,
ip, fqdn,
hostSecret2,
now, initialJsonAttributes);
return true;
}) == false)
{
return err;
}
Controller.AddPcidToRecentPcidCandidateCache(pcid);
return VpnError.ERR_NO_ERROR;
}
// MSID によるデータベースからの最新の Machine の取得
public async Task<ThinDbMachine?> SearchMachineByMsidFromDbForce(string msid, CancellationToken cancel = default)
{
if (IsDatabaseConnected == false)
{
// データベース読み込みメインループでエラーが発生している場合は、データベース接続を試行しない (大量の試行がなされ不具合が発生するおそれがあるため)
return null;
}
cancel.ThrowIfCancellationRequested();
Controller.Throughput_DatabaseRead.Add(1);
// ローカルメモリデータベースの検索でヒットしなかった場合 (たとえば、最近作成されたホストの場合) は、マスタデータベースを物理的に検索する
await using var db = await OpenDatabaseForReadAsync(cancel);
var foundMachine = await db.TranReadSnapshotIfNecessaryAsync(async () =>
{
return await db.EasySelectSingleAsync<ThinDbMachine>("select * from MACHINE where MSID = @MSID",
new
{
MSID = msid,
},
throwErrorIfMultipleFound: true, throwErrorIfNotFound: false, cancel: cancel);
});
return foundMachine;
}
// SvcName および Pcid による Machine の検索試行
public async Task<ThinDbMachine?> SearchMachineByPcidAsync(string svcName, string pcid, CancellationToken cancel = default)
{
// まずローカルメモリデータベースを検索する
var mem = this.MemDb;
if (mem != null)
{
var foundMachine = mem.MachineByPcidAndSvcName._GetOrDefault(pcid + "@" + svcName);
if (foundMachine != null)
{
// 発見
return foundMachine;
}
}
if (IsDatabaseConnected == false)
{
// データベース読み込みメインループでエラーが発生している場合は、データベース接続を試行しない (大量の試行がなされ不具合が発生するおそれがあるため)
return null;
}
cancel.ThrowIfCancellationRequested();
// ローカルメモリデータベースの検索でヒットしなかった場合 (たとえば、最近作成されたホストの場合) は、マスタデータベースを物理的に検索する
await using var db = await OpenDatabaseForReadAsync(cancel);
Controller.Throughput_DatabaseRead.Add(1);
var foundMachine2 = await db.TranReadSnapshotIfNecessaryAsync(async () =>
{
return await db.EasySelectSingleAsync<ThinDbMachine>("select * from MACHINE where PCID = @PCID and SVC_NAME = @SVC_NAME",
new
{
PCID = pcid,
SVC_NAME = svcName,
},
throwErrorIfMultipleFound: true, throwErrorIfNotFound: false, cancel: cancel);
});
if (foundMachine2 != null)
{
// 発見
return foundMachine2;
}
// 未発見
return null;
}
// HostKey および HostSecret2 による認証試行
public async Task<ThinDbMachine?> AuthMachineAsync(string hostKey, string hostSecret2, CancellationToken cancel = default)
{
// まずローカルメモリデータベースを検索する
var mem = this.MemDb;
if (mem != null)
{
var foundMachine = mem.MachineByCertHashAndHostSecret2._GetOrDefault(hostKey + "@" + hostSecret2);
if (foundMachine != null)
{
// 発見
return foundMachine;
}
// 2020/04 頃に登録された古いマシンは hostSecret2 がデータベースに登録されていない場合がある
foundMachine = mem.MachineByCertHashAndHostSecret2._GetOrDefault(hostKey + "@");
if (foundMachine != null)
{
// 発見
// データベースに hostSecret2 を登録する (つまり、アップグレード)
await using var db2 = await OpenDatabaseForWriteAsync(cancel);
Controller.Throughput_DatabaseWrite.Add(1);
await db2.QueryWithNoReturnAsync("UPDATE MACHINE SET HOST_SECRET2 = @ WHERE MSID = @ and HOST_SECRET2 = ''",
hostSecret2, foundMachine.MSID);
$"AuthMachineAsync: Upgrade hostSecret2: MSID = {foundMachine.MSID}"._Debug();
return foundMachine;
}
}
if (IsDatabaseConnected == false)
{
// データベース読み込みメインループでエラーが発生している場合は、データベース接続を試行しない (大量の試行がなされ不具合が発生するおそれがあるため)
return null;
}
cancel.ThrowIfCancellationRequested();
// ローカルメモリデータベースの検索でヒットしなかった場合 (たとえば、最近作成されたホストの場合) は、マスタデータベースを物理的に検索する
await using var db = await OpenDatabaseForReadAsync(cancel);
Controller.Throughput_DatabaseRead.Add(1);
var foundMachine2 = await db.TranReadSnapshotIfNecessaryAsync(async () =>
{
// 2020/04 頃に登録された古いマシンは hostSecret2 がデータベースに登録されていない場合がある
return await db.EasySelectSingleAsync<ThinDbMachine>("select * from MACHINE where CERT_HASH = @CERT_HASH and (HOST_SECRET2 = @HOST_SECRET2 OR HOST_SECRET2 = '')",
new
{
CERT_HASH = hostKey,
HOST_SECRET2 = hostSecret2,
},
throwErrorIfMultipleFound: true, throwErrorIfNotFound: false, cancel: cancel);
});
if (foundMachine2 != null)
{
// 発見
return foundMachine2;
}
// 未発見
return null;
}
}
}
#endif
| 38.246283 | 265 | 0.57675 | [
"Apache-2.0"
] | tyama0x7f/IPA-DN-Cores | Cores.NET/Cores.Codes/Codes/ThinController/ThinDatabase.cs | 44,885 | C# |
using Stride.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LionFire.Stride3D.Input
{
public static class PlatformKeyConversion
{
// REVIEW: These were assigned by looking at docs. May want to verify.
// TODO: Finish remaining codes
/// <summary>
/// To Windows Virtual-Key code
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
/// <remarks>
/// References:
/// - https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
/// - https://ultralig.ht/api/1_0/_key_codes_8h_source.html
/// </remarks>
public static int ToWindowsVirtualKeyCode(this Stride.Input.Keys key)
=> key switch
{
Keys.D0 => 0x30,
Keys.D1 => 0x31,
Keys.D2 => 0x32,
Keys.D3 => 0x33,
Keys.D4 => 0x34,
Keys.D5 => 0x35,
Keys.D6 => 0x36,
Keys.D7 => 0x37,
Keys.D8 => 0x38,
Keys.D9 => 0x39,
Keys.A => 0x41,
Keys.B => 0x42,
Keys.C => 0x43,
Keys.D => 0x44,
Keys.E => 0x45,
Keys.F => 0x46,
Keys.G => 0x47,
Keys.H => 0x48,
Keys.I => 0x49,
Keys.J => 0x4A,
Keys.K => 0x4B,
Keys.L => 0x4C,
Keys.M => 0x4D,
Keys.N => 0x4E,
Keys.O => 0x4F,
Keys.P => 0x50,
Keys.Q => 0x51,
Keys.R => 0x52,
Keys.S => 0x53,
Keys.T => 0x54,
Keys.U => 0x55,
Keys.V => 0x56,
Keys.W => 0x57,
Keys.X => 0x58,
Keys.Y => 0x59,
Keys.Z => 0x5A,
Keys.None => 0,
Keys.Cancel => 0x03, // TOCONFIRM
Keys.Back => 0x08,
Keys.Tab => 0x09,
//Keys.LineFeed => 0x,
Keys.Clear => 0x0C,
Keys.Enter => 0x0D,
//Keys.Return => 0x0D, // Dupe: Enter
//Keys.Pause => 0x ,
Keys.CapsLock => 0x14,
////Keys.Capital => 0x , // DUPE
//Keys.HangulMode => 0x ,
////Keys.KanaMode => 0x , // DUPE
//Keys.JunjaMode => 0x ,
//Keys.FinalMode => 0x ,
//Keys.HanjaMode => 0x ,
////Keys.KanjiMode => 0x , // DUPE
Keys.Escape => 0x1B,
//Keys.ImeConvert => 0x ,
//Keys.ImeNonConvert => 0x ,
//Keys.ImeAccept => 0x ,
//Keys.ImeModeChange => 0x ,
Keys.Space => 0x20,
Keys.PageUp => 0x21,
////Keys.Prior => 0x , // DUPE
////Keys.Next => 0x , // DUPE
Keys.PageDown => 0x22,
Keys.End => 0x23,
Keys.Home => 0x24,
Keys.Left => 0x25,
Keys.Up => 0x26,
Keys.Right => 0x27,
Keys.Down => 0x28,
//Keys.Select => 0x ,
//Keys.Print => 0x ,
//Keys.Execute => 0x ,
//Keys.PrintScreen => 0x ,
////Keys.Snapshot => 0x , // DUPE
Keys.Insert => 0x2D,
Keys.Delete => 0x2E,
Keys.Help => 0x2F,
Keys.LeftWin => 0x5B,
Keys.RightWin => 0x5C,
Keys.Apps => 0x5D,
Keys.Sleep => 0x5F,
Keys.NumPad0 => 0x60,
Keys.NumPad1 => 0x61,
Keys.NumPad2 => 0x62,
Keys.NumPad3 => 0x63,
Keys.NumPad4 => 0x64,
Keys.NumPad5 => 0x65,
Keys.NumPad6 => 0x66,
Keys.NumPad7 => 0x67,
Keys.NumPad8 => 0x68,
Keys.NumPad9 => 0x68,
Keys.Multiply => 0x6A,
Keys.Add => 0x6B,
Keys.Separator => 0x6C,
Keys.Subtract => 0x6D,
Keys.Decimal => 0x6E,
Keys.Divide => 0x6F,
Keys.F1 => 0x70,
Keys.F2 => 0x71,
Keys.F3 => 0x72,
Keys.F4 => 0x73,
Keys.F5 => 0x74,
Keys.F6 => 0x75,
Keys.F7 => 0x76,
Keys.F8 => 0x77,
Keys.F9 => 0x78,
Keys.F10 => 0x79,
Keys.F11 => 0x7A,
Keys.F12 => 0x7B,
Keys.F13 => 0x7C,
//Keys.F14 => 0x ,
//Keys.F15 => 0x ,
//Keys.F16 => 0x ,
//Keys.F17 => 0x ,
//Keys.F18 => 0x ,
//Keys.F19 => 0x ,
//Keys.F20 => 0x ,
//Keys.F21 => 0x ,
//Keys.F22 => 0x ,
//Keys.F23 => 0x ,
Keys.F24 => 0x87,
Keys.NumLock => 0x90,
Keys.Scroll => 0x91,
Keys.LeftShift => 0xA0,
Keys.RightShift => 0xA1,
Keys.LeftCtrl => 0xA2,
Keys.RightCtrl => 0xA3,
Keys.LeftAlt => 0xA4, // VK_LMenu Left MENU key (see also 0x12)
Keys.RightAlt => 0xA5, // VK_RMenu Right MENU key (see also 0x12)
Keys.BrowserBack => 0xA6,
Keys.BrowserForward => 0xA7,
Keys.BrowserRefresh => 0xA8,
Keys.BrowserStop => 0xA9,
Keys.BrowserSearch => 0xAA,
Keys.BrowserFavorites => 0xAB,
Keys.BrowserHome => 0xAC,
Keys.VolumeMute => 0xAD,
Keys.VolumeDown => 0xAE,
Keys.VolumeUp => 0xAF,
//Keys.MediaNextTrack => 0x ,
//Keys.MediaPreviousTrack => 0x ,
//Keys.MediaStop => 0x ,
//Keys.MediaPlayPause => 0x ,
//Keys.LaunchMail => 0x ,
//Keys.SelectMedia => 0x ,
//Keys.LaunchApplication1 => 0x ,
//Keys.LaunchApplication2 => 0x ,
Keys.Oem1 => 0xBA, // ;:
////Keys.OemSemicolon => 0x , // DUPE
Keys.OemPlus => 0xBB,
Keys.OemComma => 0xBC,
Keys.OemMinus => 0xBD,
Keys.OemPeriod => 0xBE,
Keys.Oem2 => 0xBF, // /?
////Keys.OemQuestion => 0x , // DUPE
Keys.OemTilde => 0xC0,
//Keys.Oem3 => 0xC0, // Dupe: OemTilde
Keys.OemOpenBrackets => 0xDB,
//Keys.Oem4 => 0xDB, // Dupe: OemOpenBrackets
Keys.OemPipe => 0xDC,
//Keys.Oem5 => 0xDC, // Dupe: OemPipe
Keys.Oem6 => 0xDD,
////Keys.OemCloseBrackets => 0x , // DUPE
Keys.OemQuotes => 0xDE,
//Keys.Oem7 => 0xDE, // Dupe: OemQuotes
Keys.Oem8 => 0xDF,
Keys.OemBackslash => 0xE2,
//Keys.Oem102 => 0xE2, // Dupe: Keys.OemBackslash
Keys.Attn => 0xF6,
Keys.CrSel => 0xF7,
Keys.ExSel => 0xF8,
Keys.EraseEof => 0xF9,
Keys.Play => 0xFA,
Keys.Zoom => 0xFB,
Keys.NoName => 0xFC,
Keys.Pa1 => 0xFD,
Keys.OemClear => 0xFE,
Keys.NumPadEnter => 0x0D,
Keys.NumPadDecimal => 0x6E,
_ => 0,
};
}
}
| 34.925439 | 87 | 0.389175 | [
"MIT"
] | LionFire/Core | src/LionFire.Hosting.Stride/Input/StrideKeyConversion.cs | 7,965 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using YesSql.Sql;
namespace YesSql.Services
{
/// <summary>
/// This class manages a linear identifiers block allocator
/// c.f., http://literatejava.com/hibernate/linear-block-allocator-a-superior-alternative-to-hilo/
/// </summary>
public class DbBlockIdGenerator : IIdGenerator
{
private object _synLock = new object();
public static string TableName => "Identifiers";
public readonly int MaxRetries = 20;
private ISqlDialect _dialect;
private IStore _store;
private int _blockSize;
private Dictionary<string, Range> _ranges = new Dictionary<string, Range>();
private string _tablePrefix;
private string SelectCommand;
private string UpdateCommand;
private string InsertCommand;
public DbBlockIdGenerator() : this(20)
{
}
public DbBlockIdGenerator(int blockSize)
{
_blockSize = blockSize;
}
public async Task InitializeAsync(IStore store, ISchemaBuilder builder)
{
_dialect = SqlDialectFactory.For(store.Configuration.ConnectionFactory.DbConnectionType);
_tablePrefix = store.Configuration.TablePrefix;
_store = store;
SelectCommand = "SELECT " + _dialect.QuoteForColumnName("nextval") + " FROM " + _dialect.QuoteForTableName(_tablePrefix + TableName) + " WHERE " + _dialect.QuoteForTableName("dimension") + " = @dimension;";
UpdateCommand = "UPDATE " + _dialect.QuoteForTableName(_tablePrefix + TableName) + " SET " + _dialect.QuoteForColumnName("nextval") + "=@new WHERE " + _dialect.QuoteForColumnName("nextval") + " = @previous AND " + _dialect.QuoteForColumnName("dimension") + " = @dimension;";
InsertCommand = "INSERT INTO " + _dialect.QuoteForTableName(_tablePrefix + TableName) + " (" + _dialect.QuoteForColumnName("dimension") + ", " + _dialect.QuoteForColumnName("nextval") + ") VALUES(@dimension, @nextval);";
using (var connection = store.Configuration.ConnectionFactory.CreateConnection())
{
await connection.OpenAsync();
try
{
using (var transaction = connection.BeginTransaction(store.Configuration.IsolationLevel))
{
var localBuilder = new SchemaBuilder(store.Configuration, transaction, false);
localBuilder.CreateTable(DbBlockIdGenerator.TableName, table => table
.Column<string>("dimension", column => column.PrimaryKey().NotNull())
.Column<ulong>("nextval")
)
.AlterTable(DbBlockIdGenerator.TableName, table => table
.CreateIndex("IX_Dimension", "dimension")
);
transaction.Commit();
}
}
catch
{
}
}
}
public long GetNextId(string collection)
{
lock (_synLock)
{
if (!_ranges.TryGetValue(collection, out var range))
{
throw new InvalidOperationException($"The collection '{collection}' was not initialized");
}
var nextId = range.Next();
if (nextId > range.End)
{
LeaseRange(range);
nextId = range.Next();
}
return nextId;
}
}
private void LeaseRange(Range range)
{
var affectedRows = 0;
long nextval = 0;
var retries = 0;
using (var connection = _store.Configuration.ConnectionFactory.CreateConnection())
{
connection.Open();
do
{
// Ensure we overwrite the value that has been read by this
// instance in case another client is trying to lease a range
// at the same time
using (var transaction = connection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
{
try
{
var selectCommand = connection.CreateCommand();
selectCommand.CommandText = SelectCommand;
var selectDimension = selectCommand.CreateParameter();
selectDimension.Value = range.Collection;
selectDimension.ParameterName = "@dimension";
selectCommand.Parameters.Add(selectDimension);
selectCommand.Transaction = transaction;
_store.Configuration.Logger.LogSql(SelectCommand);
nextval = Convert.ToInt64(selectCommand.ExecuteScalar());
var updateCommand = connection.CreateCommand();
updateCommand.CommandText = UpdateCommand;
var updateDimension = updateCommand.CreateParameter();
updateDimension.Value = range.Collection;
updateDimension.ParameterName = "@dimension";
updateCommand.Parameters.Add(updateDimension);
var newValue = updateCommand.CreateParameter();
newValue.Value = nextval + _blockSize;
newValue.ParameterName = "@new";
updateCommand.Parameters.Add(newValue);
var previousValue = updateCommand.CreateParameter();
previousValue.Value = nextval;
previousValue.ParameterName = "@previous";
updateCommand.Parameters.Add(previousValue);
updateCommand.Transaction = transaction;
_store.Configuration.Logger.LogSql(UpdateCommand);
affectedRows = updateCommand.ExecuteNonQuery();
transaction.Commit();
}
catch
{
affectedRows = 0;
transaction.Rollback();
}
}
if (retries++ > MaxRetries)
{
throw new Exception("Too many retries while trying to lease a range for: " + range.Collection);
}
} while (affectedRows == 0);
range.SetBlock(nextval, _blockSize);
}
}
public async Task InitializeCollectionAsync(IConfiguration configuration, string collection)
{
if (_ranges.ContainsKey(collection))
{
return;
}
object nextval;
using (var connection = configuration.ConnectionFactory.CreateConnection())
{
await connection.OpenAsync();
using (var transaction = connection.BeginTransaction(configuration.IsolationLevel))
{
// Does the record already exist?
var selectCommand = transaction.Connection.CreateCommand();
selectCommand.CommandText = SelectCommand;
var selectDimension = selectCommand.CreateParameter();
selectDimension.Value = collection;
selectDimension.ParameterName = "@dimension";
selectCommand.Parameters.Add(selectDimension);
selectCommand.Transaction = transaction;
_store.Configuration.Logger.LogSql(SelectCommand);
nextval = await selectCommand.ExecuteScalarAsync();
transaction.Commit();
}
if (nextval == null)
{
// Try to create a new record. If it fails, retry reading the record.
try
{
using (var transaction = connection.BeginTransaction(configuration.IsolationLevel))
{
nextval = 1;
// To prevent concurrency issues when creating this record (it must be unique)
// we generate a random collection name, then update it safely
var command = transaction.Connection.CreateCommand();
command.CommandText = InsertCommand;
command.Transaction = transaction;
var dimensionParameter = command.CreateParameter();
dimensionParameter.Value = collection;
dimensionParameter.ParameterName = "@dimension";
command.Parameters.Add(dimensionParameter);
var nextValParameter = command.CreateParameter();
nextValParameter.Value = 1;
nextValParameter.ParameterName = "@nextval";
command.Parameters.Add(nextValParameter);
_store.Configuration.Logger.LogSql(InsertCommand);
await command.ExecuteNonQueryAsync();
transaction.Commit();
}
}
catch
{
await InitializeCollectionAsync(configuration, collection);
}
}
_ranges[collection] = new Range(collection);
}
}
private class Range
{
public Range(string collection)
{
Collection = collection;
Cursor = 1;
}
public Range SetBlock(long start, int blockSize)
{
Start = start;
End = Start + blockSize - 1;
Cursor = 0;
return this;
}
public long Next()
{
return Start + Cursor++;
}
public string Collection;
public long Cursor;
public long Start;
public long End;
}
}
}
| 38.92029 | 286 | 0.503258 | [
"MIT"
] | siyamandayubi/yessql | src/YesSql.Core/Services/DbBlockIdGenerator.cs | 10,742 | C# |
//
// KeyboardKeyEventArgs.cs
//
// Copyright (C) 2019 OpenTK
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
//
using System;
using OpenToolkit.Windowing.Common.Input;
namespace OpenToolkit.Windowing.Common
{
/// <summary>
/// Defines the event data for <see cref="IWindowEvents.KeyDown"/> and <see cref="IWindowEvents.KeyUp"/> events.
/// </summary>
public readonly struct KeyboardKeyEventArgs
{
/// <summary>
/// Initializes a new instance of the <see cref="KeyboardKeyEventArgs"/> struct.
/// </summary>
/// <param name="key">The key that generated this event.</param>
/// <param name="scanCode">The scan code of the key that generated this event.</param>
/// <param name="modifiers">The key modifiers that were active when this event was generated.</param>
/// <param name="isRepeat">Whether this event is a repeat from the user holding the key down.</param>
public KeyboardKeyEventArgs(Key key, int scanCode, KeyModifiers modifiers, bool isRepeat)
{
Key = key;
ScanCode = scanCode;
Modifiers = modifiers;
IsRepeat = isRepeat;
}
/// <summary>
/// Gets the key that generated this event.
/// </summary>
public Key Key { get; }
/// <summary>
/// Gets the keyboard scan code of the key that generated this event.
/// </summary>
public int ScanCode { get; }
/// <summary>
/// Gets a bitwise combination representing the key modifiers were active when this event was generated.
/// </summary>
public KeyModifiers Modifiers { get; }
/// <summary>
/// Gets a value indicating whether
/// this key event is a repeat.
/// </summary>
/// <value>
/// true, if this event was caused by the user holding down
/// a key; false, if this was caused by the user pressing a
/// key for the first time.
/// </value>
public bool IsRepeat { get; }
/// <summary>
/// Gets a value indicating whether <see cref="OpenToolkit.Windowing.Common.Input.KeyModifiers.Alt" /> is pressed.
/// </summary>
/// <value><c>true</c> if pressed; otherwise, <c>false</c>.</value>
public bool Alt => Modifiers.HasFlag(KeyModifiers.Alt);
/// <summary>
/// Gets a value indicating whether <see cref="OpenToolkit.Windowing.Common.Input.KeyModifiers.Control" /> is pressed.
/// </summary>
/// <value><c>true</c> if pressed; otherwise, <c>false</c>.</value>
public bool Control => Modifiers.HasFlag(KeyModifiers.Control);
/// <summary>
/// Gets a value indicating whether <see cref="OpenToolkit.Windowing.Common.Input.KeyModifiers.Shift" /> is pressed.
/// </summary>
/// <value><c>true</c> if pressed; otherwise, <c>false</c>.</value>
public bool Shift => Modifiers.HasFlag(KeyModifiers.Shift);
/// <summary>
/// Gets a value indicating whether <see cref="OpenToolkit.Windowing.Common.Input.KeyModifiers.Shift" /> is pressed.
/// </summary>
/// <value><c>true</c> if pressed; otherwise, <c>false</c>.</value>
public bool Command => Modifiers.HasFlag(KeyModifiers.Command);
}
}
| 39.674419 | 126 | 0.608441 | [
"MIT"
] | AlseinX/opentk | src/Windowing/OpenToolkit.Windowing.Common/Events/KeyboardKeyEventArgs.cs | 3,414 | C# |
using CoolapkUWP.Data;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
//https://go.microsoft.com/fwlink/?LinkId=234236 上介绍了“用户控件”项模板
namespace CoolapkUWP.Control
{
//https://www.cnblogs.com/arcsinw/p/8638526.html
public sealed partial class ShowImageControl : UserControl
{
class ImageData
{
public ImageData(ImageType type, string url)
{
Type = type;
Url = url;
}
public void ChangeType()
{
if (Type == ImageType.SmallAvatar) Type = ImageType.BigAvatar;
else if (Type == ImageType.SmallImage) Type = ImageType.OriginImage;
}
public async Task<ImageSource> GetImage() => await ImageCache.GetImage(Type, Url, true);
public ImageType Type { get; private set; }
public string Url { get; set; }
}
Popup popup;
List<ImageData> datas = new List<ImageData>();
ObservableCollection<ImageSource> Images = new ObservableCollection<ImageSource>();
public ShowImageControl(Popup popup)
{
this.InitializeComponent();
Height = Window.Current.Bounds.Height;
Width = Window.Current.Bounds.Width;
Window.Current.SizeChanged += WindowSizeChanged;
popup.Closed += (s, e) => Window.Current.SizeChanged -= WindowSizeChanged;
this.popup = popup;
}
public void ShowImage(string url, ImageType type)
{
if (url.Substring(url.LastIndexOf('.')).ToLower().Contains("gif"))
if (type == ImageType.SmallImage)
datas.Add(new ImageData(ImageType.OriginImage, url));
else
datas.Add(new ImageData(ImageType.BigAvatar, url));
else datas.Add(new ImageData(type, url));
Images.Add(null);
}
public void ShowImages(string[] urls, ImageType type, int index)
{
for (int i = 0; i < urls.Length; i++)
{
if (urls[i].Substring(urls[i].LastIndexOf('.')).ToLower().Contains("gif"))
if (type == ImageType.SmallImage)
datas.Add(new ImageData(ImageType.OriginImage, urls[i]));
else datas.Add(new ImageData(ImageType.BigAvatar, urls[i]));
else datas.Add(new ImageData(type, urls[i]));
Images.Add(null);
}
Task.Run(async() =>
{
await Task.Delay(20);
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => SFlipView.SelectedIndex = index);
});
}
private void WindowSizeChanged(object sender, Windows.UI.Core.WindowSizeChangedEventArgs e)
{
Height = e.Size.Height;
Width = e.Size.Width;
}
private void CloseFlip_Click(object sender, RoutedEventArgs e) => popup.Hide();
private void UserControl_KeyUp(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Escape)
{
e.Handled = true;
popup.Hide();
}
}
private void ScrollViewerMain_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e)
{
ScrollViewer ScrollViewerMain = (sender as ScrollViewer);
if (ScrollViewerMain.ZoomFactor != 2) ScrollViewerMain.ChangeView(null, null, 2);
else ScrollViewerMain.ChangeView(null, null, 1);
}
private void ScrollViewerMain_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
ScrollViewer scrollViewer = ((sender as FrameworkElement).Parent as ScrollViewer);
scrollViewer.ChangeView(scrollViewer.HorizontalOffset - e.Delta.Translation.X * scrollViewer.ZoomFactor, scrollViewer.VerticalOffset - e.Delta.Translation.Y * scrollViewer.ZoomFactor, null);
}
private void SFlipView_RightTapped(object sender, RightTappedRoutedEventArgs e)
{
if (datas[SFlipView.SelectedIndex].Type == ImageType.BigAvatar || datas[SFlipView.SelectedIndex].Type == ImageType.OriginImage)
((SFlipView.ContextFlyout as MenuFlyout).Items[0] as MenuFlyoutItem).Visibility = Visibility.Collapsed;
else
((SFlipView.ContextFlyout as MenuFlyout).Items[0] as MenuFlyoutItem).Visibility = Visibility.Visible;
SFlipView.ContextFlyout.ShowAt(SFlipView);
}
private async void MenuFlyoutItem_Click(object sender, RoutedEventArgs e)
{
MenuFlyoutItem item = sender as MenuFlyoutItem;
datas[SFlipView.SelectedIndex].ChangeType();
Images[SFlipView.SelectedIndex] = await datas[SFlipView.SelectedIndex].GetImage();
switch (item.Tag as string)
{
case "save":
string u = datas[SFlipView.SelectedIndex].Url;
string fileName = u.Substring(u.LastIndexOf('/') + 1);
FileSavePicker fileSavePicker = new FileSavePicker
{
SuggestedStartLocation = PickerLocationId.PicturesLibrary,
SuggestedFileName = fileName.Replace(fileName.Substring(fileName.LastIndexOf('.')), string.Empty)
};
string uu = fileName.Substring(fileName.LastIndexOf('.') + 1);
int i = uu.IndexOfAny(new char[] { '?', '%', '&' });
uu = uu.Substring(0, i == -1 ? uu.Length : i);
fileSavePicker.FileTypeChoices.Add($"{uu}文件", new string[] { "." + uu });
StorageFile file = await fileSavePicker.PickSaveFileAsync();
if (file != null)
{
HttpClient httpClient = new HttpClient();
using (Stream fs = await file.OpenStreamForWriteAsync())
using (Stream s = (await (await (await ApplicationData.Current.LocalCacheFolder.GetFolderAsync(datas[SFlipView.SelectedIndex].Type.ToString())).GetFileAsync(Tools.GetMD5(u))).OpenReadAsync()).AsStreamForRead())
await s.CopyToAsync(fs);
}
break;
}
}
bool a = false;
private async void SFlipView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int i = SFlipView.SelectedIndex;
if (i == -1 || a)
{
return;
}
a = true;
Images[i] = await datas[i].GetImage();
a = false;
}
}
}
| 42.951515 | 234 | 0.581487 | [
"MIT"
] | oboard/CoolApk-UWP | 酷安 UWP/Control/ShowImageControl.xaml.cs | 7,119 | C# |
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// ReSharper disable ArrangeThisQualifier
// ReSharper disable InconsistentNaming
namespace NetZlib
{
using System;
using System.Runtime.CompilerServices;
// https://github.com/ymnk/jzlib/blob/master/src/main/java/com/jcraft/jzlib/CRC32.java
sealed class CRC32 : IChecksum
{
// The following logic has come from RFC1952.
int v;
static readonly int[] crc_table;
static CRC32()
{
crc_table = new int[256];
for (int n = 0; n < 256; n++)
{
int c = n;
for (int k = 8; --k >= 0;)
{
if ((c & 1) != 0)
c = (int)(0xedb88320 ^ (c.RightUShift(1)));
else
c = c.RightUShift(1);
}
crc_table[n] = c;
}
}
public void Update(byte[] buf, int index, int len)
{
int c = ~v;
while (--len >= 0)
c = crc_table[(c ^ buf[index++]) & 0xff] ^ (c.RightUShift(8));
v = ~c;
}
public void Reset() => v = 0;
public void Reset(long vv) => v = (int)(vv & 0xffffffffL);
public long GetValue() => v & 0xffffffffL;
// The following logic has come from zlib.1.2.
const int GF2_DIM = 32;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static long Combine(long crc1, long crc2, long len2)
{
var even = new long[GF2_DIM];
var odd = new long[GF2_DIM];
// degenerate case (also disallow negative lengths)
if (len2 <= 0)
return crc1;
// put operator for one zero bit in odd
odd[0] = 0xedb88320L; // CRC-32 polynomial
long row = 1;
for (int n = 1; n < GF2_DIM; n++)
{
odd[n] = row;
row <<= 1;
}
// put operator for two zero bits in even
gf2_matrix_square(even, odd);
// put operator for four zero bits in odd
gf2_matrix_square(odd, even);
// apply len2 zeros to crc1 (first square will put the operator for one
// zero byte, eight zero bits, in even)
do
{
// apply zeros operator for this bit of len2
gf2_matrix_square(even, odd);
if ((len2 & 1) != 0)
crc1 = gf2_matrix_times(even, crc1);
len2 >>= 1;
// if no more bits set, then done
if (len2 == 0)
break;
// another iteration of the loop with odd and even swapped
gf2_matrix_square(odd, even);
if ((len2 & 1) != 0)
crc1 = gf2_matrix_times(odd, crc1);
len2 >>= 1;
// if no more bits set, then done
}
while (len2 != 0);
/* return combined crc */
crc1 ^= crc2;
return crc1;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static long gf2_matrix_times(long[] mat, long vec)
{
long sum = 0;
int index = 0;
while (vec != 0)
{
if ((vec & 1) != 0)
sum ^= mat[index];
vec >>= 1;
index++;
}
return sum;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static void gf2_matrix_square(long[] square, long[] mat)
{
for (int n = 0; n < GF2_DIM; n++)
square[n] = gf2_matrix_times(mat, mat[n]);
}
/*
private java.util.zip.CRC32 crc32 = new java.util.zip.CRC32();
public void update(byte[] buf, int index, int len){
if(buf==null) {crc32.reset();}
else{crc32.update(buf, index, len);}
}
public void reset(){
crc32.reset();
}
public void reset(long init){
if(init==0L){
crc32.reset();
}
else{
System.err.println("unsupported operation");
}
}
public long getValue(){
return crc32.getValue();
}
*/
public IChecksum Copy()
{
var foo = new CRC32();
foo.v = this.v;
return foo;
}
public static int[] getCRC32Table()
{
var tmp = new int[crc_table.Length];
Array.Copy(crc_table, 0, tmp, 0, tmp.Length);
return tmp;
}
}
}
| 29.207317 | 102 | 0.46096 | [
"MIT"
] | StormHub/NetZlib | src/NetZlib/CRC32.cs | 4,792 | C# |
//==============================================================================
// TorqueLab -> Fonts Setup
// Copyright (c) 2015 All Right Reserved, http://nordiklab.com/
//------------------------------------------------------------------------------
//==============================================================================
//==============================================================================
function TerrainMaterialDlg::updateMaterialMapping( %this, %terrMat ) {
if (%terrMat $= "")
%terrMat = %this.activeMat;
%diffuse = %terrMat.diffuseMap;
%texName = fileBase(%diffuse);
%mapMat = getMaterialMapping(%texName);
if (isObject(%mapMat)) {
TerrainMatDlg_MaterialInfo-->matName.text = %mapMat;
TerrainMatDlg_MappedInspector.inspect(%mapMat);
TerrainMatDlg_MaterialInfo-->unmappedCont.visible = false;
TerrainMatDlg_MaterialInfo-->inspectorCont.visible = true;
TerrainMatDlg_MaterialInfo-->inspectorCont.extent = TerrainMatDlg_MappedInspector.extent;
TerrainMaterialDlg.mappedMat = %mapMat;
} else {
TerrainMatDlg_MaterialInfo-->matName.text = "";
TerrainMatDlg_MappedInspector.inspect("");
TerrainMatDlg_MaterialInfo-->inspectorCont.visible = false;
TerrainMatDlg_MaterialInfo-->unmappedCont.visible = true;
TerrainMaterialDlg.mappedMat = "";
}
}
//------------------------------------------------------------------------------
//==============================================================================
function TerrainMaterialDlg::saveMappedMat( %this, %terrMat ) {
%mapMat = %this.mappedMat;
if (!isObject(%mapMat))
return;
TerrainMatDlg_MappedInspector.apply();
devLog(%mapMat.getName(),"Material is dirty:",Lab_PM.isDirty(%mapMat));
if (!TerrainMatDlg_MappedInspector.isDirty) {
devLog("Nothing to save");
return;
}
Lab_PM.saveDirtyObject(%mapMat);
}
//------------------------------------------------------------------------------
//==============================================================================
function TerrainMaterialDlg::deleteMappedMat( %this, %terrMat ) {
%mapMat = %this.mappedMat;
if (!isObject(%mapMat))
return;
//%mapMat.delete();
%this.removeMappedMaterial(%mapMat);
}
//------------------------------------------------------------------------------
function TerrainMatDlg_MappedInspector::onInspectorFieldModified( %this, %object, %fieldName, %oldValue, %newValue ) {
Lab_PM.setDirty( %object );
TerrainMatDlg_MappedInspector.isDirty = true;
}
//------------------------------------------------------------------------------
function TerrainMatDlg_MappedInspector::inspect( %this, %object, %fieldName, %oldValue, %newValue ) {
%this.isDirty = false;
Parent::inspect( %this, %object );
}
//==============================================================================
//TerrainMaterialDlg.createMappedMaterial();
function TerrainMaterialDlg::createMappedMaterial( %this ) {
%terrMat = %this.activeMat;
%file = %terrMat.getFilename();
if (!isFile(%file)) {
warnLog("The current material doesn't have a valid file:",%file," A valid file is needed to create mapped material.");
return;
}
%diffuse = %terrMat.diffuseMap;
%texName = fileBase(%diffuse);
%mapMat = getMaterialMapping(%texName);
if (isObject(%mapMat)) {
warnLog("There's already a valid mapped material linked to this TerrainMaterial:",%mapMat);
return;
}
%newMapMat = singleton Material("GMat_"@%texName) {
mapTo = %texName;
footstepSoundId = 0;
terrainMaterials = "1";
ShowDust = "1";
showFootprints = "1";
materialTag0 = "Terrain";
impactSoundId = 0;
};
%startAtLine = 1; //Start writing obj at this line
%newMapMat.setFilename(%file);
%fileObj = getFileReadObj(%file);
while( !%fileObj.isEOF() ) {
%line = %fileObj.readLine();
%lines[%lineId++] = %line;
if (strFind(%line,"//Maps")) {
%startAtLine = %lineId+1;
}
}
closeFileObj(%fileObj);
%writeFile = %file;//strReplace(%file,".cs","_test.cs");
%fileWrite = getFileWriteObj(%writeFile);
//%fileWrite.writeLine("//==============================================================================");
//%fileWrite.writeLine("// Generated from TerrainMaterialDlg");
//%fileWrite.writeLine("//------------------------------------------------------------------------------");
%newline = 1;
for(%i = 1; %i<=%lineId; %i++) {
if (%startAtLine $= %i) {
%fileWrite.writeLine("singleton Material(GMat_"@%texName@")");
%fileWrite.writeLine("{");
%fileWrite.writeLine(" mapTo = \""@%texName@"\";");
%fileWrite.writeLine(" footstepSoundId = 0;");
%fileWrite.writeLine(" terrainMaterials = \"1\";");
%fileWrite.writeLine(" ShowDust = \"1\";");
%fileWrite.writeLine(" showFootprints = \"1\";");
%fileWrite.writeLine(" materialTag0 = \"Terrain\";");
%fileWrite.writeLine(" impactSoundId = 0;");
%fileWrite.writeLine("};");
//%fileWrite.writeLine("");
}
%fileWrite.writeLine(%lines[%i]);
}
closeFileObj(%fileWrite);
%this.updateMaterialMapping();
}
//------------------------------------------------------------------------------
//==============================================================================
//TerrainMaterialDlg.removeMappedMaterial("GMat_gvSandGrain01_c");
function TerrainMaterialDlg::removeMappedMaterial( %this,%mapMat ) {
if (!isObject(%mapMat)) {
warnLog("Invalid mapped material to remove:",%mapMat);
return;
}
%file = %mapMat.getFilename();
if (!isFile(%file)) {
warnLog("The current material doesn't have a valid file:",%file," A valid file is needed to create mapped material.");
return;
}
%file = %mapMat.getFilename();
%name = %mapMat.getName();
%fileObj = getFileReadObj(%file);
while( !%fileObj.isEOF() ) {
%line = %fileObj.readLine();
if (strFind(%line,%name)) {
%removeMode = true;
}
if (!%removeMode) {
%lines[%lineId++] = %line;
}
if (%removeMode && strFind(%line,"};"))
%removeMode = false;
}
closeFileObj(%fileObj);
%writeFile = %file;//strReplace(%file,".cs","_test.cs");
//%writeFile = strReplace(%file,".cs","_del.cs");
%fileWrite = getFileWriteObj(%writeFile);
for(%i = 1; %i<=%lineId; %i++) {
%fileWrite.writeLine(%lines[%i]);
}
closeFileObj(%fileWrite);
delObj(%mapMat);
%this.updateMaterialMapping();
}
//------------------------------------------------------------------------------
| 32.916667 | 120 | 0.548576 | [
"MIT"
] | Torque3D-Resources/TorqueLab-v0.5-Alpha | tlab/terrainEditor/terrainMaterials/terrainMaterialMap.cs | 6,320 | C# |
using Polly;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
namespace ErrorHandling
{
public static class PollyDemo
{
private static List<WebExceptionStatus> connectionFailure = new List<WebExceptionStatus>() {
WebExceptionStatus.ConnectFailure,
WebExceptionStatus.ConnectionClosed,
WebExceptionStatus.RequestCanceled,
WebExceptionStatus.PipelineFailure,
WebExceptionStatus.SendFailure,
WebExceptionStatus.KeepAliveFailure,
WebExceptionStatus.Timeout
};
private static List<WebExceptionStatus> resourceAccessFailure = new List<WebExceptionStatus>() {
WebExceptionStatus.NameResolutionFailure,
WebExceptionStatus.ProxyNameResolutionFailure,
WebExceptionStatus.ServerProtocolViolation
};
private static List<WebExceptionStatus> securityFailure = new List<WebExceptionStatus>() {
WebExceptionStatus.SecureChannelFailure,
WebExceptionStatus.TrustFailure
};
public static HttpResponseMessage ExecuteRemoteLookup()
{
var num = new Random().Next();
if (num % 3 == 0)
{
Console.WriteLine("Breaking the circuit");
throw new WebException("Name Resolution Failure", WebExceptionStatus.NameResolutionFailure);
}
else if (num % 4 == 0)
{
Console.WriteLine("Falling Back");
throw new WebException("Security Failure", WebExceptionStatus.TrustFailure);
}
else if (num % 2 == 0)
{
Console.WriteLine("Retrying connections...");
throw new WebException("Connection Failure", WebExceptionStatus.ConnectFailure);
}
return new HttpResponseMessage();
}
private static HttpResponseMessage GetAuthorizationErrorResponse()
{
return new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
public static void ExecuteRemoteLookupWithPolly()
{
Policy connFailurePolicy = Policy
.Handle<WebException>(x => connectionFailure.Contains(x.Status))
.RetryForever();
Policy<HttpResponseMessage> authFailurePolicy = Policy<HttpResponseMessage>
.Handle<WebException>(x => securityFailure.Contains(x.Status))
.Fallback(() => GetAuthorizationErrorResponse());
Policy nameResolutionPolicy = Policy
.Handle<WebException>(x => resourceAccessFailure.Contains(x.Status))
.CircuitBreaker(1, TimeSpan.FromMinutes(2));
Policy intermediatePolicy = Policy
.Wrap(connFailurePolicy, nameResolutionPolicy);
Policy<HttpResponseMessage> combinedPolicies = intermediatePolicy
.Wrap(authFailurePolicy);
try
{
HttpResponseMessage resp = combinedPolicies.Execute(() => ExecuteRemoteLookup());
if (resp.IsSuccessStatusCode)
{
Console.WriteLine("Success!");
}
else if (resp.StatusCode.Equals(HttpStatusCode.Unauthorized))
{
Console.WriteLine("We have fallen back!");
}
}
catch (WebException ex)
{
if (resourceAccessFailure.Contains(ex.Status))
{
Console.WriteLine("We should expect to see a broken circuit.");
}
}
}
}
} | 37.434343 | 108 | 0.592283 | [
"MIT"
] | wagnerhsu/packt-Hands-On-Network-Programming-with-CSharp-and-.NET-Core | Chapter 7/ErrorHandling/PollyDemo.cs | 3,708 | C# |
using MachineLearning.Data;
using System;
using System.Threading;
namespace MachineLearning.Model
{
/// <summary>
/// Trainer con validazione incrociata
/// </summary>
[Serializable]
public class ModelTrainerCrossValidation : IModelTrainer
{
#region Fields
/// <summary>
/// Seme per le operazioni random
/// </summary>
[NonSerialized]
private int _trainingSeed;
#endregion
#region Properties
/// <summary>
/// Numero di folds di training
/// </summary>
public int NumFolds { get; set; } = 5;
#endregion
#region Methods
/// <summary>
/// Restituisce il modello effettuando il training
/// </summary>
/// <param name="model">Modello con cui effettuare il training</param>
/// <param name="data">Dati di training</param>
/// <param name="evaluationMetrics">Eventuali metriche di valutazione precalcolate</param>
/// <param name="cancellation">Token di annullamento</param>
/// <returns>Il modello appreso</returns>
IDataTransformer IModelTrainer.GetTrainedModel(ModelBase model, IDataAccess data, out object evaluationMetrics, CancellationToken cancellation)
{
if (model is IModelTrainingCrossValidate training)
return training.CrossValidateTraining(data, out evaluationMetrics, NumFolds, null, _trainingSeed++, cancellation);
else
return ((IModelTrainer)new ModelTrainerStandard()).GetTrainedModel(model, data, out evaluationMetrics, cancellation);
}
#endregion
}
}
| 35.244444 | 149 | 0.663934 | [
"MIT"
] | darth-vader-lg/MachineLearning | src/MachineLearning/Model/ModelTrainerCrossValidation.cs | 1,588 | C# |
using System;
namespace FrogJump
{
public class Solution
{
public int solution(int X, int Y, int D) {
var distance = Y - X;
var mod = distance % D;
var result = distance / D;
return mod > 0
? result + 1
: result;
}
}
}
| 18.647059 | 51 | 0.457413 | [
"MIT"
] | 1OMKAR7NAM/HacktoberFest2020-Contributions | Algorithms/FrogJump/Solution.cs | 319 | 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 SimpleWpfApp.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SimpleWpfApp.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 35.402778 | 168 | 0.658297 | [
"MIT"
] | DangerousDarlow/WpfDesignData | SimpleWpfApp/Properties/Resources.Designer.cs | 2,551 | 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("StarshipSeven.GameEntities")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("StarshipSeven.GameEntities")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("0b15bd27-07e9-4cd1-8f1b-12e55b27f6ce")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.486486 | 85 | 0.730322 | [
"MIT"
] | smolyakoff/starshipseven | StarshipSeven.GameEntities/Properties/AssemblyInfo.cs | 1,464 | C# |
namespace WarCroft.Entities.Characters.Contracts
{
public interface IAttacker
{
void Attack(Character character);
}
} | 17.571429 | 49 | 0.780488 | [
"MIT"
] | Anzzhhela98/CSharp-Advanced | C# OOP/Exam Preparation/C# OOP Retake Exam - 19 December 2020/WarCroft/Entities/Characters/Contracts/IAttacker.cs | 125 | 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 accessanalyzer-2019-11-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Net;
using Amazon.AccessAnalyzer.Model;
using Amazon.AccessAnalyzer.Model.Internal.MarshallTransformations;
using Amazon.AccessAnalyzer.Internal;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.AccessAnalyzer
{
/// <summary>
/// Implementation for accessing AccessAnalyzer
///
/// AWS IAM Access Analyzer helps identify potential resource-access risks by enabling
/// you to identify any policies that grant access to an external principal. It does this
/// by using logic-based reasoning to analyze resource-based policies in your AWS environment.
/// An external principal can be another AWS account, a root user, an IAM user or role,
/// a federated user, an AWS service, or an anonymous user. This guide describes the AWS
/// IAM Access Analyzer operations that you can call programmatically. For general information
/// about Access Analyzer, see the <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html">AWS
/// IAM Access Analyzer section of the IAM User Guide</a>.
///
///
/// <para>
/// To start using Access Analyzer, you first need to create an analyzer.
/// </para>
/// </summary>
public partial class AmazonAccessAnalyzerClient : AmazonServiceClient, IAmazonAccessAnalyzer
{
private static IServiceMetadata serviceMetadata = new AmazonAccessAnalyzerMetadata();
#region Constructors
/// <summary>
/// Constructs AmazonAccessAnalyzerClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonAccessAnalyzerClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonAccessAnalyzerConfig()) { }
/// <summary>
/// Constructs AmazonAccessAnalyzerClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonAccessAnalyzerClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonAccessAnalyzerConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonAccessAnalyzerClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonAccessAnalyzerClient Configuration Object</param>
public AmazonAccessAnalyzerClient(AmazonAccessAnalyzerConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonAccessAnalyzerClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonAccessAnalyzerClient(AWSCredentials credentials)
: this(credentials, new AmazonAccessAnalyzerConfig())
{
}
/// <summary>
/// Constructs AmazonAccessAnalyzerClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonAccessAnalyzerClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonAccessAnalyzerConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonAccessAnalyzerClient with AWS Credentials and an
/// AmazonAccessAnalyzerClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonAccessAnalyzerClient Configuration Object</param>
public AmazonAccessAnalyzerClient(AWSCredentials credentials, AmazonAccessAnalyzerConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonAccessAnalyzerClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonAccessAnalyzerClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonAccessAnalyzerConfig())
{
}
/// <summary>
/// Constructs AmazonAccessAnalyzerClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonAccessAnalyzerClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonAccessAnalyzerConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonAccessAnalyzerClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonAccessAnalyzerClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonAccessAnalyzerClient Configuration Object</param>
public AmazonAccessAnalyzerClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonAccessAnalyzerConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonAccessAnalyzerClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonAccessAnalyzerClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonAccessAnalyzerConfig())
{
}
/// <summary>
/// Constructs AmazonAccessAnalyzerClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonAccessAnalyzerClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonAccessAnalyzerConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonAccessAnalyzerClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonAccessAnalyzerClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonAccessAnalyzerClient Configuration Object</param>
public AmazonAccessAnalyzerClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonAccessAnalyzerConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
/// <summary>
/// Capture metadata for the service.
/// </summary>
protected override IServiceMetadata ServiceMetadata
{
get
{
return serviceMetadata;
}
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region CreateAnalyzer
/// <summary>
/// Creates an analyzer for your account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateAnalyzer service method.</param>
///
/// <returns>The response from the CreateAnalyzer service method, as returned by AccessAnalyzer.</returns>
/// <exception cref="Amazon.AccessAnalyzer.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ConflictException">
/// A conflict exception error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.InternalServerException">
/// Internal server error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ServiceQuotaExceededException">
/// Service quote met error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ThrottlingException">
/// Throttling limit exceeded error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ValidationException">
/// Validation exception error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/CreateAnalyzer">REST API Reference for CreateAnalyzer Operation</seealso>
public virtual CreateAnalyzerResponse CreateAnalyzer(CreateAnalyzerRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateAnalyzerRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateAnalyzerResponseUnmarshaller.Instance;
return Invoke<CreateAnalyzerResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateAnalyzer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateAnalyzer operation on AmazonAccessAnalyzerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateAnalyzer
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/CreateAnalyzer">REST API Reference for CreateAnalyzer Operation</seealso>
public virtual IAsyncResult BeginCreateAnalyzer(CreateAnalyzerRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateAnalyzerRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateAnalyzerResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the CreateAnalyzer operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateAnalyzer.</param>
///
/// <returns>Returns a CreateAnalyzerResult from AccessAnalyzer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/CreateAnalyzer">REST API Reference for CreateAnalyzer Operation</seealso>
public virtual CreateAnalyzerResponse EndCreateAnalyzer(IAsyncResult asyncResult)
{
return EndInvoke<CreateAnalyzerResponse>(asyncResult);
}
#endregion
#region CreateArchiveRule
/// <summary>
/// Creates an archive rule for the specified analyzer. Archive rules automatically archive
/// findings that meet the criteria you define when you create the rule.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateArchiveRule service method.</param>
///
/// <returns>The response from the CreateArchiveRule service method, as returned by AccessAnalyzer.</returns>
/// <exception cref="Amazon.AccessAnalyzer.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ConflictException">
/// A conflict exception error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.InternalServerException">
/// Internal server error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ResourceNotFoundException">
/// The specified resource could not be found.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ServiceQuotaExceededException">
/// Service quote met error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ThrottlingException">
/// Throttling limit exceeded error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ValidationException">
/// Validation exception error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/CreateArchiveRule">REST API Reference for CreateArchiveRule Operation</seealso>
public virtual CreateArchiveRuleResponse CreateArchiveRule(CreateArchiveRuleRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateArchiveRuleRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateArchiveRuleResponseUnmarshaller.Instance;
return Invoke<CreateArchiveRuleResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateArchiveRule operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateArchiveRule operation on AmazonAccessAnalyzerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateArchiveRule
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/CreateArchiveRule">REST API Reference for CreateArchiveRule Operation</seealso>
public virtual IAsyncResult BeginCreateArchiveRule(CreateArchiveRuleRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateArchiveRuleRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateArchiveRuleResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the CreateArchiveRule operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateArchiveRule.</param>
///
/// <returns>Returns a CreateArchiveRuleResult from AccessAnalyzer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/CreateArchiveRule">REST API Reference for CreateArchiveRule Operation</seealso>
public virtual CreateArchiveRuleResponse EndCreateArchiveRule(IAsyncResult asyncResult)
{
return EndInvoke<CreateArchiveRuleResponse>(asyncResult);
}
#endregion
#region DeleteAnalyzer
/// <summary>
/// Deletes the specified analyzer. When you delete an analyzer, Access Analyzer is disabled
/// for the account in the current or specific Region. All findings that were generated
/// by the analyzer are deleted. You cannot undo this action.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteAnalyzer service method.</param>
///
/// <returns>The response from the DeleteAnalyzer service method, as returned by AccessAnalyzer.</returns>
/// <exception cref="Amazon.AccessAnalyzer.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.InternalServerException">
/// Internal server error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ResourceNotFoundException">
/// The specified resource could not be found.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ThrottlingException">
/// Throttling limit exceeded error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ValidationException">
/// Validation exception error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/DeleteAnalyzer">REST API Reference for DeleteAnalyzer Operation</seealso>
public virtual DeleteAnalyzerResponse DeleteAnalyzer(DeleteAnalyzerRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteAnalyzerRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteAnalyzerResponseUnmarshaller.Instance;
return Invoke<DeleteAnalyzerResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteAnalyzer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteAnalyzer operation on AmazonAccessAnalyzerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteAnalyzer
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/DeleteAnalyzer">REST API Reference for DeleteAnalyzer Operation</seealso>
public virtual IAsyncResult BeginDeleteAnalyzer(DeleteAnalyzerRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteAnalyzerRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteAnalyzerResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DeleteAnalyzer operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteAnalyzer.</param>
///
/// <returns>Returns a DeleteAnalyzerResult from AccessAnalyzer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/DeleteAnalyzer">REST API Reference for DeleteAnalyzer Operation</seealso>
public virtual DeleteAnalyzerResponse EndDeleteAnalyzer(IAsyncResult asyncResult)
{
return EndInvoke<DeleteAnalyzerResponse>(asyncResult);
}
#endregion
#region DeleteArchiveRule
/// <summary>
/// Deletes the specified archive rule.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteArchiveRule service method.</param>
///
/// <returns>The response from the DeleteArchiveRule service method, as returned by AccessAnalyzer.</returns>
/// <exception cref="Amazon.AccessAnalyzer.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.InternalServerException">
/// Internal server error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ResourceNotFoundException">
/// The specified resource could not be found.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ThrottlingException">
/// Throttling limit exceeded error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ValidationException">
/// Validation exception error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/DeleteArchiveRule">REST API Reference for DeleteArchiveRule Operation</seealso>
public virtual DeleteArchiveRuleResponse DeleteArchiveRule(DeleteArchiveRuleRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteArchiveRuleRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteArchiveRuleResponseUnmarshaller.Instance;
return Invoke<DeleteArchiveRuleResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteArchiveRule operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteArchiveRule operation on AmazonAccessAnalyzerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteArchiveRule
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/DeleteArchiveRule">REST API Reference for DeleteArchiveRule Operation</seealso>
public virtual IAsyncResult BeginDeleteArchiveRule(DeleteArchiveRuleRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteArchiveRuleRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteArchiveRuleResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the DeleteArchiveRule operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteArchiveRule.</param>
///
/// <returns>Returns a DeleteArchiveRuleResult from AccessAnalyzer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/DeleteArchiveRule">REST API Reference for DeleteArchiveRule Operation</seealso>
public virtual DeleteArchiveRuleResponse EndDeleteArchiveRule(IAsyncResult asyncResult)
{
return EndInvoke<DeleteArchiveRuleResponse>(asyncResult);
}
#endregion
#region GetAnalyzedResource
/// <summary>
/// Retrieves information about a resource that was analyzed.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetAnalyzedResource service method.</param>
///
/// <returns>The response from the GetAnalyzedResource service method, as returned by AccessAnalyzer.</returns>
/// <exception cref="Amazon.AccessAnalyzer.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.InternalServerException">
/// Internal server error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ResourceNotFoundException">
/// The specified resource could not be found.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ThrottlingException">
/// Throttling limit exceeded error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ValidationException">
/// Validation exception error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/GetAnalyzedResource">REST API Reference for GetAnalyzedResource Operation</seealso>
public virtual GetAnalyzedResourceResponse GetAnalyzedResource(GetAnalyzedResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetAnalyzedResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetAnalyzedResourceResponseUnmarshaller.Instance;
return Invoke<GetAnalyzedResourceResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the GetAnalyzedResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetAnalyzedResource operation on AmazonAccessAnalyzerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetAnalyzedResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/GetAnalyzedResource">REST API Reference for GetAnalyzedResource Operation</seealso>
public virtual IAsyncResult BeginGetAnalyzedResource(GetAnalyzedResourceRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetAnalyzedResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetAnalyzedResourceResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetAnalyzedResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetAnalyzedResource.</param>
///
/// <returns>Returns a GetAnalyzedResourceResult from AccessAnalyzer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/GetAnalyzedResource">REST API Reference for GetAnalyzedResource Operation</seealso>
public virtual GetAnalyzedResourceResponse EndGetAnalyzedResource(IAsyncResult asyncResult)
{
return EndInvoke<GetAnalyzedResourceResponse>(asyncResult);
}
#endregion
#region GetAnalyzer
/// <summary>
/// Retrieves information about the specified analyzer.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetAnalyzer service method.</param>
///
/// <returns>The response from the GetAnalyzer service method, as returned by AccessAnalyzer.</returns>
/// <exception cref="Amazon.AccessAnalyzer.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.InternalServerException">
/// Internal server error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ResourceNotFoundException">
/// The specified resource could not be found.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ThrottlingException">
/// Throttling limit exceeded error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ValidationException">
/// Validation exception error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/GetAnalyzer">REST API Reference for GetAnalyzer Operation</seealso>
public virtual GetAnalyzerResponse GetAnalyzer(GetAnalyzerRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetAnalyzerRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetAnalyzerResponseUnmarshaller.Instance;
return Invoke<GetAnalyzerResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the GetAnalyzer operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetAnalyzer operation on AmazonAccessAnalyzerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetAnalyzer
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/GetAnalyzer">REST API Reference for GetAnalyzer Operation</seealso>
public virtual IAsyncResult BeginGetAnalyzer(GetAnalyzerRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetAnalyzerRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetAnalyzerResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetAnalyzer operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetAnalyzer.</param>
///
/// <returns>Returns a GetAnalyzerResult from AccessAnalyzer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/GetAnalyzer">REST API Reference for GetAnalyzer Operation</seealso>
public virtual GetAnalyzerResponse EndGetAnalyzer(IAsyncResult asyncResult)
{
return EndInvoke<GetAnalyzerResponse>(asyncResult);
}
#endregion
#region GetArchiveRule
/// <summary>
/// Retrieves information about an archive rule.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetArchiveRule service method.</param>
///
/// <returns>The response from the GetArchiveRule service method, as returned by AccessAnalyzer.</returns>
/// <exception cref="Amazon.AccessAnalyzer.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.InternalServerException">
/// Internal server error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ResourceNotFoundException">
/// The specified resource could not be found.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ThrottlingException">
/// Throttling limit exceeded error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ValidationException">
/// Validation exception error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/GetArchiveRule">REST API Reference for GetArchiveRule Operation</seealso>
public virtual GetArchiveRuleResponse GetArchiveRule(GetArchiveRuleRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetArchiveRuleRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetArchiveRuleResponseUnmarshaller.Instance;
return Invoke<GetArchiveRuleResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the GetArchiveRule operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetArchiveRule operation on AmazonAccessAnalyzerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetArchiveRule
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/GetArchiveRule">REST API Reference for GetArchiveRule Operation</seealso>
public virtual IAsyncResult BeginGetArchiveRule(GetArchiveRuleRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetArchiveRuleRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetArchiveRuleResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetArchiveRule operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetArchiveRule.</param>
///
/// <returns>Returns a GetArchiveRuleResult from AccessAnalyzer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/GetArchiveRule">REST API Reference for GetArchiveRule Operation</seealso>
public virtual GetArchiveRuleResponse EndGetArchiveRule(IAsyncResult asyncResult)
{
return EndInvoke<GetArchiveRuleResponse>(asyncResult);
}
#endregion
#region GetFinding
/// <summary>
/// Retrieves information about the specified finding.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetFinding service method.</param>
///
/// <returns>The response from the GetFinding service method, as returned by AccessAnalyzer.</returns>
/// <exception cref="Amazon.AccessAnalyzer.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.InternalServerException">
/// Internal server error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ResourceNotFoundException">
/// The specified resource could not be found.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ThrottlingException">
/// Throttling limit exceeded error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ValidationException">
/// Validation exception error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/GetFinding">REST API Reference for GetFinding Operation</seealso>
public virtual GetFindingResponse GetFinding(GetFindingRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetFindingRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetFindingResponseUnmarshaller.Instance;
return Invoke<GetFindingResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the GetFinding operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetFinding operation on AmazonAccessAnalyzerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetFinding
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/GetFinding">REST API Reference for GetFinding Operation</seealso>
public virtual IAsyncResult BeginGetFinding(GetFindingRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetFindingRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetFindingResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the GetFinding operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetFinding.</param>
///
/// <returns>Returns a GetFindingResult from AccessAnalyzer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/GetFinding">REST API Reference for GetFinding Operation</seealso>
public virtual GetFindingResponse EndGetFinding(IAsyncResult asyncResult)
{
return EndInvoke<GetFindingResponse>(asyncResult);
}
#endregion
#region ListAnalyzedResources
/// <summary>
/// Retrieves a list of resources of the specified type that have been analyzed by the
/// specified analyzer..
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListAnalyzedResources service method.</param>
///
/// <returns>The response from the ListAnalyzedResources service method, as returned by AccessAnalyzer.</returns>
/// <exception cref="Amazon.AccessAnalyzer.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.InternalServerException">
/// Internal server error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ResourceNotFoundException">
/// The specified resource could not be found.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ThrottlingException">
/// Throttling limit exceeded error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ValidationException">
/// Validation exception error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/ListAnalyzedResources">REST API Reference for ListAnalyzedResources Operation</seealso>
public virtual ListAnalyzedResourcesResponse ListAnalyzedResources(ListAnalyzedResourcesRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListAnalyzedResourcesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListAnalyzedResourcesResponseUnmarshaller.Instance;
return Invoke<ListAnalyzedResourcesResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListAnalyzedResources operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListAnalyzedResources operation on AmazonAccessAnalyzerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListAnalyzedResources
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/ListAnalyzedResources">REST API Reference for ListAnalyzedResources Operation</seealso>
public virtual IAsyncResult BeginListAnalyzedResources(ListAnalyzedResourcesRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListAnalyzedResourcesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListAnalyzedResourcesResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListAnalyzedResources operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListAnalyzedResources.</param>
///
/// <returns>Returns a ListAnalyzedResourcesResult from AccessAnalyzer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/ListAnalyzedResources">REST API Reference for ListAnalyzedResources Operation</seealso>
public virtual ListAnalyzedResourcesResponse EndListAnalyzedResources(IAsyncResult asyncResult)
{
return EndInvoke<ListAnalyzedResourcesResponse>(asyncResult);
}
#endregion
#region ListAnalyzers
/// <summary>
/// Retrieves a list of analyzers.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListAnalyzers service method.</param>
///
/// <returns>The response from the ListAnalyzers service method, as returned by AccessAnalyzer.</returns>
/// <exception cref="Amazon.AccessAnalyzer.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.InternalServerException">
/// Internal server error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ThrottlingException">
/// Throttling limit exceeded error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ValidationException">
/// Validation exception error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/ListAnalyzers">REST API Reference for ListAnalyzers Operation</seealso>
public virtual ListAnalyzersResponse ListAnalyzers(ListAnalyzersRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListAnalyzersRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListAnalyzersResponseUnmarshaller.Instance;
return Invoke<ListAnalyzersResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListAnalyzers operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListAnalyzers operation on AmazonAccessAnalyzerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListAnalyzers
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/ListAnalyzers">REST API Reference for ListAnalyzers Operation</seealso>
public virtual IAsyncResult BeginListAnalyzers(ListAnalyzersRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListAnalyzersRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListAnalyzersResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListAnalyzers operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListAnalyzers.</param>
///
/// <returns>Returns a ListAnalyzersResult from AccessAnalyzer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/ListAnalyzers">REST API Reference for ListAnalyzers Operation</seealso>
public virtual ListAnalyzersResponse EndListAnalyzers(IAsyncResult asyncResult)
{
return EndInvoke<ListAnalyzersResponse>(asyncResult);
}
#endregion
#region ListArchiveRules
/// <summary>
/// Retrieves a list of archive rules created for the specified analyzer.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListArchiveRules service method.</param>
///
/// <returns>The response from the ListArchiveRules service method, as returned by AccessAnalyzer.</returns>
/// <exception cref="Amazon.AccessAnalyzer.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.InternalServerException">
/// Internal server error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ThrottlingException">
/// Throttling limit exceeded error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ValidationException">
/// Validation exception error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/ListArchiveRules">REST API Reference for ListArchiveRules Operation</seealso>
public virtual ListArchiveRulesResponse ListArchiveRules(ListArchiveRulesRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListArchiveRulesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListArchiveRulesResponseUnmarshaller.Instance;
return Invoke<ListArchiveRulesResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListArchiveRules operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListArchiveRules operation on AmazonAccessAnalyzerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListArchiveRules
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/ListArchiveRules">REST API Reference for ListArchiveRules Operation</seealso>
public virtual IAsyncResult BeginListArchiveRules(ListArchiveRulesRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListArchiveRulesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListArchiveRulesResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListArchiveRules operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListArchiveRules.</param>
///
/// <returns>Returns a ListArchiveRulesResult from AccessAnalyzer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/ListArchiveRules">REST API Reference for ListArchiveRules Operation</seealso>
public virtual ListArchiveRulesResponse EndListArchiveRules(IAsyncResult asyncResult)
{
return EndInvoke<ListArchiveRulesResponse>(asyncResult);
}
#endregion
#region ListFindings
/// <summary>
/// Retrieves a list of findings generated by the specified analyzer.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListFindings service method.</param>
///
/// <returns>The response from the ListFindings service method, as returned by AccessAnalyzer.</returns>
/// <exception cref="Amazon.AccessAnalyzer.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.InternalServerException">
/// Internal server error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ResourceNotFoundException">
/// The specified resource could not be found.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ThrottlingException">
/// Throttling limit exceeded error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ValidationException">
/// Validation exception error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/ListFindings">REST API Reference for ListFindings Operation</seealso>
public virtual ListFindingsResponse ListFindings(ListFindingsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListFindingsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListFindingsResponseUnmarshaller.Instance;
return Invoke<ListFindingsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListFindings operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListFindings operation on AmazonAccessAnalyzerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListFindings
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/ListFindings">REST API Reference for ListFindings Operation</seealso>
public virtual IAsyncResult BeginListFindings(ListFindingsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListFindingsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListFindingsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListFindings operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListFindings.</param>
///
/// <returns>Returns a ListFindingsResult from AccessAnalyzer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/ListFindings">REST API Reference for ListFindings Operation</seealso>
public virtual ListFindingsResponse EndListFindings(IAsyncResult asyncResult)
{
return EndInvoke<ListFindingsResponse>(asyncResult);
}
#endregion
#region ListTagsForResource
/// <summary>
/// Retrieves a list of tags applied to the specified resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListTagsForResource service method.</param>
///
/// <returns>The response from the ListTagsForResource service method, as returned by AccessAnalyzer.</returns>
/// <exception cref="Amazon.AccessAnalyzer.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.InternalServerException">
/// Internal server error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ResourceNotFoundException">
/// The specified resource could not be found.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ThrottlingException">
/// Throttling limit exceeded error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ValidationException">
/// Validation exception error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
public virtual ListTagsForResourceResponse ListTagsForResource(ListTagsForResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance;
return Invoke<ListTagsForResourceResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the ListTagsForResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListTagsForResource operation on AmazonAccessAnalyzerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListTagsForResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
public virtual IAsyncResult BeginListTagsForResource(ListTagsForResourceRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the ListTagsForResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginListTagsForResource.</param>
///
/// <returns>Returns a ListTagsForResourceResult from AccessAnalyzer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
public virtual ListTagsForResourceResponse EndListTagsForResource(IAsyncResult asyncResult)
{
return EndInvoke<ListTagsForResourceResponse>(asyncResult);
}
#endregion
#region StartResourceScan
/// <summary>
/// Immediately starts a scan of the policies applied to the specified resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StartResourceScan service method.</param>
///
/// <returns>The response from the StartResourceScan service method, as returned by AccessAnalyzer.</returns>
/// <exception cref="Amazon.AccessAnalyzer.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.InternalServerException">
/// Internal server error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ResourceNotFoundException">
/// The specified resource could not be found.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ThrottlingException">
/// Throttling limit exceeded error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ValidationException">
/// Validation exception error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/StartResourceScan">REST API Reference for StartResourceScan Operation</seealso>
public virtual StartResourceScanResponse StartResourceScan(StartResourceScanRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = StartResourceScanRequestMarshaller.Instance;
options.ResponseUnmarshaller = StartResourceScanResponseUnmarshaller.Instance;
return Invoke<StartResourceScanResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the StartResourceScan operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the StartResourceScan operation on AmazonAccessAnalyzerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndStartResourceScan
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/StartResourceScan">REST API Reference for StartResourceScan Operation</seealso>
public virtual IAsyncResult BeginStartResourceScan(StartResourceScanRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = StartResourceScanRequestMarshaller.Instance;
options.ResponseUnmarshaller = StartResourceScanResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the StartResourceScan operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginStartResourceScan.</param>
///
/// <returns>Returns a StartResourceScanResult from AccessAnalyzer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/StartResourceScan">REST API Reference for StartResourceScan Operation</seealso>
public virtual StartResourceScanResponse EndStartResourceScan(IAsyncResult asyncResult)
{
return EndInvoke<StartResourceScanResponse>(asyncResult);
}
#endregion
#region TagResource
/// <summary>
/// Adds a tag to the specified resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param>
///
/// <returns>The response from the TagResource service method, as returned by AccessAnalyzer.</returns>
/// <exception cref="Amazon.AccessAnalyzer.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.InternalServerException">
/// Internal server error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ResourceNotFoundException">
/// The specified resource could not be found.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ThrottlingException">
/// Throttling limit exceeded error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ValidationException">
/// Validation exception error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/TagResource">REST API Reference for TagResource Operation</seealso>
public virtual TagResourceResponse TagResource(TagResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = TagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance;
return Invoke<TagResourceResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the TagResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the TagResource operation on AmazonAccessAnalyzerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndTagResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/TagResource">REST API Reference for TagResource Operation</seealso>
public virtual IAsyncResult BeginTagResource(TagResourceRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = TagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the TagResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginTagResource.</param>
///
/// <returns>Returns a TagResourceResult from AccessAnalyzer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/TagResource">REST API Reference for TagResource Operation</seealso>
public virtual TagResourceResponse EndTagResource(IAsyncResult asyncResult)
{
return EndInvoke<TagResourceResponse>(asyncResult);
}
#endregion
#region UntagResource
/// <summary>
/// Removes a tag from the specified resource.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param>
///
/// <returns>The response from the UntagResource service method, as returned by AccessAnalyzer.</returns>
/// <exception cref="Amazon.AccessAnalyzer.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.InternalServerException">
/// Internal server error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ResourceNotFoundException">
/// The specified resource could not be found.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ThrottlingException">
/// Throttling limit exceeded error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ValidationException">
/// Validation exception error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/UntagResource">REST API Reference for UntagResource Operation</seealso>
public virtual UntagResourceResponse UntagResource(UntagResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UntagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance;
return Invoke<UntagResourceResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the UntagResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UntagResource operation on AmazonAccessAnalyzerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUntagResource
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/UntagResource">REST API Reference for UntagResource Operation</seealso>
public virtual IAsyncResult BeginUntagResource(UntagResourceRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = UntagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the UntagResource operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUntagResource.</param>
///
/// <returns>Returns a UntagResourceResult from AccessAnalyzer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/UntagResource">REST API Reference for UntagResource Operation</seealso>
public virtual UntagResourceResponse EndUntagResource(IAsyncResult asyncResult)
{
return EndInvoke<UntagResourceResponse>(asyncResult);
}
#endregion
#region UpdateArchiveRule
/// <summary>
/// Updates the criteria and values for the specified archive rule.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateArchiveRule service method.</param>
///
/// <returns>The response from the UpdateArchiveRule service method, as returned by AccessAnalyzer.</returns>
/// <exception cref="Amazon.AccessAnalyzer.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.InternalServerException">
/// Internal server error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ResourceNotFoundException">
/// The specified resource could not be found.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ThrottlingException">
/// Throttling limit exceeded error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ValidationException">
/// Validation exception error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/UpdateArchiveRule">REST API Reference for UpdateArchiveRule Operation</seealso>
public virtual UpdateArchiveRuleResponse UpdateArchiveRule(UpdateArchiveRuleRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateArchiveRuleRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateArchiveRuleResponseUnmarshaller.Instance;
return Invoke<UpdateArchiveRuleResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the UpdateArchiveRule operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateArchiveRule operation on AmazonAccessAnalyzerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateArchiveRule
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/UpdateArchiveRule">REST API Reference for UpdateArchiveRule Operation</seealso>
public virtual IAsyncResult BeginUpdateArchiveRule(UpdateArchiveRuleRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateArchiveRuleRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateArchiveRuleResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the UpdateArchiveRule operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateArchiveRule.</param>
///
/// <returns>Returns a UpdateArchiveRuleResult from AccessAnalyzer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/UpdateArchiveRule">REST API Reference for UpdateArchiveRule Operation</seealso>
public virtual UpdateArchiveRuleResponse EndUpdateArchiveRule(IAsyncResult asyncResult)
{
return EndInvoke<UpdateArchiveRuleResponse>(asyncResult);
}
#endregion
#region UpdateFindings
/// <summary>
/// Updates the status for the specified findings.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateFindings service method.</param>
///
/// <returns>The response from the UpdateFindings service method, as returned by AccessAnalyzer.</returns>
/// <exception cref="Amazon.AccessAnalyzer.Model.AccessDeniedException">
/// You do not have sufficient access to perform this action.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.InternalServerException">
/// Internal server error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ResourceNotFoundException">
/// The specified resource could not be found.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ThrottlingException">
/// Throttling limit exceeded error.
/// </exception>
/// <exception cref="Amazon.AccessAnalyzer.Model.ValidationException">
/// Validation exception error.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/UpdateFindings">REST API Reference for UpdateFindings Operation</seealso>
public virtual UpdateFindingsResponse UpdateFindings(UpdateFindingsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateFindingsRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateFindingsResponseUnmarshaller.Instance;
return Invoke<UpdateFindingsResponse>(request, options);
}
/// <summary>
/// Initiates the asynchronous execution of the UpdateFindings operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateFindings operation on AmazonAccessAnalyzerClient.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateFindings
/// operation.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/UpdateFindings">REST API Reference for UpdateFindings Operation</seealso>
public virtual IAsyncResult BeginUpdateFindings(UpdateFindingsRequest request, AsyncCallback callback, object state)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateFindingsRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateFindingsResponseUnmarshaller.Instance;
return BeginInvoke(request, options, callback, state);
}
/// <summary>
/// Finishes the asynchronous execution of the UpdateFindings operation.
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateFindings.</param>
///
/// <returns>Returns a UpdateFindingsResult from AccessAnalyzer.</returns>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/accessanalyzer-2019-11-01/UpdateFindings">REST API Reference for UpdateFindings Operation</seealso>
public virtual UpdateFindingsResponse EndUpdateFindings(IAsyncResult asyncResult)
{
return EndInvoke<UpdateFindingsResponse>(asyncResult);
}
#endregion
}
} | 54.350866 | 179 | 0.672371 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/AccessAnalyzer/Generated/_bcl35/AmazonAccessAnalyzerClient.cs | 81,635 | C# |
using System;
using System.Threading;
using tusdotnet.Adapters;
using tusdotnet.Extensions;
using tusdotnet.Interfaces;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
#if netfull
using Microsoft.Owin;
#endif
namespace tusdotnet.Models.Configuration
{
/// <summary>
/// Base context for all events in tusdotnet
/// </summary>
/// <typeparam name="TSelf">The type of the derived class inheriting the EventContext</typeparam>
public abstract class EventContext<TSelf> where TSelf : EventContext<TSelf>, new()
{
/// <summary>
/// The id of the file that was completed
/// </summary>
public string FileId { get; set; }
/// <summary>
/// The store that was used when completing the upload
/// </summary>
public ITusStore Store { get; set; }
/// <summary>
/// The request's cancellation token
/// </summary>
public CancellationToken CancellationToken { get; set; }
#if netfull
/// <summary>
/// The OWIN context for the current request
/// </summary>
public IOwinContext OwinContext { get; private set; }
#endif
/// <summary>
/// The http context for the current request
/// </summary>
public HttpContext HttpContext { get; private set; }
/// <summary>
/// Get the file with the id specified in the <see cref="FileId"/> property.
/// Returns null if there is no file id or if the file was not found.
/// </summary>
/// <returns>The file or null</returns>
public Task<ITusFile> GetFileAsync()
{
if(string.IsNullOrEmpty(FileId))
return Task.FromResult<ITusFile>(null);
return ((ITusReadableStore)Store).GetFileAsync(FileId, CancellationToken);
}
internal static TSelf Create(ContextAdapter context, Action<TSelf> configure = null)
{
var fileId = context.Request.FileId;
if (string.IsNullOrEmpty(fileId))
{
fileId = null;
}
var eventContext = new TSelf
{
Store = context.Configuration.Store,
CancellationToken = context.CancellationToken,
FileId = fileId,
HttpContext = context.HttpContext,
#if netfull
OwinContext = context.OwinContext
#endif
};
configure?.Invoke(eventContext);
return eventContext;
}
}
}
| 29.534884 | 101 | 0.590551 | [
"MIT"
] | Badabum/tusdotnet | Source/tusdotnet/Models/Configuration/EventContext.cs | 2,542 | C# |
using System;
using System.Threading.Tasks;
using System.Web.Http;
using Abp.Authorization;
using Abp.Authorization.Users;
using Abp.UI;
using Abp.Web.Models;
using Abp.WebApi.Controllers;
using AbpMvc5.Api.Models;
using AbpMvc5.Authorization;
using AbpMvc5.Authorization.Users;
using AbpMvc5.MultiTenancy;
using AbpMvc5.Users;
using Microsoft.Owin.Infrastructure;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
namespace AbpMvc5.Api.Controllers
{
public class AccountController : AbpApiController
{
public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }
private readonly LogInManager _logInManager;
static AccountController()
{
OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
}
public AccountController(LogInManager logInManager)
{
_logInManager = logInManager;
LocalizationSourceName = AbpMvc5Consts.LocalizationSourceName;
}
[HttpPost]
public async Task<AjaxResponse> Authenticate(LoginModel loginModel)
{
CheckModelState();
var loginResult = await GetLoginResultAsync(
loginModel.UsernameOrEmailAddress,
loginModel.Password,
loginModel.TenancyName
);
var ticket = new AuthenticationTicket(loginResult.Identity, new AuthenticationProperties());
var currentUtc = new SystemClock().UtcNow;
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
return new AjaxResponse(OAuthBearerOptions.AccessTokenFormat.Protect(ticket));
}
private async Task<AbpLoginResult<Tenant, User>> GetLoginResultAsync(string usernameOrEmailAddress, string password, string tenancyName)
{
var loginResult = await _logInManager.LoginAsync(usernameOrEmailAddress, password, tenancyName);
switch (loginResult.Result)
{
case AbpLoginResultType.Success:
return loginResult;
default:
throw CreateExceptionForFailedLoginAttempt(loginResult.Result, usernameOrEmailAddress, tenancyName);
}
}
private Exception CreateExceptionForFailedLoginAttempt(AbpLoginResultType result, string usernameOrEmailAddress, string tenancyName)
{
switch (result)
{
case AbpLoginResultType.Success:
return new ApplicationException("Don't call this method with a success result!");
case AbpLoginResultType.InvalidUserNameOrEmailAddress:
case AbpLoginResultType.InvalidPassword:
return new UserFriendlyException(L("LoginFailed"), L("InvalidUserNameOrPassword"));
case AbpLoginResultType.InvalidTenancyName:
return new UserFriendlyException(L("LoginFailed"), L("ThereIsNoTenantDefinedWithName{0}", tenancyName));
case AbpLoginResultType.TenantIsNotActive:
return new UserFriendlyException(L("LoginFailed"), L("TenantIsNotActive", tenancyName));
case AbpLoginResultType.UserIsNotActive:
return new UserFriendlyException(L("LoginFailed"), L("UserIsNotActiveAndCanNotLogin", usernameOrEmailAddress));
case AbpLoginResultType.UserEmailIsNotConfirmed:
return new UserFriendlyException(L("LoginFailed"), "Your email address is not confirmed. You can not login"); //TODO: localize message
default: //Can not fall to default actually. But other result types can be added in the future and we may forget to handle it
Logger.Warn("Unhandled login fail reason: " + result);
return new UserFriendlyException(L("LoginFailed"));
}
}
protected virtual void CheckModelState()
{
if (!ModelState.IsValid)
{
throw new UserFriendlyException("Invalid request!");
}
}
}
}
| 41.127451 | 154 | 0.658641 | [
"MIT"
] | meehealth/sample-AbpMvc5 | src/AbpMvc5.WebApi/Api/Controllers/AccountController.cs | 4,197 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using exploitation_csrf.Entities;
namespace exploitation_csrf.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<exploitation_csrf.Entities.Book> Book { get; set; }
}
}
| 25.45 | 83 | 0.740668 | [
"MIT"
] | PacktPublishing/Writing-Secure-Code-in-ASP.NET | cross_site_request_forgery/exploitation_csrf/exploitation_csrf/Data/ApplicationDbContext.cs | 509 | C# |
using UnityEngine;
using System.Collections;
public class SphereScript : MonoBehaviour {
public GameObject cam;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.position = cam.transform.position + Vector3.up * 1.1f;
}
}
| 18.058824 | 72 | 0.687296 | [
"MIT"
] | Michigari/PLATEAU_DroneNavigation | Assets/Camera/SphereScript.cs | 309 | C# |
//---------------------------------------------------------------------------
//
// <copyright file="ObservableCollection.cs" company="Microsoft">
// Copyright (C) 2003 by Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: Implementation of an Collection<T> implementing INotifyCollectionChanged
// to notify listeners of dynamic changes of the list.
//
// See spec at http://avalon/connecteddata/Specs/Collection%20Interfaces.mht
//
// History:
// 11/22/2004 : [....] - created
//
//---------------------------------------------------------------------------
#if (UNITY_5_5 && (ENABLE_MONO || ENABLE_IL2CPP)) || NET_2_0 || NET_2_0_SUBSET || (UNITY_EDITOR && ENABLE_DOTNET)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
namespace System.Collections.ObjectModel
{
/// <summary>
/// Implementation of a dynamic data collection based on generic Collection<T>,
/// implementing INotifyCollectionChanged to notify listeners
/// when items get added, removed or the whole list is refreshed.
/// </summary>
public class ObservableCollection<T> : Collection<T>, INotifyCollectionChanged, INotifyPropertyChanged
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// Initializes a new instance of ObservableCollection that is empty and has default initial capacity.
/// </summary>
public ObservableCollection()
: base()
{
}
/// <summary>
/// Initializes a new instance of the ObservableCollection class
/// that contains elements copied from the specified list
/// </summary>
/// <param name="list">The list whose elements are copied to the new list.</param>
/// <remarks>
/// The elements are copied onto the ObservableCollection in the
/// same order they are read by the enumerator of the list.
/// </remarks>
/// <exception cref="ArgumentNullException"> list is a null reference </exception>
public ObservableCollection(List<T> list)
: base((list != null) ? new List<T>(list.Count) : list)
{
// Workaround for VSWhidbey bug 562681 (tracked by Windows bug 1369339).
// We should be able to simply call the base(list) ctor. But Collection<T>
// doesn't copy the list (contrary to the documentation) - it uses the
// list directly as its storage. So we do the copying here.
//
CopyFrom(list);
}
/// <summary>
/// Initializes a new instance of the ObservableCollection class that contains
/// elements copied from the specified collection and has sufficient capacity
/// to accommodate the number of elements copied.
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new list.</param>
/// <remarks>
/// The elements are copied onto the ObservableCollection in the
/// same order they are read by the enumerator of the collection.
/// </remarks>
/// <exception cref="ArgumentNullException"> collection is a null reference </exception>
public ObservableCollection(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException("collection");
CopyFrom(collection);
}
private void CopyFrom(IEnumerable<T> collection)
{
IList<T> items = Items;
if (collection != null && items != null)
{
using (IEnumerator<T> enumerator = collection.GetEnumerator())
{
while (enumerator.MoveNext())
{
items.Add(enumerator.Current);
}
}
}
}
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Move item at oldIndex to newIndex.
/// </summary>
public void Move(int oldIndex, int newIndex)
{
MoveItem(oldIndex, newIndex);
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Events
//
//------------------------------------------------------
#region Public Events
//------------------------------------------------------
/// <summary>
/// PropertyChanged event (per <see cref="INotifyPropertyChanged" />).
/// </summary>
public virtual event PropertyChangedEventHandler PropertyChanged;
//------------------------------------------------------
/// <summary>
/// Occurs when the collection changes, either by adding or removing an item.
/// </summary>
/// <remarks>
/// see <seealso cref="INotifyCollectionChanged"/>
/// </remarks>
public virtual event NotifyCollectionChangedEventHandler CollectionChanged;
#endregion Public Events
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Called by base class Collection<T> when the list is being cleared;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void ClearItems()
{
CheckReentrancy();
base.ClearItems();
OnPropertyChanged(CountString);
OnPropertyChanged(IndexerName);
OnCollectionReset();
}
/// <summary>
/// Called by base class Collection<T> when an item is removed from list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void RemoveItem(int index)
{
CheckReentrancy();
T removedItem = this[index];
base.RemoveItem(index);
OnPropertyChanged(CountString);
OnPropertyChanged(IndexerName);
OnCollectionChanged(NotifyCollectionChangedAction.Remove, removedItem, index);
}
/// <summary>
/// Called by base class Collection<T> when an item is added to list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void InsertItem(int index, T item)
{
CheckReentrancy();
base.InsertItem(index, item);
OnPropertyChanged(CountString);
OnPropertyChanged(IndexerName);
OnCollectionChanged(NotifyCollectionChangedAction.Add, item, index);
}
/// <summary>
/// Called by base class Collection<T> when an item is set in list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void SetItem(int index, T item)
{
CheckReentrancy();
T originalItem = this[index];
base.SetItem(index, item);
OnPropertyChanged(IndexerName);
OnCollectionChanged(NotifyCollectionChangedAction.Replace, originalItem, item, index);
}
/// <summary>
/// Called by base class ObservableCollection<T> when an item is to be moved within the list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected virtual void MoveItem(int oldIndex, int newIndex)
{
CheckReentrancy();
T removedItem = this[oldIndex];
base.RemoveItem(oldIndex);
base.InsertItem(newIndex, removedItem);
OnPropertyChanged(IndexerName);
OnCollectionChanged(NotifyCollectionChangedAction.Move, removedItem, newIndex, oldIndex);
}
/// <summary>
/// Raises a PropertyChanged event (per <see cref="INotifyPropertyChanged" />).
/// </summary>
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(this, e);
}
}
/// <summary>
/// Raise CollectionChanged event to any listeners.
/// Properties/methods modifying this ObservableCollection will raise
/// a collection changed event through this virtual method.
/// </summary>
/// <remarks>
/// When overriding this method, either call its base implementation
/// or call <see cref="BlockReentrancy"/> to guard against reentrant collection changes.
/// </remarks>
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (CollectionChanged != null)
{
using (BlockReentrancy())
{
CollectionChanged(this, e);
}
}
}
/// <summary>
/// Disallow reentrant attempts to change this collection. E.g. a event handler
/// of the CollectionChanged event is not allowed to make changes to this collection.
/// </summary>
/// <remarks>
/// typical usage is to wrap e.g. a OnCollectionChanged call with a using() scope:
/// <code>
/// using (BlockReentrancy())
/// {
/// CollectionChanged(this, new NotifyCollectionChangedEventArgs(action, item, index));
/// }
/// </code>
/// </remarks>
protected IDisposable BlockReentrancy()
{
_monitor.Enter();
return _monitor;
}
/// <summary> Check and assert for reentrant attempts to change this collection. </summary>
/// <exception cref="InvalidOperationException"> raised when changing the collection
/// while another collection change is still being notified to other listeners </exception>
protected void CheckReentrancy()
{
if (_monitor.Busy)
{
// we can allow changes if there's only one listener - the problem
// only arises if reentrant changes make the original event args
// invalid for later listeners. This keeps existing code working
// (e.g. Selector.SelectedItems).
if ((CollectionChanged != null) && (CollectionChanged.GetInvocationList().Length > 1))
throw new InvalidOperationException("Cannot modify the collection while reentrancy is blocked.");
}
}
#endregion Protected Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
/// <summary>
/// Helper to raise a PropertyChanged event />).
/// </summary>
private void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Helper to raise CollectionChanged event to any listeners
/// </summary>
private void OnCollectionChanged(NotifyCollectionChangedAction action, object item, int index)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item, index));
}
/// <summary>
/// Helper to raise CollectionChanged event to any listeners
/// </summary>
private void OnCollectionChanged(NotifyCollectionChangedAction action, object item, int index, int oldIndex)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item, index, oldIndex));
}
/// <summary>
/// Helper to raise CollectionChanged event to any listeners
/// </summary>
private void OnCollectionChanged(NotifyCollectionChangedAction action, object oldItem, object newItem, int index)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, newItem, oldItem, index));
}
/// <summary>
/// Helper to raise CollectionChanged event with action == Reset to any listeners
/// </summary>
private void OnCollectionReset()
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
#endregion Private Methods
//------------------------------------------------------
//
// Private Types
//
//------------------------------------------------------
#region Private Types
// this class helps prevent reentrant calls
private class SimpleMonitor : IDisposable
{
public void Enter()
{
++_busyCount;
}
public void Dispose()
{
--_busyCount;
}
public bool Busy { get { return _busyCount > 0; } }
private int _busyCount;
}
#endregion Private Types
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
private const string CountString = "Count";
// This must agree with Binding.IndexerName. It is declared separately
// here so as to avoid a dependency on PresentationFramework.dll.
private const string IndexerName = "Item[]";
private SimpleMonitor _monitor = new SimpleMonitor();
#endregion Private Fields
}
}
#endif
| 36.7825 | 122 | 0.524842 | [
"MIT"
] | CodingJinxx/gameoff2020 | Gameoff2020/Assets/NoesisGUI/Plugins/API/Core/ObservableCollection.cs | 14,713 | C# |
using Dibware.Template.Core.Domain.Contracts.Services;
using Dibware.Template.Presentation.Web.Controllers.Base;
using Dibware.Template.Presentation.Web.Models.Error;
using Dibware.Template.Presentation.Web.Resources;
using System;
using System.Web;
using System.Web.Mvc;
namespace Dibware.Template.Presentation.Web.Filters
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class CustomHandleErrorAttribute : HandleErrorAttribute
{
//private IErrorService _errorService = null;
/// <summary>
/// Gets the error service.
/// </summary>
/// <value>
/// The error service.
/// </value>
//[Inject]
public IErrorService ErrorService { get; private set; }
//{
// get { return _errorService; }
// set { _errorService = value; }
//}
/// <summary>
/// Gets a value indicating whether to show detailed error messages.
/// </summary>
/// <value>
/// <c>true</c> if to show detailed error messages; otherwise, <c>false</c>.
/// </value>
public Boolean ShowDetailedErrorMessages { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="CustomHandleErrorAttribute"/> class.
/// </summary>
/// <param name="errorService">The error service.</param>
/// <param name="showDetailedErrorMessages">if set to <c>true</c> [show detailed error messages].</param>
public CustomHandleErrorAttribute(
IErrorService errorService,
Boolean showDetailedErrorMessages)
{
ErrorService = errorService;
ShowDetailedErrorMessages = showDetailedErrorMessages;
// Errors come here before other error filters
Order = 1;
}
/// <summary>
/// Called when an exception occurs.
/// </summary>
/// <param name="filterContext">The action-filter context.</param>
public override void OnException(ExceptionContext filterContext)
{
if (!filterContext.RequestContext.HttpContext.Request.IsAjaxRequest() &&
!filterContext.ExceptionHandled)
{
// Capture details we are interested in
var username = (String.IsNullOrEmpty(HttpContext.Current.User.Identity.Name) ?
"Guest" :
HttpContext.Current.User.Identity.Name);
var exception = filterContext.Exception;
// Log the error
LogException(exception, username);
// determine what sort of message we need to display to the user
var errorMessage = GetErrorMessage(
exception, username,
ShowDetailedErrorMessages);
// Create error view model
var model = new ErrorViewModel
{
PageTitle = PageTitles.Error,
PageSubTitle = PageSubTitles.ErroOccurredWhileProcessingAction,
ErrorMessage = errorMessage
};
// Fill that base view model with some data
var controller = (BaseController)filterContext.Controller;
controller.FillBaseViewModel(model);
// Set the result
filterContext.Result = new ViewResult
{
ViewName = "Error",
ViewData = new ViewDataDictionary<ErrorViewModel>(model)
};
// Configure the response object
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
}
/// <summary>
/// Gets the error message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="username">The username.</param>
/// <param name="ShowDetailedErrorMessages">if set to <c>true</c> [show detailed error messages].</param>
/// <returns></returns>
private static String GetErrorMessage(Exception exception,
String username, Boolean ShowDetailedErrorMessages)
{
var friendlyMessageFormat = WarningText.FriendlyErrorMessageFormat;
var detailedMessageText = (ShowDetailedErrorMessages ? exception.Message : String.Empty);
var fullMessage = String.Format(friendlyMessageFormat, username, detailedMessageText);
return fullMessage;
}
/// <summary>
/// Logs the exception.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="username">The username.</param>
private void LogException(Exception exception, string username)
{
try
{
if (ErrorService != null)
{
ErrorService.LogException(exception, username);
}
}
catch (Exception) { } // fail gracefully
}
}
} | 40.169118 | 114 | 0.565074 | [
"MIT"
] | dibley1973/Dibware.Template.Presentation.Web | Dibware.Template.Presentation.Web/Filters/CustomHandleErrorAttribute.cs | 5,465 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VO.Entities;
namespace DAO.Mappers
{
public class SettingsMapper : EntityTypeConfiguration<Settings>
{
private string Schema;
public SettingsMapper(string Schema)
{
// TODO: Complete member initialization
this.Schema = Schema;
this.ToTable("Settings", this.Schema);
this.HasKey(e => e.Id)
.Property(e => e.Id)
.HasColumnName("Sett_Id")
.HasColumnType("INT")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
.IsRequired();
this.Property(e => e.Key)
.HasColumnName("Sett_Key")
.IsRequired();
this.Property(e => e.Value)
.HasColumnName("Sett_Value")
.IsRequired();
}
}
}
| 27.175 | 75 | 0.576817 | [
"MIT"
] | haroldsalcedo01/Bitgray | EmpresaTelefonica/DAO/Mappers/SettingsMapper.cs | 1,089 | C# |
using UnityEngine;
using System;
public static class Util {
public static void BroadcastEveryone(string message, object parameter, SendMessageOptions options) {
foreach (var go in (GameObject[]) GameObject.FindObjectsOfType(typeof(GameObject))) {
go.SendMessage(message, parameter, SendMessageOptions.DontRequireReceiver);
}
}
public static void BroadcastEveryone(string message, SendMessageOptions options) {
BroadcastEveryone(message, null, options);
}
public static Vector2 xy(this Vector3 v) {
return new Vector2(v.x, v.y);
}
public static Vector3 MoveTowards(Vector3 from, Vector3 to, float max) {
return new Vector3(
Mathf.MoveTowards(from.x, to.x, max),
Mathf.MoveTowards(from.y, to.y, max),
Mathf.MoveTowards(from.z, to.z, max));
}
public static Vector2 MoveTowards(Vector2 from, Vector2 to, float max) {
return new Vector2(
Mathf.MoveTowards(from.x, to.x, max),
Mathf.MoveTowards(from.y, to.y, max)
);
}
public static T RandomItem<T>(T[] arr) {
if (arr.Length == 0) {
throw new Exception("Empty array");
}
return arr[(int) (arr.Length * UnityEngine.Random.value)];
}
} | 32.804878 | 105 | 0.608922 | [
"MIT"
] | WeAthFoLD/PurEgo | Assets/Script/Util.cs | 1,305 | C# |
namespace MeetAndGo.WinUI.Rented
{
partial class frmRentedOffices
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.dgvRentedOffices = new System.Windows.Forms.DataGridView();
this.txt_Price = new System.Windows.Forms.TextBox();
this.label9 = new System.Windows.Forms.Label();
this.txt_Adress = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.txt_LastName = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.btnCancel = new System.Windows.Forms.Button();
this.txt_FirstName = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.txt_OfficeName = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.pbx_Picture = new System.Windows.Forms.PictureBox();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.dtp_BeginRentalDate = new System.Windows.Forms.DateTimePicker();
this.dtp_EndRentalDate = new System.Windows.Forms.DateTimePicker();
this.txt_Days = new System.Windows.Forms.TextBox();
this.label7 = new System.Windows.Forms.Label();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dgvRentedOffices)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pbx_Picture)).BeginInit();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.dgvRentedOffices);
this.groupBox1.Location = new System.Drawing.Point(35, 356);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(663, 267);
this.groupBox1.TabIndex = 5;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Rented Offices";
//
// dgvRentedOffices
//
this.dgvRentedOffices.AllowUserToAddRows = false;
this.dgvRentedOffices.AllowUserToDeleteRows = false;
this.dgvRentedOffices.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgvRentedOffices.Dock = System.Windows.Forms.DockStyle.Fill;
this.dgvRentedOffices.Location = new System.Drawing.Point(3, 16);
this.dgvRentedOffices.Name = "dgvRentedOffices";
this.dgvRentedOffices.ReadOnly = true;
this.dgvRentedOffices.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dgvRentedOffices.Size = new System.Drawing.Size(657, 248);
this.dgvRentedOffices.TabIndex = 0;
this.dgvRentedOffices.CellDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvRentedOffices_CellDoubleClick);
//
// txt_Price
//
this.txt_Price.Location = new System.Drawing.Point(38, 189);
this.txt_Price.Name = "txt_Price";
this.txt_Price.Size = new System.Drawing.Size(219, 20);
this.txt_Price.TabIndex = 157;
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(35, 173);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(31, 13);
this.label9.TabIndex = 164;
this.label9.Text = "Price";
//
// txt_Adress
//
this.txt_Adress.Location = new System.Drawing.Point(38, 150);
this.txt_Adress.Name = "txt_Adress";
this.txt_Adress.Size = new System.Drawing.Size(219, 20);
this.txt_Adress.TabIndex = 156;
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(35, 134);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(39, 13);
this.label6.TabIndex = 163;
this.label6.Text = "Adress";
//
// txt_LastName
//
this.txt_LastName.Location = new System.Drawing.Point(38, 72);
this.txt_LastName.Name = "txt_LastName";
this.txt_LastName.Size = new System.Drawing.Size(219, 20);
this.txt_LastName.TabIndex = 155;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(35, 56);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(58, 13);
this.label5.TabIndex = 162;
this.label5.Text = "Last Name";
//
// btnCancel
//
this.btnCancel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
this.btnCancel.ForeColor = System.Drawing.Color.Red;
this.btnCancel.Location = new System.Drawing.Point(536, 280);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(159, 35);
this.btnCancel.TabIndex = 158;
this.btnCancel.Text = "Cancel reservation";
this.btnCancel.UseVisualStyleBackColor = false;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// txt_FirstName
//
this.txt_FirstName.Location = new System.Drawing.Point(38, 33);
this.txt_FirstName.Name = "txt_FirstName";
this.txt_FirstName.Size = new System.Drawing.Size(219, 20);
this.txt_FirstName.TabIndex = 154;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(35, 17);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(57, 13);
this.label2.TabIndex = 161;
this.label2.Text = "First Name";
//
// txt_OfficeName
//
this.txt_OfficeName.Location = new System.Drawing.Point(38, 111);
this.txt_OfficeName.Name = "txt_OfficeName";
this.txt_OfficeName.Size = new System.Drawing.Size(219, 20);
this.txt_OfficeName.TabIndex = 153;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(35, 95);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(66, 13);
this.label1.TabIndex = 160;
this.label1.Text = "Office Name";
//
// pbx_Picture
//
this.pbx_Picture.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.pbx_Picture.Location = new System.Drawing.Point(426, 33);
this.pbx_Picture.Name = "pbx_Picture";
this.pbx_Picture.Size = new System.Drawing.Size(269, 231);
this.pbx_Picture.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pbx_Picture.TabIndex = 159;
this.pbx_Picture.TabStop = false;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(32, 251);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(94, 13);
this.label3.TabIndex = 166;
this.label3.Text = "Begin Rental Date";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(32, 292);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(86, 13);
this.label4.TabIndex = 168;
this.label4.Text = "End Rental Date";
//
// dtp_BeginRentalDate
//
this.dtp_BeginRentalDate.Location = new System.Drawing.Point(35, 269);
this.dtp_BeginRentalDate.Name = "dtp_BeginRentalDate";
this.dtp_BeginRentalDate.Size = new System.Drawing.Size(219, 20);
this.dtp_BeginRentalDate.TabIndex = 169;
//
// dtp_EndRentalDate
//
this.dtp_EndRentalDate.Location = new System.Drawing.Point(35, 308);
this.dtp_EndRentalDate.Name = "dtp_EndRentalDate";
this.dtp_EndRentalDate.Size = new System.Drawing.Size(219, 20);
this.dtp_EndRentalDate.TabIndex = 170;
//
// txt_Days
//
this.txt_Days.Location = new System.Drawing.Point(35, 228);
this.txt_Days.Name = "txt_Days";
this.txt_Days.Size = new System.Drawing.Size(219, 20);
this.txt_Days.TabIndex = 171;
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(32, 212);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(64, 13);
this.label7.TabIndex = 172;
this.label7.Text = "Days rented";
//
// frmRentedOffices
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(741, 635);
this.Controls.Add(this.txt_Days);
this.Controls.Add(this.label7);
this.Controls.Add(this.dtp_EndRentalDate);
this.Controls.Add(this.dtp_BeginRentalDate);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.txt_Price);
this.Controls.Add(this.label9);
this.Controls.Add(this.txt_Adress);
this.Controls.Add(this.label6);
this.Controls.Add(this.txt_LastName);
this.Controls.Add(this.label5);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.txt_FirstName);
this.Controls.Add(this.label2);
this.Controls.Add(this.txt_OfficeName);
this.Controls.Add(this.label1);
this.Controls.Add(this.pbx_Picture);
this.Controls.Add(this.groupBox1);
this.Name = "frmRentedOffices";
this.Text = "frmRentedOffices";
this.Load += new System.EventHandler(this.frmRentedOffices_Load);
this.groupBox1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dgvRentedOffices)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pbx_Picture)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.DataGridView dgvRentedOffices;
private System.Windows.Forms.TextBox txt_Price;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.TextBox txt_Adress;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.TextBox txt_LastName;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.TextBox txt_FirstName;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txt_OfficeName;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.PictureBox pbx_Picture;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.DateTimePicker dtp_BeginRentalDate;
private System.Windows.Forms.DateTimePicker dtp_EndRentalDate;
private System.Windows.Forms.TextBox txt_Days;
private System.Windows.Forms.Label label7;
}
} | 46.072664 | 146 | 0.58573 | [
"MIT"
] | emin-alajbegovic/Meet-Go | MeetAndGo/MeetAndGo.WinUI/Rented/frmRentedOffices.Designer.cs | 13,317 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using MyJetWallet.Circle.Settings.Services;
using MyJetWallet.Domain.Assets;
using MyJetWallet.Sdk.Service;
using MyJetWallet.Sdk.ServiceBus;
using Newtonsoft.Json;
using Service.AssetsDictionary.Client;
using Service.Bitgo.DepositDetector.Domain.Models;
using Service.Bitgo.DepositDetector.Postgres;
using Service.Bitgo.DepositDetector.Postgres.Models;
using Service.Fireblocks.Webhook.ServiceBus.Deposits;
// ReSharper disable InconsistentLogPropertyNaming
// ReSharper disable TemplateIsNotCompileTimeConstantProblem
namespace Service.Bitgo.DepositDetector.Services
{
public class FireblocksDepositProcessingService
{
private readonly DbContextOptionsBuilder<DatabaseContext> _dbContextOptionsBuilder;
private readonly ILogger<FireblocksDepositProcessingService> _logger;
private readonly IAssetsDictionaryClient _assetsDictionary;
private readonly IServiceBusPublisher<Deposit> _depositPublisher;
public FireblocksDepositProcessingService(
ILogger<FireblocksDepositProcessingService> logger,
DbContextOptionsBuilder<DatabaseContext> dbContextOptionsBuilder,
IAssetsDictionaryClient assetsDictionary,
IServiceBusPublisher<Deposit> depositPublisher,
ICircleAssetMapper circleAssetMapper,
ICircleBlockchainMapper circleBlockchainMapper)
{
_logger = logger;
_dbContextOptionsBuilder = dbContextOptionsBuilder;
_assetsDictionary = assetsDictionary;
_depositPublisher = depositPublisher;
}
public async Task HandledDepositAsync(FireblocksDepositSignal deposit)
{
deposit.AddToActivityAsJsonTag("fireblocks-deposit");
_logger.LogInformation("Request to handle deposit from fireblocks: {transferJson}",
JsonConvert.SerializeObject(deposit));
deposit.BrokerId.AddToActivityAsTag("brokerId");
deposit.WalletId.AddToActivityAsTag("walletId");
deposit.ClientId.AddToActivityAsTag("clientId");
var accuracy = _assetsDictionary.GetAssetById(new AssetIdentity
{
Symbol = deposit.AssetSymbol,
BrokerId = deposit.BrokerId
}).Accuracy;
var amount = deposit.Amount;
//var feeAmount = double.Parse(string.IsNullOrEmpty(deposit.PaymentInfo?.Fees?.Amount)
// ? "0.0"
// : deposit.PaymentInfo.Fees.Amount);
var roundedAmount = Math.Round(amount, accuracy, MidpointRounding.ToNegativeInfinity);
try
{
await using var ctx = DatabaseContext.Create(_dbContextOptionsBuilder);
var existingEntity =
await ctx.Deposits.Where(e => e.TransactionId == deposit.TransactionId).FirstOrDefaultAsync();
if (existingEntity == null)
{
_logger.LogInformation("Got deposit from fireblocks, adding entry");
existingEntity = new DepositEntity
{
BrokerId = deposit.BrokerId,
WalletId = deposit.WalletId,
ClientId = deposit.ClientId,
TransactionId = deposit.TransactionId,
Amount = amount,
AssetSymbol = deposit.AssetSymbol,
Comment = "",
Integration = "Fireblocks",
Txid = deposit.TransactionId,
Status = DepositStatus.New,
EventDate = deposit.EventDate.ToUniversalTime(),
UpdateDate = DateTime.UtcNow,
//FeeAmount = feeAmount,
FeeAssetSymbol = deposit.FeeAssetSymbol,
// ? deposit.PaymentInfo.Amount.Currency
// : deposit.PaymentInfo.Fees.Currency,
Network = deposit.Network
};
}
else
{
existingEntity.Amount = amount;
existingEntity.UpdateDate = DateTime.UtcNow;
//existingEntity.FeeAmount = feeAmount;
existingEntity.FeeAssetSymbol = deposit.FeeAssetSymbol;
}
await ctx.UpsertAsync(existingEntity);
await _depositPublisher.PublishAsync(new Deposit(existingEntity));
}
catch (Exception)
{
_logger.LogError("Unable to update deposit entry");
throw;
}
_logger.LogInformation("Deposit request from Circle {transferIdString} is handled",
deposit.TransactionId);
}
}
} | 41.97479 | 114 | 0.611612 | [
"MIT"
] | MyJetWallet/Service.Bitgo.DepositDetector | src/Service.Bitgo.DepositDetector/Services/FireblocksDepositProcessingService.cs | 4,997 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Globalization;
using System.Linq;
using Microsoft.VisualStudio.TestPlatform.Client.RequestHelper;
using Microsoft.VisualStudio.TestPlatform.CommandLine.Internal;
using Microsoft.VisualStudio.TestPlatform.CommandLine.TestPlatformHelpers;
using Microsoft.VisualStudio.TestPlatform.Common;
using Microsoft.VisualStudio.TestPlatform.Common.Interfaces;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;
using Microsoft.VisualStudio.TestPlatform.Utilities;
using CommandLineResources = Microsoft.VisualStudio.TestPlatform.CommandLine.Resources.Resources;
namespace Microsoft.VisualStudio.TestPlatform.CommandLine.Processors;
/// <summary>
/// Argument Executor for the "-lt|--ListTests|/lt|/ListTests" command line argument.
/// </summary>
internal class ListTestsArgumentProcessor : IArgumentProcessor
{
/// <summary>
/// The short name of the command line argument that the ListTestsArgumentExecutor handles.
/// </summary>
public const string ShortCommandName = "/lt";
/// <summary>
/// The name of the command line argument that the ListTestsArgumentExecutor handles.
/// </summary>
public const string CommandName = "/ListTests";
private Lazy<IArgumentProcessorCapabilities>? _metadata;
private Lazy<IArgumentExecutor>? _executor;
/// <summary>
/// Gets the metadata.
/// </summary>
public Lazy<IArgumentProcessorCapabilities> Metadata
=> _metadata ??= new Lazy<IArgumentProcessorCapabilities>(() =>
new ListTestsArgumentProcessorCapabilities());
/// <summary>
/// Gets or sets the executor.
/// </summary>
public Lazy<IArgumentExecutor>? Executor
{
get => _executor ??= new Lazy<IArgumentExecutor>(() =>
new ListTestsArgumentExecutor(
CommandLineOptions.Instance,
RunSettingsManager.Instance,
TestRequestManager.Instance));
set => _executor = value;
}
}
internal class ListTestsArgumentProcessorCapabilities : BaseArgumentProcessorCapabilities
{
public override string CommandName => ListTestsArgumentProcessor.CommandName;
public override string ShortCommandName => ListTestsArgumentProcessor.ShortCommandName;
public override bool AllowMultiple => false;
public override bool IsAction => true;
public override ArgumentProcessorPriority Priority => ArgumentProcessorPriority.Normal;
public override string HelpContentResourceName => CommandLineResources.ListTestsHelp;
public override HelpContentPriority HelpPriority => HelpContentPriority.ListTestsArgumentProcessorHelpPriority;
}
/// <summary>
/// Argument Executor for the "/ListTests" command line argument.
/// </summary>
internal class ListTestsArgumentExecutor : IArgumentExecutor
{
/// <summary>
/// Used for getting sources.
/// </summary>
private readonly CommandLineOptions _commandLineOptions;
/// <summary>
/// Used for getting tests.
/// </summary>
private readonly ITestRequestManager _testRequestManager;
/// <summary>
/// Used for sending output.
/// </summary>
internal IOutput Output;
/// <summary>
/// RunSettingsManager to get currently active run settings.
/// </summary>
private readonly IRunSettingsProvider _runSettingsManager;
/// <summary>
/// Registers for discovery events during discovery
/// </summary>
private readonly ITestDiscoveryEventsRegistrar _discoveryEventsRegistrar;
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="options">
/// The options.
/// </param>
public ListTestsArgumentExecutor(
CommandLineOptions options,
IRunSettingsProvider runSettingsProvider,
ITestRequestManager testRequestManager) :
this(options, runSettingsProvider, testRequestManager, ConsoleOutput.Instance)
{
}
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="options">
/// The options.
/// </param>
internal ListTestsArgumentExecutor(
CommandLineOptions options,
IRunSettingsProvider runSettingsProvider,
ITestRequestManager testRequestManager,
IOutput output)
{
ValidateArg.NotNull(options, nameof(options));
_commandLineOptions = options;
Output = output;
_testRequestManager = testRequestManager;
_runSettingsManager = runSettingsProvider;
_discoveryEventsRegistrar = new DiscoveryEventsRegistrar(output);
}
#region IArgumentExecutor
/// <summary>
/// Initializes with the argument that was provided with the command.
/// </summary>
/// <param name="argument">Argument that was provided with the command.</param>
public void Initialize(string? argument)
{
if (!argument.IsNullOrWhiteSpace())
{
_commandLineOptions.AddSource(argument);
}
}
/// <summary>
/// Lists out the available discoverers.
/// </summary>
public ArgumentProcessorResult Execute()
{
TPDebug.Assert(Output != null);
TPDebug.Assert(_commandLineOptions != null);
TPDebug.Assert(!StringUtils.IsNullOrWhiteSpace(_runSettingsManager?.ActiveRunSettings?.SettingsXml));
if (!_commandLineOptions.Sources.Any())
{
throw new CommandLineException(string.Format(CultureInfo.CurrentUICulture, CommandLineResources.MissingTestSourceFile));
}
Output.WriteLine(CommandLineResources.ListTestsHeaderMessage, OutputLevel.Information);
if (!StringUtils.IsNullOrEmpty(EqtTrace.LogFile))
{
Output.Information(false, CommandLineResources.VstestDiagLogOutputPath, EqtTrace.LogFile);
}
var runSettings = _runSettingsManager.ActiveRunSettings.SettingsXml;
_testRequestManager.DiscoverTests(
new DiscoveryRequestPayload() { Sources = _commandLineOptions.Sources, RunSettings = runSettings },
_discoveryEventsRegistrar, Constants.DefaultProtocolConfig);
return ArgumentProcessorResult.Success;
}
#endregion
private class DiscoveryEventsRegistrar : ITestDiscoveryEventsRegistrar
{
private readonly IOutput _output;
public DiscoveryEventsRegistrar(IOutput output)
{
_output = output;
}
public void LogWarning(string message)
{
ConsoleLogger.RaiseTestRunWarning(message);
}
public void RegisterDiscoveryEvents(IDiscoveryRequest discoveryRequest)
{
discoveryRequest.OnDiscoveredTests += DiscoveryRequest_OnDiscoveredTests;
}
public void UnregisterDiscoveryEvents(IDiscoveryRequest discoveryRequest)
{
discoveryRequest.OnDiscoveredTests -= DiscoveryRequest_OnDiscoveredTests;
}
private void DiscoveryRequest_OnDiscoveredTests(Object sender, DiscoveredTestsEventArgs args)
{
// List out each of the tests.
foreach (var test in args.DiscoveredTestCases)
{
_output.WriteLine(string.Format(CultureInfo.CurrentUICulture,
CommandLineResources.AvailableTestsFormat,
test.DisplayName),
OutputLevel.Information);
}
}
}
}
| 33.610619 | 132 | 0.697736 | [
"MIT"
] | Microsoft/vstest | src/vstest.console/Processors/ListTestsArgumentProcessor.cs | 7,596 | C# |
using System;
using System.Drawing;
using Microsoft.VisualStudio.Modeling.Diagrams;
namespace NuPattern.Authoring.WorkflowDesign
{
/// <summary>
/// Customized shape for a Supplied Asset.
/// </summary>
partial class SuppliedAssetShapeBase
{
/// <summary>
/// Returns the value of the StereotypeText property.
/// </summary>
internal string GetStereotypeTextValue()
{
SuppliedAsset asset = this.Subject as SuppliedAsset;
if (asset != null)
{
if (asset.IsUserSupplied)
{
return this.IsUserSuppliedStereotypeText;
}
else
{
return this.IsMaterialStereotypeText;
}
}
return string.Empty;
}
}
/// <summary>
/// Customized shape for a Supplied Asset.
/// </summary>
partial class SuppliedAssetShape : SuppliedAssetShapeBase, IDisposable
{
private RightSideArrowShapeGeometry geometry = new RightSideArrowShapeGeometry();
/// <summary>
/// Finalizes an instance of the <see cref="SuppliedAssetShape"/> class.
/// </summary>
~SuppliedAssetShape()
{
this.Dispose(false);
}
/// <summary>
/// Returns the geometry for the shape.
/// </summary>
public override ShapeGeometry ShapeGeometry
{
get
{
return this.geometry;
}
}
/// <summary>
/// Gets the sides of the node shape which can be resized by the user.
/// Default behavior is that all sides may be resized.
/// </summary>
public override NodeSides ResizableSides
{
get
{
return NodeSides.All;
}
}
/// <summary>
/// Constrain width of shape to maintain shape integrity.
/// </summary>
public override SizeD MinimumResizableSize
{
get
{
// Fix width/height constraints
return (new SizeD(1.5d, 0.6d));
}
}
/// <summary>
/// Gets whether the shape has custom connection points.
/// </summary>
public override bool HasConnectionPoints
{
get
{
return true;
}
}
/// <summary>
/// Defines the connection points for the shape.
/// </summary>
public override void EnsureConnectionPoints(LinkShape link)
{
PointD[] connectionPoints = this.geometry.GetGeometryConnectionPoints(this);
if (connectionPoints != null)
{
foreach (PointD connectionPoint in connectionPoints)
{
this.CreateConnectionPoint(connectionPoint);
}
}
else
{
base.EnsureConnectionPoints(link);
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Returns the color of the current stereotype.
/// </summary>
internal Color GetStereotypeFillColor()
{
SuppliedAsset asset = this.Subject as SuppliedAsset;
if (asset != null)
{
if (asset.IsUserSupplied)
{
return this.IsUserSuppliedColor;
}
else
{
return this.IsMaterialColor;
}
}
return Color.Empty;
}
/// <summary>
/// Disposes instances.
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (this.geometry != null)
{
this.geometry.Dispose();
}
}
}
}
} | 27.170886 | 116 | 0.485208 | [
"Apache-2.0"
] | dbremner/nupattern | Src/Authoring/Source/Authoring.WorkflowDesign/Diagram/Shapes/SuppliedAssetShape.cs | 4,295 | C# |
using System;
using System.Threading;
using System.ComponentModel;
using Gdk;
using OpenTK.Graphics;
using Gtk;
namespace OpenTK
{
/// <summary>
/// The <see cref="GLWidget"/> is a GTK widget for which an OpenGL context can be used to draw arbitrary graphics.
/// </summary>
[CLSCompliant(false)]
[ToolboxItem(true)]
public class GLWidget : GLArea
{
private static int _GraphicsContextCount;
private static bool _SharedContextInitialized = false;
private IGraphicsContext _GraphicsContext;
private bool _Initialized = false;
/// <summary>
/// The previous frame time reported by GTK.
/// </summary>
private double? _PreviousFrameTime;
/// <summary>
/// Gets the time taken to render the last frame (in seconds).
/// </summary>
public double DeltaTime { get; private set; }
/// <summary>
/// The set <see cref="ContextFlags"/> for this widget.
/// </summary>
public GraphicsContextFlags ContextFlags { get; }
/// <summary>
/// Initializes a new instance of the <see cref="GLWidget"/> class.
/// </summary>
public GLWidget()
: this(GraphicsMode.Default)
{
}
/// <summary>Constructs a new GLWidget using a given GraphicsMode</summary>
public GLWidget(GraphicsMode graphicsMode)
: this(graphicsMode, 1, 0, GraphicsContextFlags.Default)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="GLWidget"/> class.
/// </summary>
/// <param name="graphicsMode">The <see cref="GraphicsMode"/> which the widget should be constructed with.</param>
/// <param name="glVersionMajor">The major OpenGL version to attempt to initialize.</param>
/// <param name="glVersionMinor">The minor OpenGL version to attempt to initialize.</param>
/// <param name="contextFlags">
/// Any flags which should be used during initialization of the <see cref="GraphicsContext"/>.
/// </param>
public GLWidget(GraphicsMode graphicsMode, int glVersionMajor, int glVersionMinor, GraphicsContextFlags contextFlags)
{
ContextFlags = contextFlags;
AddTickCallback(UpdateFrameTime);
SetRequiredVersion(glVersionMajor, glVersionMinor);
if (graphicsMode.Depth > 0)
{
HasDepthBuffer = true;
}
if (graphicsMode.Stencil > 0)
{
HasStencilBuffer = true;
}
if (graphicsMode.ColorFormat.Alpha > 0)
{
HasAlpha = true;
}
}
/// <summary>
/// Updates the time delta with a new value from the last frame.
/// </summary>
/// <param name="widget">The sending widget.</param>
/// <param name="frameClock">The relevant frame clock.</param>
/// <returns>true if the callback should be called again; otherwise, false.</returns>
private bool UpdateFrameTime(Widget widget, FrameClock frameClock)
{
var frameTimeµSeconds = frameClock.FrameTime;
if (!_PreviousFrameTime.HasValue)
{
_PreviousFrameTime = frameTimeµSeconds;
return true;
}
var frameTimeSeconds = (frameTimeµSeconds - _PreviousFrameTime) / 10e6;
DeltaTime = (float)frameTimeSeconds;
_PreviousFrameTime = frameTimeµSeconds;
return true;
}
/// <inheritdoc />
protected override GLContext OnCreateContext()
{
var gdkGLContext = Window.CreateGlContext();
GetRequiredVersion(out var major, out var minor);
gdkGLContext.SetRequiredVersion(major, minor);
gdkGLContext.DebugEnabled = ContextFlags.HasFlag(GraphicsContextFlags.Debug);
gdkGLContext.ForwardCompatible = ContextFlags.HasFlag(GraphicsContextFlags.ForwardCompatible);
gdkGLContext.Realize();
return gdkGLContext;
}
/// <summary>
/// Destructs this object.
/// </summary>
~GLWidget()
{
Dispose(false);
}
/// <summary>
/// Destroys this <see cref="Widget"/>, disposing it and destroying it in the context of GTK.
/// </summary>
public override void Destroy()
{
GC.SuppressFinalize(this);
Dispose(true);
base.Destroy();
}
/// <summary>
/// Disposes the current object, releasing any native resources it was using.
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
MakeCurrent();
OnShuttingDown();
if (GraphicsContext.ShareContexts && (Interlocked.Decrement(ref _GraphicsContextCount) == 0))
{
OnGraphicsContextShuttingDown();
_SharedContextInitialized = false;
}
_GraphicsContext.Dispose();
}
}
/// <summary>
/// Called when the first <see cref="GraphicsContext"/> is created in the case where
/// GraphicsContext.ShareContexts == true;
/// </summary>
public static event EventHandler GraphicsContextInitialized;
/// <summary>
/// Invokes the <see cref="GraphicsContextInitialized"/> event.
/// </summary>
private static void OnGraphicsContextInitialized()
{
if (GraphicsContextInitialized != null)
{
GraphicsContextInitialized(null, EventArgs.Empty);
}
}
/// <summary>
/// Called when the first <see cref="GraphicsContext"/> is being destroyed in the case where
/// GraphicsContext.ShareContext == true;
/// </summary>
public static event EventHandler GraphicsContextShuttingDown;
/// <summary>
/// Invokes the <see cref="GraphicsContextShuttingDown"/> event.
/// </summary>
private static void OnGraphicsContextShuttingDown()
{
if (GraphicsContextShuttingDown != null)
{
GraphicsContextShuttingDown(null, EventArgs.Empty);
}
}
/// <summary>
/// Called when this <see cref="GLWidget"/> has finished initializing and has a valid
/// <see cref="GraphicsContext"/>.
/// </summary>
public event EventHandler Initialized;
/// <summary>
/// Invokes the <see cref="Initialized"/> event.
/// </summary>
protected virtual void OnInitialized()
{
if (Initialized != null)
{
Initialized(this, EventArgs.Empty);
}
}
/// <summary>
/// Called when this <see cref="GLWidget"/> is being disposed.
/// </summary>
public event EventHandler ShuttingDown;
/// <summary>
/// Invokes the <see cref="ShuttingDown"/> event.
/// </summary>
protected virtual void OnShuttingDown()
{
if (ShuttingDown != null)
{
ShuttingDown(this, EventArgs.Empty);
}
}
/// <summary>
/// Called when the widget needs to be (fully or partially) redrawn.
/// </summary>
/// <param name="cr"></param>
/// <returns></returns>
protected override bool OnDrawn(Cairo.Context cr)
{
if (!_Initialized)
{
Initialize();
}
var result = base.OnDrawn(cr);
return result;
}
/// <summary>
/// Initializes the <see cref="GLWidget"/> with its given values and creates a <see cref="GraphicsContext"/>.
/// </summary>
private void Initialize()
{
_Initialized = true;
// Make the GDK GL context current
MakeCurrent();
// Create a dummy context that will grab the GdkGLContext that is current on the thread
_GraphicsContext = new GraphicsContext(ContextHandle.Zero, null);
if (ContextFlags.HasFlag(GraphicsContextFlags.Debug))
{
_GraphicsContext.ErrorChecking = true;
}
if (GraphicsContext.ShareContexts)
{
Interlocked.Increment(ref _GraphicsContextCount);
if (!_SharedContextInitialized)
{
_SharedContextInitialized = true;
((IGraphicsContextInternal)_GraphicsContext).LoadAll();
OnGraphicsContextInitialized();
}
}
else
{
((IGraphicsContextInternal)_GraphicsContext).LoadAll();
OnGraphicsContextInitialized();
}
OnInitialized();
}
}
}
| 32.207018 | 125 | 0.553982 | [
"BSD-3-Clause"
] | AdamsLair/opentk | src/OpenTK.GLWidget/GLWidget.cs | 9,185 | C# |
using System;
using Newtonsoft.Json.Linq;
namespace COLID.Graph.Metadata.Extensions
{
public static class DynamicExtension
{
public static bool IsType<TResult>(dynamic value, out TResult result)
{
if (value is TResult)
{
result = value;
return true;
}
else if (value is JObject)
{
JObject jObject = value;
try
{
result = jObject.ToObject<TResult>();
return true;
}
catch (System.Exception ex)
{
Console.WriteLine(ex);
}
}
result = default;
return false;
}
}
}
| 22.857143 | 77 | 0.4275 | [
"BSD-3-Clause"
] | Bayer-Group/COLID-Registration-Service | libs/COLID.Graph/Metadata/Extensions/DynamicExtension.cs | 802 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using NuGet.Common;
using NuGet.DependencyResolver;
using NuGet.Frameworks;
using NuGet.LibraryModel;
using NuGet.Packaging;
using NuGet.ProjectModel;
using NuGet.Repositories;
using NuGet.Shared;
using NuGetVersion = NuGet.Versioning.NuGetVersion;
namespace NuGet.Commands
{
public class LockFileBuilder
{
private readonly int _lockFileVersion;
private readonly ILogger _logger;
private readonly Dictionary<RestoreTargetGraph, Dictionary<string, LibraryIncludeFlags>> _includeFlagGraphs;
public LockFileBuilder(int lockFileVersion,
ILogger logger,
Dictionary<RestoreTargetGraph,
Dictionary<string, LibraryIncludeFlags>> includeFlagGraphs)
{
_lockFileVersion = lockFileVersion;
_logger = logger;
_includeFlagGraphs = includeFlagGraphs;
}
[Obsolete("Use method with LockFileBuilderCache parameter")]
public LockFile CreateLockFile(LockFile previousLockFile,
PackageSpec project,
IEnumerable<RestoreTargetGraph> targetGraphs,
IReadOnlyList<NuGetv3LocalRepository> localRepositories,
RemoteWalkContext context)
{
return CreateLockFile(previousLockFile,
project,
targetGraphs,
localRepositories,
context,
new LockFileBuilderCache());
}
public LockFile CreateLockFile(LockFile previousLockFile,
PackageSpec project,
IEnumerable<RestoreTargetGraph> targetGraphs,
IReadOnlyList<NuGetv3LocalRepository> localRepositories,
RemoteWalkContext context,
LockFileBuilderCache lockFileBuilderCache)
{
var lockFile = new LockFile()
{
Version = _lockFileVersion
};
var previousLibraries = previousLockFile?.Libraries.ToDictionary(l => Tuple.Create(l.Name, l.Version));
if (project.RestoreMetadata?.ProjectStyle == ProjectStyle.PackageReference ||
project.RestoreMetadata?.ProjectStyle == ProjectStyle.DotnetToolReference)
{
AddProjectFileDependenciesForPackageReference(project, lockFile, targetGraphs);
}
else
{
AddProjectFileDependenciesForSpec(project, lockFile);
}
// Record all libraries used
var libraryItems = targetGraphs
.SelectMany(g => g.Flattened) // All GraphItem<RemoteResolveResult> resolved in the graph.
.Distinct(GraphItemKeyComparer<RemoteResolveResult>.Instance) // Distinct list of GraphItems. Two items are equal only if the itmes' Keys are equal.
.OrderBy(x => x.Data.Match.Library);
foreach (var item in libraryItems)
{
var library = item.Data.Match.Library;
if (project.Name.Equals(library.Name, StringComparison.OrdinalIgnoreCase))
{
// Do not include the project itself as a library.
continue;
}
if (library.Type == LibraryType.Project || library.Type == LibraryType.ExternalProject)
{
// Project
var localMatch = (LocalMatch)item.Data.Match;
var projectLib = new LockFileLibrary()
{
Name = library.Name,
Version = library.Version,
Type = LibraryType.Project,
};
// Set the relative path if a path exists
// For projects without project.json this will be empty
if (!string.IsNullOrEmpty(localMatch.LocalLibrary.Path))
{
projectLib.Path = PathUtility.GetRelativePath(
project.FilePath,
localMatch.LocalLibrary.Path,
'/');
}
// The msbuild project path if it exists
object msbuildPath;
if (localMatch.LocalLibrary.Items.TryGetValue(KnownLibraryProperties.MSBuildProjectPath, out msbuildPath))
{
var msbuildRelativePath = PathUtility.GetRelativePath(
project.FilePath,
(string)msbuildPath,
'/');
projectLib.MSBuildProject = msbuildRelativePath;
}
lockFile.Libraries.Add(projectLib);
}
else if (library.Type == LibraryType.Package)
{
// Packages
var packageInfo = NuGetv3LocalRepositoryUtility.GetPackage(localRepositories, library.Name, library.Version);
// Add the library if it was resolved, unresolved packages are not added to the assets file.
if (packageInfo != null)
{
var package = packageInfo.Package;
var resolver = packageInfo.Repository.PathResolver;
var sha512 = package.Sha512;
var path = PathUtility.GetPathWithForwardSlashes(resolver.GetPackageDirectory(package.Id, package.Version));
LockFileLibrary lockFileLib = null;
LockFileLibrary previousLibrary = null;
if (previousLibraries?.TryGetValue(Tuple.Create(package.Id, package.Version), out previousLibrary) == true)
{
// Check that the previous library is still valid
if (previousLibrary != null
&& StringComparer.Ordinal.Equals(path, previousLibrary.Path)
&& StringComparer.Ordinal.Equals(sha512, previousLibrary.Sha512))
{
// We mutate this previous library so we must take a clone of it. This is
// important because later, when deciding whether the lock file has changed,
// we compare the new lock file to the previous (in-memory) lock file.
lockFileLib = previousLibrary.Clone();
}
}
// Create a new lock file library if one doesn't exist already.
if (lockFileLib == null)
{
lockFileLib = CreateLockFileLibrary(package, sha512, path);
}
// Create a new lock file library
lockFile.Libraries.Add(lockFileLib);
}
}
}
Dictionary<Tuple<string, NuGetVersion>, LockFileLibrary> libraries = EnsureUniqueLockFileLibraries(lockFile);
var librariesWithWarnings = new HashSet<LibraryIdentity>();
var rootProjectStyle = project.RestoreMetadata?.ProjectStyle ?? ProjectStyle.Unknown;
// Add the targets
foreach (var targetGraph in targetGraphs
.OrderBy(graph => graph.Framework.ToString(), StringComparer.Ordinal)
.ThenBy(graph => graph.RuntimeIdentifier, StringComparer.Ordinal))
{
var target = new LockFileTarget
{
TargetFramework = targetGraph.Framework,
RuntimeIdentifier = targetGraph.RuntimeIdentifier
};
var flattenedFlags = IncludeFlagUtils.FlattenDependencyTypes(_includeFlagGraphs, project, targetGraph);
// Check if warnings should be displayed for the current framework.
var tfi = project.GetTargetFramework(targetGraph.Framework);
bool warnForImportsOnGraph = tfi.Warn
&& (target.TargetFramework is FallbackFramework
|| target.TargetFramework is AssetTargetFallbackFramework);
foreach (var graphItem in targetGraph.Flattened.OrderBy(x => x.Key))
{
var library = graphItem.Key;
// include flags
LibraryIncludeFlags includeFlags;
if (!flattenedFlags.TryGetValue(library.Name, out includeFlags))
{
includeFlags = ~LibraryIncludeFlags.ContentFiles;
}
if (library.Type == LibraryType.Project || library.Type == LibraryType.ExternalProject)
{
if (project.Name.Equals(library.Name, StringComparison.OrdinalIgnoreCase))
{
// Do not include the project itself as a library.
continue;
}
var projectLib = LockFileUtils.CreateLockFileTargetProject(
graphItem,
library,
includeFlags,
targetGraph,
rootProjectStyle);
target.Libraries.Add(projectLib);
}
else if (library.Type == LibraryType.Package)
{
var packageInfo = NuGetv3LocalRepositoryUtility.GetPackage(localRepositories, library.Name, library.Version);
if (packageInfo == null)
{
continue;
}
var package = packageInfo.Package;
var libraryDependency = tfi.Dependencies.FirstOrDefault(e => e.Name.Equals(library.Name, StringComparison.OrdinalIgnoreCase));
var targetLibrary = LockFileUtils.CreateLockFileTargetLibrary(
libraryDependency?.Aliases,
libraries[Tuple.Create(library.Name, library.Version)],
package,
targetGraph,
dependencyType: includeFlags,
targetFrameworkOverride: null,
dependencies: graphItem.Data.Dependencies,
cache: lockFileBuilderCache);
target.Libraries.Add(targetLibrary);
// Log warnings if the target library used the fallback framework
if (warnForImportsOnGraph && !librariesWithWarnings.Contains(library))
{
var nonFallbackFramework = new NuGetFramework(target.TargetFramework);
var targetLibraryWithoutFallback = LockFileUtils.CreateLockFileTargetLibrary(
libraryDependency?.Aliases,
libraries[Tuple.Create(library.Name, library.Version)],
package,
targetGraph,
targetFrameworkOverride: nonFallbackFramework,
dependencyType: includeFlags,
dependencies: graphItem.Data.Dependencies,
cache: lockFileBuilderCache);
if (!targetLibrary.Equals(targetLibraryWithoutFallback))
{
var libraryName = DiagnosticUtility.FormatIdentity(library);
var message = string.Format(CultureInfo.CurrentCulture,
Strings.Log_ImportsFallbackWarning,
libraryName,
GetFallbackFrameworkString(target.TargetFramework),
nonFallbackFramework);
var logMessage = RestoreLogMessage.CreateWarning(
NuGetLogCode.NU1701,
message,
library.Name,
targetGraph.TargetGraphName);
_logger.Log(logMessage);
// only log the warning once per library
librariesWithWarnings.Add(library);
}
}
}
}
EnsureUniqueLockFileTargetLibraries(target);
lockFile.Targets.Add(target);
}
PopulatePackageFolders(localRepositories.Select(repo => repo.RepositoryRoot).Distinct(), lockFile);
AddCentralTransitiveDependencyGroupsForPackageReference(project, lockFile, targetGraphs);
// Add the original package spec to the lock file.
lockFile.PackageSpec = project;
return lockFile;
}
private Dictionary<Tuple<string, NuGetVersion>, LockFileLibrary> EnsureUniqueLockFileLibraries(LockFile lockFile)
{
IList<LockFileLibrary> libraries = lockFile.Libraries;
var libraryReferences = new Dictionary<Tuple<string, NuGetVersion>, LockFileLibrary>();
foreach (LockFileLibrary lib in libraries)
{
var libraryKey = Tuple.Create(lib.Name, lib.Version);
if (libraryReferences.TryGetValue(libraryKey, out LockFileLibrary existingLibrary))
{
if (RankReferences(existingLibrary.Type) > RankReferences(lib.Type))
{
// Prefer project reference over package reference, so replace the the package reference.
libraryReferences[libraryKey] = lib;
}
}
else
{
libraryReferences[libraryKey] = lib;
}
}
if (lockFile.Libraries.Count != libraryReferences.Count)
{
lockFile.Libraries = new List<LockFileLibrary>(libraryReferences.Count);
foreach (KeyValuePair<Tuple<string, NuGetVersion>, LockFileLibrary> pair in libraryReferences)
{
lockFile.Libraries.Add(pair.Value);
}
}
return libraryReferences;
}
private static void EnsureUniqueLockFileTargetLibraries(LockFileTarget lockFileTarget)
{
IList<LockFileTargetLibrary> libraries = lockFileTarget.Libraries;
var libraryReferences = new Dictionary<LockFileTargetLibrary, LockFileTargetLibrary>(comparer: LockFileTargetLibraryNameAndVersionEqualityComparer.Instance);
foreach (LockFileTargetLibrary library in libraries)
{
if (libraryReferences.TryGetValue(library, out LockFileTargetLibrary existingLibrary))
{
if (RankReferences(existingLibrary.Type) > RankReferences(library.Type))
{
// Prefer project reference over package reference, so replace the the package reference.
libraryReferences[library] = library;
}
}
else
{
libraryReferences[library] = library;
}
}
if (lockFileTarget.Libraries.Count == libraryReferences.Count)
{
return;
}
lockFileTarget.Libraries = new List<LockFileTargetLibrary>(libraryReferences.Count);
foreach (KeyValuePair<LockFileTargetLibrary, LockFileTargetLibrary> pair in libraryReferences)
{
lockFileTarget.Libraries.Add(pair.Value);
}
}
/// <summary>
/// Prefer projects over packages
/// </summary>
/// <param name="referenceType"></param>
/// <returns></returns>
private static int RankReferences(string referenceType)
{
if (referenceType == "project")
{
return 0;
}
else if (referenceType == "externalProject")
{
return 1;
}
else if (referenceType == "package")
{
return 2;
}
return 5;
}
private static string GetFallbackFrameworkString(NuGetFramework framework)
{
var frameworks = (framework as AssetTargetFallbackFramework)?.Fallback
?? (framework as FallbackFramework)?.Fallback
?? new List<NuGetFramework>();
return string.Join(", ", frameworks);
}
private static void AddProjectFileDependenciesForSpec(PackageSpec project, LockFile lockFile)
{
// Use empty string as the key of dependencies shared by all frameworks
lockFile.ProjectFileDependencyGroups.Add(new ProjectFileDependencyGroup(
string.Empty,
project.Dependencies
.Select(group => group.LibraryRange.ToLockFileDependencyGroupString())
.OrderBy(group => group, StringComparer.Ordinal)));
foreach (var frameworkInfo in project.TargetFrameworks
.OrderBy(framework => framework.FrameworkName.ToString(),
StringComparer.Ordinal))
{
lockFile.ProjectFileDependencyGroups.Add(new ProjectFileDependencyGroup(
frameworkInfo.FrameworkName.ToString(),
frameworkInfo.Dependencies
.Select(x => x.LibraryRange.ToLockFileDependencyGroupString())
.OrderBy(dependency => dependency, StringComparer.Ordinal)));
}
}
private static void AddProjectFileDependenciesForPackageReference(PackageSpec project, LockFile lockFile, IEnumerable<RestoreTargetGraph> targetGraphs)
{
// For NETCore put everything under a TFM section
// Projects are included for NETCore
foreach (var frameworkInfo in project.TargetFrameworks
.OrderBy(framework => framework.FrameworkName.ToString(),
StringComparer.Ordinal))
{
var dependencies = new List<LibraryRange>();
dependencies.AddRange(project.Dependencies.Select(e => e.LibraryRange));
dependencies.AddRange(frameworkInfo.Dependencies.Select(e => e.LibraryRange));
var targetGraph = targetGraphs.SingleOrDefault(graph =>
graph.Framework.Equals(frameworkInfo.FrameworkName)
&& string.IsNullOrEmpty(graph.RuntimeIdentifier));
var resolvedEntry = targetGraph?
.Flattened
.SingleOrDefault(library => library.Key.Name.Equals(project.Name, StringComparison.OrdinalIgnoreCase));
// In some failure cases where there is a conflict the root level project cannot be resolved, this should be handled gracefully
if (resolvedEntry != null)
{
dependencies.AddRange(resolvedEntry.Data.Dependencies.Where(lib =>
lib.LibraryRange.TypeConstraint == LibraryDependencyTarget.ExternalProject)
.Select(lib => lib.LibraryRange));
}
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var uniqueDependencies = new List<LibraryRange>();
foreach (var dependency in dependencies)
{
if (seen.Add(dependency.Name))
{
uniqueDependencies.Add(dependency);
}
}
// Add entry
var dependencyGroup = new ProjectFileDependencyGroup(
frameworkInfo.FrameworkName.ToString(),
uniqueDependencies.Select(x => x.ToLockFileDependencyGroupString())
.OrderBy(dependency => dependency, StringComparer.Ordinal));
lockFile.ProjectFileDependencyGroups.Add(dependencyGroup);
}
}
private void AddCentralTransitiveDependencyGroupsForPackageReference(PackageSpec project, LockFile lockFile, IEnumerable<RestoreTargetGraph> targetGraphs)
{
if (project.RestoreMetadata?.CentralPackageVersionsEnabled == false)
{
return;
}
// Do not pack anything from the runtime graphs
// The runtime graphs are added in addition to the graphs without a runtime
foreach (var targetGraph in targetGraphs.Where(targetGraph => string.IsNullOrEmpty(targetGraph.RuntimeIdentifier)))
{
var centralPackageVersionsForFramework = project.TargetFrameworks.Where(tfmi => tfmi.FrameworkName.Equals(targetGraph.Framework)).FirstOrDefault()?.CentralPackageVersions;
// The transitive dependencies enforced by the central package version management file are written to the assets to be used by the pack task.
IEnumerable<LibraryDependency> centralEnforcedTransitiveDependencies = targetGraph
.Flattened
.Where(graphItem => graphItem.IsCentralTransitive && centralPackageVersionsForFramework?.ContainsKey(graphItem.Key.Name) == true)
.Select((graphItem) =>
{
CentralPackageVersion matchingCentralVersion = centralPackageVersionsForFramework[graphItem.Key.Name];
Dictionary<string, LibraryIncludeFlags> dependenciesIncludeFlags = _includeFlagGraphs[targetGraph];
var libraryDependency = new LibraryDependency()
{
LibraryRange = new LibraryRange(matchingCentralVersion.Name, matchingCentralVersion.VersionRange, LibraryDependencyTarget.Package),
ReferenceType = LibraryDependencyReferenceType.Transitive,
VersionCentrallyManaged = true,
IncludeType = dependenciesIncludeFlags[matchingCentralVersion.Name]
};
return libraryDependency;
});
if (centralEnforcedTransitiveDependencies.Any())
{
var centralEnforcedTransitiveDependencyGroup = new CentralTransitiveDependencyGroup
(
targetGraph.Framework,
centralEnforcedTransitiveDependencies
);
lockFile.CentralTransitiveDependencyGroups.Add(centralEnforcedTransitiveDependencyGroup);
}
}
}
private static void PopulatePackageFolders(IEnumerable<string> packageFolders, LockFile lockFile)
{
lockFile.PackageFolders.AddRange(packageFolders.Select(path => new LockFileItem(path)));
}
private static LockFileLibrary CreateLockFileLibrary(LocalPackageInfo package, string sha512, string path)
{
var lockFileLib = new LockFileLibrary
{
Name = package.Id,
Version = package.Version,
Type = LibraryType.Package,
Sha512 = sha512,
// This is the relative path, appended to the global packages folder path. All
// of the paths in the in the Files property should be appended to this path along
// with the global packages folder path to get the absolute path to each file in the
// package.
Path = path
};
foreach (var file in package.Files)
{
if (!lockFileLib.HasTools && HasTools(file))
{
lockFileLib.HasTools = true;
}
lockFileLib.Files.Add(file);
}
return lockFileLib;
}
private static bool HasTools(string file)
{
return file.StartsWith("tools/", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// An <see cref="IEqualityComparer{T}" /> that compares <see cref="LockFileTargetLibrary" /> objects by the value of the <see cref="LockFileTargetLibrary.Name" /> and <see cref="LockFileTargetLibrary.Version" /> properties.
/// </summary>
private class LockFileTargetLibraryNameAndVersionEqualityComparer : IEqualityComparer<LockFileTargetLibrary>
{
/// <summary>
/// Gets a static singleton for the <see cref="LockFileTargetLibraryNameAndVersionEqualityComparer" /> class.
/// </summary>
public static LockFileTargetLibraryNameAndVersionEqualityComparer Instance = new();
/// <summary>
/// Initializes a new instance of the <see cref="LockFileTargetLibraryNameAndVersionEqualityComparer" /> class.
/// </summary>
private LockFileTargetLibraryNameAndVersionEqualityComparer()
{
}
/// <summary>
/// Determines whether the specified <see cref="LockFileTargetLibrary" /> objects are equal by comparing their <see cref="LockFileTargetLibrary.Name" /> and <see cref="LockFileTargetLibrary.Version" /> properties.
/// </summary>
/// <param name="x">The first <see cref="LockFileTargetLibrary" /> to compare.</param>
/// <param name="y">The second <see cref="LockFileTargetLibrary" /> to compare.</param>
/// <returns><c>true</c> if the specified <see cref="LockFileTargetLibrary" /> objects' <see cref="LockFileTargetLibrary.Name" /> and <see cref="LockFileTargetLibrary.Version" /> properties are equal, otherwise <c>false</c>.</returns>
public bool Equals(LockFileTargetLibrary x, LockFileTargetLibrary y)
{
return string.Equals(x.Name, y.Name, StringComparison.Ordinal) && x.Version.Equals(y.Version);
}
/// <summary>
/// Returns a hash code for the specified <see cref="LockFileTargetLibrary" /> object's <see cref="LockFileTargetLibrary.Name" /> property.
/// </summary>
/// <param name="obj">The <see cref="LockFileTargetLibrary" /> for which a hash code is to be returned.</param>
/// <returns>A hash code for the specified <see cref="LockFileTargetLibrary" /> object's <see cref="LockFileTargetLibrary.Name" /> and and <see cref="LockFileTargetLibrary.Version" /> properties.</returns>
public int GetHashCode(LockFileTargetLibrary obj)
{
var combiner = new HashCodeCombiner();
combiner.AddObject(obj.Name);
combiner.AddObject(obj.Version);
return combiner.CombinedHash;
}
}
}
}
| 46.350584 | 246 | 0.557557 | [
"Apache-2.0"
] | MarkKharitonov/NuGet.Client | src/NuGet.Core/NuGet.Commands/RestoreCommand/LockFileBuilder.cs | 27,764 | C# |
using System.Collections.Generic;
using System.Linq;
namespace GradeBook.Models
{
public class Student
{
public Student()
{
this.CoursesGrades = new Dictionary<string, double>();
}
public string FullName { get; set; }
public Dictionary<string, double> CoursesGrades { get; }
public override string ToString()
{
return this.FullName;
}
public void AddGrade(string courseName, double grade)
{
if (this.CoursesGrades.ContainsKey(courseName))
{
this.CoursesGrades[courseName] = grade;
}
else
{
this.CoursesGrades.Add(courseName, grade);
}
}
public double GetAverageGrade()
{
if (this.CoursesGrades.Count == 0)
{
return 0;
}
return this.CoursesGrades.Average(k => k.Value);
}
}
} | 21.73913 | 66 | 0.509 | [
"MIT"
] | KostaDinkov/unibit-programming-practice | GradeBook/Models/Student.cs | 1,002 | C# |
namespace DFC.App.CareerPath.FunctionalTests.Model.ContentType.JobProfile
{
public class EntryRequirement
{
public string Id { get; set; }
public string Title { get; set; }
public string Info { get; set; }
}
}
| 20.75 | 74 | 0.634538 | [
"MIT"
] | SkillsFundingAgency/dfc-app-careerpath | DFC.App.CareerPath.FunctionalTests/Model/ContentType/JobProfile/EntryRequirement.cs | 251 | C# |
using System;
using System.Globalization;
using System.Reflection;
using Eto.Forms;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
namespace Eto.Serialization.Json.Converters
{
public class DynamicLayoutConverter : JsonConverter
{
public override bool CanWrite
{
get { return false; }
}
public override bool CanConvert(Type objectType)
{
return typeof(DynamicItem).IsAssignableFrom(objectType) || typeof(DynamicRow).IsAssignableFrom(objectType);
}
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
object instance;
JContainer container;
if (reader.TokenType == JsonToken.Null)
{
return null;
}
if (reader.TokenType == JsonToken.String)
{
if (objectType == typeof(DynamicItem))
return new DynamicControl { Control = Convert.ToString(reader.Value) };
if (objectType == typeof(TableCell))
return new DynamicRow(new DynamicControl { Control = Convert.ToString(reader.Value) });
}
if (reader.TokenType == JsonToken.StartArray)
{
container = JArray.Load(reader);
if (objectType == typeof(DynamicRow))
{
var dynamicRow = new DynamicRow();
instance = dynamicRow;
serializer.Populate(container.CreateReader(), dynamicRow);
}
else if (objectType == typeof(DynamicItem))
{
var dynamicTable = new DynamicTable();
instance = dynamicTable;
serializer.Populate(container.CreateReader(), dynamicTable.Rows);
}
else
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid object graph"));
}
else
{
container = JObject.Load(reader);
if (container["$type"] == null)
{
if (container["Rows"] != null)
instance = new DynamicTable();
else if (container["Control"] != null)
instance = new DynamicControl();
else
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Could not infer the type of object to create"));
serializer.Populate(container.CreateReader(), instance);
}
else
{
var type = Type.GetType((string)container["$type"]);
if (!typeof(DynamicItem).IsAssignableFrom(type))
{
var dynamicControl = new DynamicControl();
dynamicControl.Control = serializer.Deserialize(container.CreateReader()) as Control;
instance = dynamicControl;
}
else
{
instance = serializer.Deserialize(container.CreateReader());
}
}
}
if (objectType == typeof(DynamicRow) && instance.GetType() != typeof(DynamicRow))
{
var row = new DynamicRow();
row.Add(instance as DynamicItem);
return row;
}
return instance;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
}
| 28.326733 | 134 | 0.686473 | [
"BSD-3-Clause"
] | 745564106/Eto | src/Eto.Serialization.Json/Converters/DynamicLayoutConverter.cs | 2,861 | C# |
using System;
using CocosSharp;
using CoinTimeGame.ContentRuntime.Animations;
using System.Collections.Generic;
using CoinTimeGame.Entities.Data;
using System.Linq;
namespace CoinTimeGame.Entities
{
public enum LeftOrRight
{
Left,
Right
}
public class Player : PhysicsEntity
{
Animation walkLeftAnimation;
Animation walkRightAnimation;
public bool IsOnGround
{
get;
private set;
}
public Player ()
{
LoadAnimations ("Content/animations/playeranimations.achx");
walkLeftAnimation = animations.Find (item => item.Name == "WalkLeft");
walkRightAnimation = animations.Find (item => item.Name == "WalkRight");
CurrentAnimation = walkLeftAnimation;
}
public void PerformActivity(float seconds)
{
ApplyMovementValues (seconds);
AssignAnimation ();
this.VelocityY = System.Math.Max (this.VelocityY, PlayerMovementCoefficients.MaxFallingSpeed);
}
private void AssignAnimation()
{
if (VelocityX > 0)
{
CurrentAnimation = walkRightAnimation;
}
else if (VelocityX < 0)
{
CurrentAnimation = walkLeftAnimation;
}
// if 0 do nothing
}
public void ApplyInput(float horizontalMovementRatio, bool jumpPressed)
{
AccelerationY = PlayerMovementCoefficients.GravityAcceleration;
VelocityX = horizontalMovementRatio * PlayerMovementCoefficients.MaxHorizontalSpeed;
if (jumpPressed && IsOnGround)
{
VelocityY = PlayerMovementCoefficients.JumpVelocity;
}
}
public void ReactToCollision(CCPoint reposition)
{
IsOnGround = reposition.Y > 0;
ProjectVelocityOnSurface (reposition);
}
}
}
| 19.975309 | 97 | 0.724351 | [
"Apache-2.0"
] | KinveyClientServices/xamarin-mobile-samples | CoinTime/CoinTimeShared/Entities/Player.cs | 1,620 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace EmpowerBusiness
{
using System;
using System.Collections.Generic;
public partial class IW_UWAccessRight
{
public int UWAccessRightSysID { get; set; }
public System.DateTime SysDate { get; set; }
public int UserID { get; set; }
public int PackageID { get; set; }
public string AccessType { get; set; }
}
}
| 33.5 | 85 | 0.527363 | [
"Apache-2.0"
] | HaloImageEngine/EmpowerClaim-hotfix-1.25.1 | EmpowerBusiness/IW_UWAccessRight.cs | 804 | 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.Cdb.V20170320.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class CreateDBInstanceHourRequest : AbstractModel
{
/// <summary>
/// 实例数量,默认值为 1,最小值 1,最大值为 100。
/// </summary>
[JsonProperty("GoodsNum")]
public long? GoodsNum{ get; set; }
/// <summary>
/// 实例内存大小,单位:MB,请使用 [获取云数据库可售卖规格](https://cloud.tencent.com/document/api/236/17229) 接口获取可创建的内存规格。
/// </summary>
[JsonProperty("Memory")]
public long? Memory{ get; set; }
/// <summary>
/// 实例硬盘大小,单位:GB,请使用 [获取云数据库可售卖规格](https://cloud.tencent.com/document/api/236/17229) 接口获取可创建的硬盘范围。
/// </summary>
[JsonProperty("Volume")]
public long? Volume{ get; set; }
/// <summary>
/// MySQL 版本,值包括:5.5、5.6 和 5.7,请使用 [获取云数据库可售卖规格](https://cloud.tencent.com/document/api/236/17229) 接口获取可创建的实例版本。
/// </summary>
[JsonProperty("EngineVersion")]
public string EngineVersion{ get; set; }
/// <summary>
/// 私有网络 ID,如果不传则默认选择基础网络,请使用 [查询私有网络列表](/document/api/215/15778) 。
/// </summary>
[JsonProperty("UniqVpcId")]
public string UniqVpcId{ get; set; }
/// <summary>
/// 私有网络下的子网 ID,如果设置了 UniqVpcId,则 UniqSubnetId 必填,请使用[查询子网列表](/document/api/215/15784)。
/// </summary>
[JsonProperty("UniqSubnetId")]
public string UniqSubnetId{ get; set; }
/// <summary>
/// 项目 ID,不填为默认项目。请使用 [查询项目列表](https://cloud.tencent.com/document/product/378/4400) 接口获取项目 ID。
/// </summary>
[JsonProperty("ProjectId")]
public long? ProjectId{ get; set; }
/// <summary>
/// 可用区信息,该参数缺省时,系统会自动选择一个可用区,请使用 [获取云数据库可售卖规格](https://cloud.tencent.com/document/api/236/17229) 接口获取可创建的可用区。
/// </summary>
[JsonProperty("Zone")]
public string Zone{ get; set; }
/// <summary>
/// 实例 ID,购买只读实例或者灾备实例时必填,该字段表示只读实例或者灾备实例的主实例 ID,请使用 [查询实例列表](https://cloud.tencent.com/document/api/236/15872) 接口查询云数据库实例 ID。
/// </summary>
[JsonProperty("MasterInstanceId")]
public string MasterInstanceId{ get; set; }
/// <summary>
/// 实例类型,默认为 master,支持值包括:master - 表示主实例,dr - 表示灾备实例,ro - 表示只读实例。
/// </summary>
[JsonProperty("InstanceRole")]
public string InstanceRole{ get; set; }
/// <summary>
/// 主实例的可用区信息,购买灾备实例时必填。
/// </summary>
[JsonProperty("MasterRegion")]
public string MasterRegion{ get; set; }
/// <summary>
/// 自定义端口,端口支持范围:[ 1024-65535 ] 。
/// </summary>
[JsonProperty("Port")]
public long? Port{ get; set; }
/// <summary>
/// 设置 root 帐号密码,密码规则:8 - 64 个字符,至少包含字母、数字、字符(支持的字符:_+-&=!@#$%^*())中的两种,购买主实例时可指定该参数,购买只读实例或者灾备实例时指定该参数无意义。
/// </summary>
[JsonProperty("Password")]
public string Password{ get; set; }
/// <summary>
/// 参数列表,参数格式如 ParamList.0.Name=auto_increment&ParamList.0.Value=1。可通过 [查询默认的可设置参数列表](https://cloud.tencent.com/document/api/236/32662) 查询支持设置的参数。
/// </summary>
[JsonProperty("ParamList")]
public ParamInfo[] ParamList{ get; set; }
/// <summary>
/// 数据复制方式,默认为 0,支持值包括:0 - 表示异步复制,1 - 表示半同步复制,2 - 表示强同步复制,购买主实例时可指定该参数,购买只读实例或者灾备实例时指定该参数无意义。
/// </summary>
[JsonProperty("ProtectMode")]
public long? ProtectMode{ get; set; }
/// <summary>
/// 多可用区域,默认为 0,支持值包括:0 - 表示单可用区,1 - 表示多可用区,购买主实例时可指定该参数,购买只读实例或者灾备实例时指定该参数无意义。
/// </summary>
[JsonProperty("DeployMode")]
public long? DeployMode{ get; set; }
/// <summary>
/// 备库 1 的可用区信息,默认为 Zone 的值,购买主实例时可指定该参数,购买只读实例或者灾备实例时指定该参数无意义。
/// </summary>
[JsonProperty("SlaveZone")]
public string SlaveZone{ get; set; }
/// <summary>
/// 备库 2 的可用区信息,默认为空,购买强同步主实例时可指定该参数,购买其他类型实例时指定该参数无意义。
/// </summary>
[JsonProperty("BackupZone")]
public string BackupZone{ get; set; }
/// <summary>
/// 安全组参数,可使用 [查询项目安全组信息](https://cloud.tencent.com/document/api/236/15850) 接口查询某个项目的安全组详情。
/// </summary>
[JsonProperty("SecurityGroup")]
public string[] SecurityGroup{ get; set; }
/// <summary>
/// 只读实例信息。购买只读实例时,该参数必传。
/// </summary>
[JsonProperty("RoGroup")]
public RoGroup RoGroup{ get; set; }
/// <summary>
/// 购买按量计费实例该字段无意义。
/// </summary>
[JsonProperty("AutoRenewFlag")]
public long? AutoRenewFlag{ get; set; }
/// <summary>
/// 实例名称。
/// </summary>
[JsonProperty("InstanceName")]
public string InstanceName{ get; set; }
/// <summary>
/// 实例标签信息。
/// </summary>
[JsonProperty("ResourceTags")]
public TagInfo[] ResourceTags{ get; set; }
/// <summary>
/// 置放群组 ID。
/// </summary>
[JsonProperty("DeployGroupId")]
public string DeployGroupId{ get; set; }
/// <summary>
/// 用于保证请求幂等性的字符串。该字符串由客户生成,需保证不同请求之间在当天内唯一,最大值不超过64个ASCII字符。若不指定该参数,则无法保证请求的幂等性。
/// </summary>
[JsonProperty("ClientToken")]
public string ClientToken{ get; set; }
/// <summary>
/// 实例类型。支持值包括: "HA" - 高可用版实例, "BASIC" - 基础版实例。 不指定则默认为高可用版。
/// </summary>
[JsonProperty("DeviceType")]
public string DeviceType{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "GoodsNum", this.GoodsNum);
this.SetParamSimple(map, prefix + "Memory", this.Memory);
this.SetParamSimple(map, prefix + "Volume", this.Volume);
this.SetParamSimple(map, prefix + "EngineVersion", this.EngineVersion);
this.SetParamSimple(map, prefix + "UniqVpcId", this.UniqVpcId);
this.SetParamSimple(map, prefix + "UniqSubnetId", this.UniqSubnetId);
this.SetParamSimple(map, prefix + "ProjectId", this.ProjectId);
this.SetParamSimple(map, prefix + "Zone", this.Zone);
this.SetParamSimple(map, prefix + "MasterInstanceId", this.MasterInstanceId);
this.SetParamSimple(map, prefix + "InstanceRole", this.InstanceRole);
this.SetParamSimple(map, prefix + "MasterRegion", this.MasterRegion);
this.SetParamSimple(map, prefix + "Port", this.Port);
this.SetParamSimple(map, prefix + "Password", this.Password);
this.SetParamArrayObj(map, prefix + "ParamList.", this.ParamList);
this.SetParamSimple(map, prefix + "ProtectMode", this.ProtectMode);
this.SetParamSimple(map, prefix + "DeployMode", this.DeployMode);
this.SetParamSimple(map, prefix + "SlaveZone", this.SlaveZone);
this.SetParamSimple(map, prefix + "BackupZone", this.BackupZone);
this.SetParamArraySimple(map, prefix + "SecurityGroup.", this.SecurityGroup);
this.SetParamObj(map, prefix + "RoGroup.", this.RoGroup);
this.SetParamSimple(map, prefix + "AutoRenewFlag", this.AutoRenewFlag);
this.SetParamSimple(map, prefix + "InstanceName", this.InstanceName);
this.SetParamArrayObj(map, prefix + "ResourceTags.", this.ResourceTags);
this.SetParamSimple(map, prefix + "DeployGroupId", this.DeployGroupId);
this.SetParamSimple(map, prefix + "ClientToken", this.ClientToken);
this.SetParamSimple(map, prefix + "DeviceType", this.DeviceType);
}
}
}
| 38.812785 | 154 | 0.597059 | [
"Apache-2.0"
] | ImEdisonJiang/tencentcloud-sdk-dotnet | TencentCloud/Cdb/V20170320/Models/CreateDBInstanceHourRequest.cs | 10,382 | C# |
using System;
namespace lbhDynamics365AccessTokenApi.Tests
{
public static class ConnectionString
{
public static string TestDatabase()
{
return $"Host={Environment.GetEnvironmentVariable("DB_HOST") ?? "127.0.0.1"};" +
$"Port={Environment.GetEnvironmentVariable("DB_PORT") ?? "5432"};" +
$"Username={Environment.GetEnvironmentVariable("DB_USERNAME") ?? "postgres"};" +
$"Password={Environment.GetEnvironmentVariable("DB_PASSWORD") ?? "mypassword"};" +
$"Database={Environment.GetEnvironmentVariable("DB_DATABASE") ?? "test-database"}";
}
}
}
| 39.235294 | 102 | 0.608696 | [
"MIT"
] | LBHackney-IT/lbh-dynamics-365-access-token-api | lbhDynamics365AccessTokenApi.Tests/ConnectionString.cs | 667 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Http.Headers;
using System.Text;
using System.Xml.Linq;
using Umbraco.Core.Configuration;
using Umbraco.Core.Dynamics;
using Umbraco.Core.IO;
using Umbraco.Core.Models;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence.Caching;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Persistence.Factories;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Persistence.Repositories
{
/// <summary>
/// Represents a repository for doing CRUD operations for <see cref="IContent"/>
/// </summary>
internal class ContentRepository : RecycleBinRepository<int, IContent>, IContentRepository
{
private readonly IContentTypeRepository _contentTypeRepository;
private readonly ITemplateRepository _templateRepository;
private readonly ITagRepository _tagRepository;
private readonly CacheHelper _cacheHelper;
private readonly ContentPreviewRepository<IContent> _contentPreviewRepository;
private readonly ContentXmlRepository<IContent> _contentXmlRepository;
public ContentRepository(IDatabaseUnitOfWork work, IContentTypeRepository contentTypeRepository, ITemplateRepository templateRepository, ITagRepository tagRepository, CacheHelper cacheHelper)
: base(work)
{
if (contentTypeRepository == null) throw new ArgumentNullException("contentTypeRepository");
if (templateRepository == null) throw new ArgumentNullException("templateRepository");
if (tagRepository == null) throw new ArgumentNullException("tagRepository");
_contentTypeRepository = contentTypeRepository;
_templateRepository = templateRepository;
_tagRepository = tagRepository;
_cacheHelper = cacheHelper;
_contentPreviewRepository = new ContentPreviewRepository<IContent>(work, NullCacheProvider.Current);
_contentXmlRepository = new ContentXmlRepository<IContent>(work, NullCacheProvider.Current);
EnsureUniqueNaming = true;
}
public ContentRepository(IDatabaseUnitOfWork work, IRepositoryCacheProvider cache, IContentTypeRepository contentTypeRepository, ITemplateRepository templateRepository, ITagRepository tagRepository, CacheHelper cacheHelper)
: base(work, cache)
{
if (contentTypeRepository == null) throw new ArgumentNullException("contentTypeRepository");
if (templateRepository == null) throw new ArgumentNullException("templateRepository");
if (tagRepository == null) throw new ArgumentNullException("tagRepository");
_contentTypeRepository = contentTypeRepository;
_templateRepository = templateRepository;
_tagRepository = tagRepository;
_cacheHelper = cacheHelper;
_contentPreviewRepository = new ContentPreviewRepository<IContent>(work, NullCacheProvider.Current);
_contentXmlRepository = new ContentXmlRepository<IContent>(work, NullCacheProvider.Current);
EnsureUniqueNaming = true;
}
public bool EnsureUniqueNaming { get; set; }
#region Overrides of RepositoryBase<IContent>
protected override IContent PerformGet(int id)
{
var sql = GetBaseQuery(false)
.Where(GetBaseWhereClause(), new { Id = id })
.Where<DocumentDto>(x => x.Newest)
.OrderByDescending<ContentVersionDto>(x => x.VersionDate);
var dto = Database.Fetch<DocumentDto, ContentVersionDto, ContentDto, NodeDto>(sql).FirstOrDefault();
if (dto == null)
return null;
var content = CreateContentFromDto(dto, dto.ContentVersionDto.VersionId, sql);
return content;
}
protected override IEnumerable<IContent> PerformGetAll(params int[] ids)
{
var sql = GetBaseQuery(false);
if (ids.Any())
{
sql.Where("umbracoNode.id in (@ids)", new {ids = ids});
}
//we only want the newest ones with this method
sql.Where<DocumentDto>(x => x.Newest);
return ProcessQuery(sql);
}
protected override IEnumerable<IContent> PerformGetByQuery(IQuery<IContent> query)
{
var sqlClause = GetBaseQuery(false);
var translator = new SqlTranslator<IContent>(sqlClause, query);
var sql = translator.Translate()
.Where<DocumentDto>(x => x.Newest)
.OrderByDescending<ContentVersionDto>(x => x.VersionDate)
.OrderBy<NodeDto>(x => x.SortOrder);
return ProcessQuery(sql);
}
#endregion
#region Overrides of PetaPocoRepositoryBase<IContent>
protected override Sql GetBaseQuery(bool isCount)
{
var sql = new Sql();
sql.Select(isCount ? "COUNT(*)" : "*")
.From<DocumentDto>()
.InnerJoin<ContentVersionDto>()
.On<DocumentDto, ContentVersionDto>(left => left.VersionId, right => right.VersionId)
.InnerJoin<ContentDto>()
.On<ContentVersionDto, ContentDto>(left => left.NodeId, right => right.NodeId)
.InnerJoin<NodeDto>()
.On<ContentDto, NodeDto>(left => left.NodeId, right => right.NodeId)
.Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId );
return sql;
}
protected override string GetBaseWhereClause()
{
return "umbracoNode.id = @Id";
}
protected override IEnumerable<string> GetDeleteClauses()
{
var list = new List<string>
{
"DELETE FROM cmsTask WHERE nodeId = @Id",
"DELETE FROM umbracoUser2NodeNotify WHERE nodeId = @Id",
"DELETE FROM umbracoUser2NodePermission WHERE nodeId = @Id",
"DELETE FROM umbracoRelation WHERE parentId = @Id",
"DELETE FROM umbracoRelation WHERE childId = @Id",
"DELETE FROM cmsTagRelationship WHERE nodeId = @Id",
"DELETE FROM umbracoDomains WHERE domainRootStructureID = @Id",
"DELETE FROM cmsDocument WHERE nodeId = @Id",
"DELETE FROM cmsPropertyData WHERE contentNodeId = @Id",
"DELETE FROM cmsPreviewXml WHERE nodeId = @Id",
"DELETE FROM cmsContentVersion WHERE ContentId = @Id",
"DELETE FROM cmsContentXml WHERE nodeId = @Id",
"DELETE FROM cmsContent WHERE nodeId = @Id",
"DELETE FROM umbracoNode WHERE id = @Id"
};
return list;
}
protected override Guid NodeObjectTypeId
{
get { return new Guid(Constants.ObjectTypes.Document); }
}
#endregion
#region Overrides of VersionableRepositoryBase<IContent>
public void RebuildXmlStructures(Func<IContent, XElement> serializer, int groupSize = 5000, IEnumerable<int> contentTypeIds = null)
{
//Ok, now we need to remove the data and re-insert it, we'll do this all in one transaction too.
using (var tr = Database.GetTransaction())
{
//Remove all the data first, if anything fails after this it's no problem the transaction will be reverted
if (contentTypeIds == null)
{
var subQuery = new Sql()
.Select("DISTINCT cmsContentXml.nodeId")
.From<ContentXmlDto>()
.InnerJoin<DocumentDto>()
.On<ContentXmlDto, DocumentDto>(left => left.NodeId, right => right.NodeId);
var deleteSql = SqlSyntaxContext.SqlSyntaxProvider.GetDeleteSubquery("cmsContentXml", "nodeId", subQuery);
Database.Execute(deleteSql);
}
else
{
foreach (var id in contentTypeIds)
{
var id1 = id;
var subQuery = new Sql()
.Select("cmsDocument.nodeId")
.From<DocumentDto>()
.InnerJoin<ContentDto>()
.On<DocumentDto, ContentDto>(left => left.NodeId, right => right.NodeId)
.Where<DocumentDto>(dto => dto.Published)
.Where<ContentDto>(dto => dto.ContentTypeId == id1);
var deleteSql = SqlSyntaxContext.SqlSyntaxProvider.GetDeleteSubquery("cmsContentXml", "nodeId", subQuery);
Database.Execute(deleteSql);
}
}
//now insert the data, again if something fails here, the whole transaction is reversed
if (contentTypeIds == null)
{
var query = Query<IContent>.Builder.Where(x => x.Published == true);
RebuildXmlStructuresProcessQuery(serializer, query, tr, groupSize);
}
else
{
foreach (var contentTypeId in contentTypeIds)
{
//copy local
var id = contentTypeId;
var query = Query<IContent>.Builder.Where(x => x.Published == true && x.ContentTypeId == id && x.Trashed == false);
RebuildXmlStructuresProcessQuery(serializer, query, tr, groupSize);
}
}
tr.Complete();
}
}
private void RebuildXmlStructuresProcessQuery(Func<IContent, XElement> serializer, IQuery<IContent> query, Transaction tr, int pageSize)
{
var pageIndex = 0;
var total = int.MinValue;
var processed = 0;
do
{
var descendants = GetPagedResultsByQuery(query, pageIndex, pageSize, out total, "Path", Direction.Ascending);
var xmlItems = (from descendant in descendants
let xml = serializer(descendant)
select new ContentXmlDto { NodeId = descendant.Id, Xml = xml.ToString(SaveOptions.None) }).ToArray();
//bulk insert it into the database
Database.BulkInsertRecords(xmlItems, tr);
processed += xmlItems.Length;
pageIndex++;
} while (processed < total);
}
public override IContent GetByVersion(Guid versionId)
{
var sql = GetBaseQuery(false);
sql.Where("cmsContentVersion.VersionId = @VersionId", new { VersionId = versionId });
sql.OrderByDescending<ContentVersionDto>(x => x.VersionDate);
var dto = Database.Fetch<DocumentDto, ContentVersionDto, ContentDto, NodeDto>(sql).FirstOrDefault();
if (dto == null)
return null;
var content = CreateContentFromDto(dto, versionId, sql);
return content;
}
public override void DeleteVersion(Guid versionId)
{
var sql = new Sql()
.Select("*")
.From<DocumentDto>()
.InnerJoin<ContentVersionDto>().On<ContentVersionDto, DocumentDto>(left => left.VersionId, right => right.VersionId)
.Where<ContentVersionDto>(x => x.VersionId == versionId)
.Where<DocumentDto>(x => x.Newest != true);
var dto = Database.Fetch<DocumentDto, ContentVersionDto>(sql).FirstOrDefault();
if(dto == null) return;
using (var transaction = Database.GetTransaction())
{
PerformDeleteVersion(dto.NodeId, versionId);
transaction.Complete();
}
}
public override void DeleteVersions(int id, DateTime versionDate)
{
var sql = new Sql()
.Select("*")
.From<DocumentDto>()
.InnerJoin<ContentVersionDto>().On<ContentVersionDto, DocumentDto>(left => left.VersionId, right => right.VersionId)
.Where<ContentVersionDto>(x => x.NodeId == id)
.Where<ContentVersionDto>(x => x.VersionDate < versionDate)
.Where<DocumentDto>(x => x.Newest != true);
var list = Database.Fetch<DocumentDto, ContentVersionDto>(sql);
if (list.Any() == false) return;
using (var transaction = Database.GetTransaction())
{
foreach (var dto in list)
{
PerformDeleteVersion(id, dto.VersionId);
}
transaction.Complete();
}
}
protected override void PerformDeleteVersion(int id, Guid versionId)
{
Database.Delete<PreviewXmlDto>("WHERE nodeId = @Id AND versionId = @VersionId", new { Id = id, VersionId = versionId });
Database.Delete<PropertyDataDto>("WHERE contentNodeId = @Id AND versionId = @VersionId", new { Id = id, VersionId = versionId });
Database.Delete<ContentVersionDto>("WHERE ContentId = @Id AND VersionId = @VersionId", new { Id = id, VersionId = versionId });
Database.Delete<DocumentDto>("WHERE nodeId = @Id AND versionId = @VersionId", new { Id = id, VersionId = versionId });
}
#endregion
#region Unit of Work Implementation
protected override void PersistNewItem(IContent entity)
{
((Content)entity).AddingEntity();
//Ensure unique name on the same level
entity.Name = EnsureUniqueNodeName(entity.ParentId, entity.Name);
//Ensure that strings don't contain characters that are invalid in XML
entity.SanitizeEntityPropertiesForXmlStorage();
var factory = new ContentFactory(NodeObjectTypeId, entity.Id);
var dto = factory.BuildDto(entity);
//NOTE Should the logic below have some kind of fallback for empty parent ids ?
//Logic for setting Path, Level and SortOrder
var parent = Database.First<NodeDto>("WHERE id = @ParentId", new { ParentId = entity.ParentId });
int level = parent.Level + 1;
int sortOrder =
Database.ExecuteScalar<int>("SELECT COUNT(*) FROM umbracoNode WHERE parentID = @ParentId AND nodeObjectType = @NodeObjectType",
new { ParentId = entity.ParentId, NodeObjectType = NodeObjectTypeId });
//Create the (base) node data - umbracoNode
var nodeDto = dto.ContentVersionDto.ContentDto.NodeDto;
nodeDto.Path = parent.Path;
nodeDto.Level = short.Parse(level.ToString(CultureInfo.InvariantCulture));
nodeDto.SortOrder = sortOrder;
var o = Database.IsNew(nodeDto) ? Convert.ToInt32(Database.Insert(nodeDto)) : Database.Update(nodeDto);
//Update with new correct path
nodeDto.Path = string.Concat(parent.Path, ",", nodeDto.NodeId);
Database.Update(nodeDto);
//Update entity with correct values
entity.Id = nodeDto.NodeId; //Set Id on entity to ensure an Id is set
entity.Path = nodeDto.Path;
entity.SortOrder = sortOrder;
entity.Level = level;
//Assign the same permissions to it as the parent node
// http://issues.umbraco.org/issue/U4-2161
var permissionsRepo = new PermissionRepository<IContent>(UnitOfWork, _cacheHelper);
var parentPermissions = permissionsRepo.GetPermissionsForEntity(entity.ParentId).ToArray();
//if there are parent permissions then assign them, otherwise leave null and permissions will become the
// user's default permissions.
if (parentPermissions.Any())
{
var userPermissions = (
from perm in parentPermissions
from p in perm.AssignedPermissions
select new EntityPermissionSet.UserPermission(perm.UserId, p)).ToList();
permissionsRepo.ReplaceEntityPermissions(new EntityPermissionSet(entity.Id, userPermissions));
//flag the entity's permissions changed flag so we can track those changes.
//Currently only used for the cache refreshers to detect if we should refresh all user permissions cache.
((Content) entity).PermissionsChanged = true;
}
//Create the Content specific data - cmsContent
var contentDto = dto.ContentVersionDto.ContentDto;
contentDto.NodeId = nodeDto.NodeId;
Database.Insert(contentDto);
//Create the first version - cmsContentVersion
//Assumes a new Version guid and Version date (modified date) has been set
var contentVersionDto = dto.ContentVersionDto;
contentVersionDto.NodeId = nodeDto.NodeId;
Database.Insert(contentVersionDto);
//Create the Document specific data for this version - cmsDocument
//Assumes a new Version guid has been generated
dto.NodeId = nodeDto.NodeId;
Database.Insert(dto);
//Create the PropertyData for this version - cmsPropertyData
var propertyFactory = new PropertyFactory(entity.ContentType.CompositionPropertyTypes.ToArray(), entity.Version, entity.Id);
var propertyDataDtos = propertyFactory.BuildDto(entity.Properties);
var keyDictionary = new Dictionary<int, int>();
//Add Properties
foreach (var propertyDataDto in propertyDataDtos)
{
var primaryKey = Convert.ToInt32(Database.Insert(propertyDataDto));
keyDictionary.Add(propertyDataDto.PropertyTypeId, primaryKey);
}
//Update Properties with its newly set Id
foreach (var property in entity.Properties)
{
property.Id = keyDictionary[property.PropertyTypeId];
}
//lastly, check if we are a creating a published version , then update the tags table
if (entity.Published)
{
UpdatePropertyTags(entity, _tagRepository);
}
entity.ResetDirtyProperties();
}
protected override void PersistUpdatedItem(IContent entity)
{
var publishedState = ((Content) entity).PublishedState;
//check if we need to make any database changes at all
if (entity.RequiresSaving(publishedState) == false)
{
entity.ResetDirtyProperties();
return;
}
//check if we need to create a new version
bool shouldCreateNewVersion = entity.ShouldCreateNewVersion(publishedState);
if (shouldCreateNewVersion)
{
//Updates Modified date and Version Guid
((Content)entity).UpdatingEntity();
}
else
{
entity.UpdateDate = DateTime.Now;
}
//Ensure unique name on the same level
entity.Name = EnsureUniqueNodeName(entity.ParentId, entity.Name, entity.Id);
//Ensure that strings don't contain characters that are invalid in XML
entity.SanitizeEntityPropertiesForXmlStorage();
//Look up parent to get and set the correct Path and update SortOrder if ParentId has changed
if (entity.IsPropertyDirty("ParentId"))
{
var parent = Database.First<NodeDto>("WHERE id = @ParentId", new { ParentId = entity.ParentId });
entity.Path = string.Concat(parent.Path, ",", entity.Id);
entity.Level = parent.Level + 1;
var maxSortOrder =
Database.ExecuteScalar<int>(
"SELECT coalesce(max(sortOrder),0) FROM umbracoNode WHERE parentid = @ParentId AND nodeObjectType = @NodeObjectType",
new {ParentId = entity.ParentId, NodeObjectType = NodeObjectTypeId});
entity.SortOrder = maxSortOrder + 1;
//Question: If we move a node, should we update permissions to inherit from the new parent if the parent has permissions assigned?
// if we do that, then we'd need to propogate permissions all the way downward which might not be ideal for many people.
// Gonna just leave it as is for now, and not re-propogate permissions.
}
var factory = new ContentFactory(NodeObjectTypeId, entity.Id);
//Look up Content entry to get Primary for updating the DTO
var contentDto = Database.SingleOrDefault<ContentDto>("WHERE nodeId = @Id", new { Id = entity.Id });
factory.SetPrimaryKey(contentDto.PrimaryKey);
var dto = factory.BuildDto(entity);
//Updates the (base) node data - umbracoNode
var nodeDto = dto.ContentVersionDto.ContentDto.NodeDto;
var o = Database.Update(nodeDto);
//Only update this DTO if the contentType has actually changed
if (contentDto.ContentTypeId != entity.ContentTypeId)
{
//Create the Content specific data - cmsContent
var newContentDto = dto.ContentVersionDto.ContentDto;
Database.Update(newContentDto);
}
//a flag that we'll use later to create the tags in the tag db table
var publishedStateChanged = false;
//If Published state has changed then previous versions should have their publish state reset.
//If state has been changed to unpublished the previous versions publish state should also be reset.
//if (((ICanBeDirty)entity).IsPropertyDirty("Published") && (entity.Published || publishedState == PublishedState.Unpublished))
if (entity.ShouldClearPublishedFlagForPreviousVersions(publishedState, shouldCreateNewVersion))
{
var publishedDocs = Database.Fetch<DocumentDto>("WHERE nodeId = @Id AND published = @IsPublished", new { Id = entity.Id, IsPublished = true });
foreach (var doc in publishedDocs)
{
var docDto = doc;
docDto.Published = false;
Database.Update(docDto);
}
//this is a newly published version so we'll update the tags table too (end of this method)
publishedStateChanged = true;
}
//Look up (newest) entries by id in cmsDocument table to set newest = false
var documentDtos = Database.Fetch<DocumentDto>("WHERE nodeId = @Id AND newest = @IsNewest", new { Id = entity.Id, IsNewest = true });
foreach (var documentDto in documentDtos)
{
var docDto = documentDto;
docDto.Newest = false;
Database.Update(docDto);
}
var contentVersionDto = dto.ContentVersionDto;
if (shouldCreateNewVersion)
{
//Create a new version - cmsContentVersion
//Assumes a new Version guid and Version date (modified date) has been set
Database.Insert(contentVersionDto);
//Create the Document specific data for this version - cmsDocument
//Assumes a new Version guid has been generated
Database.Insert(dto);
}
else
{
//In order to update the ContentVersion we need to retrieve its primary key id
var contentVerDto = Database.SingleOrDefault<ContentVersionDto>("WHERE VersionId = @Version", new { Version = entity.Version });
contentVersionDto.Id = contentVerDto.Id;
Database.Update(contentVersionDto);
Database.Update(dto);
}
//Create the PropertyData for this version - cmsPropertyData
var propertyFactory = new PropertyFactory(entity.ContentType.CompositionPropertyTypes.ToArray(), entity.Version, entity.Id);
var propertyDataDtos = propertyFactory.BuildDto(entity.Properties);
var keyDictionary = new Dictionary<int, int>();
//Add Properties
foreach (var propertyDataDto in propertyDataDtos)
{
if (shouldCreateNewVersion == false && propertyDataDto.Id > 0)
{
Database.Update(propertyDataDto);
}
else
{
int primaryKey = Convert.ToInt32(Database.Insert(propertyDataDto));
keyDictionary.Add(propertyDataDto.PropertyTypeId, primaryKey);
}
}
//Update Properties with its newly set Id
if (keyDictionary.Any())
{
foreach (var property in entity.Properties)
{
if(keyDictionary.ContainsKey(property.PropertyTypeId) == false) continue;
property.Id = keyDictionary[property.PropertyTypeId];
}
}
//lastly, check if we are a newly published version and then update the tags table
if (publishedStateChanged && entity.Published)
{
UpdatePropertyTags(entity, _tagRepository);
}
else if (publishedStateChanged && (entity.Trashed || entity.Published == false))
{
//it's in the trash or not published remove all entity tags
ClearEntityTags(entity, _tagRepository);
}
entity.ResetDirtyProperties();
}
#endregion
#region Implementation of IContentRepository
public IEnumerable<IContent> GetByPublishedVersion(IQuery<IContent> query)
{
// we WANT to return contents in top-down order, ie parents should come before children
// ideal would be pure xml "document order" which can be achieved with:
// ORDER BY substring(path, 1, len(path) - charindex(',', reverse(path))), sortOrder
// but that's probably an overkill - sorting by level,sortOrder should be enough
var sqlClause = GetBaseQuery(false);
var translator = new SqlTranslator<IContent>(sqlClause, query);
var sql = translator.Translate()
.Where<DocumentDto>(x => x.Published)
.OrderBy<NodeDto>(x => x.Level)
.OrderBy<NodeDto>(x => x.SortOrder);
//NOTE: This doesn't allow properties to be part of the query
var dtos = Database.Fetch<DocumentDto, ContentVersionDto, ContentDto, NodeDto>(sql);
foreach (var dto in dtos)
{
//Check in the cache first. If it exists there AND it is published
// then we can use that entity. Otherwise if it is not published (which can be the case
// because we only store the 'latest' entries in the cache which might not be the published
// version)
var fromCache = TryGetFromCache(dto.NodeId);
if (fromCache.Success && fromCache.Result.Published)
{
yield return fromCache.Result;
}
else
{
yield return CreateContentFromDto(dto, dto.VersionId, sql);
}
}
}
public int CountPublished()
{
var sql = GetBaseQuery(true).Where<NodeDto>(x => x.Trashed == false)
.Where<DocumentDto>(x => x.Published == true)
.Where<DocumentDto>(x => x.Newest == true);
return Database.ExecuteScalar<int>(sql);
}
public void ReplaceContentPermissions(EntityPermissionSet permissionSet)
{
var repo = new PermissionRepository<IContent>(UnitOfWork, _cacheHelper);
repo.ReplaceEntityPermissions(permissionSet);
}
public IContent GetByLanguage(int id, string language)
{
var sql = GetBaseQuery(false);
sql.Where(GetBaseWhereClause(), new { Id = id });
sql.Where<ContentVersionDto>(x => x.Language == language);
sql.OrderByDescending<ContentVersionDto>(x => x.VersionDate);
var dto = Database.Fetch<DocumentDto, ContentVersionDto, ContentDto, NodeDto>(sql).FirstOrDefault();
if (dto == null)
return null;
return GetByVersion(dto.ContentVersionDto.VersionId);
}
/// <summary>
/// Assigns a single permission to the current content item for the specified user ids
/// </summary>
/// <param name="entity"></param>
/// <param name="permission"></param>
/// <param name="userIds"></param>
public void AssignEntityPermission(IContent entity, char permission, IEnumerable<int> userIds)
{
var repo = new PermissionRepository<IContent>(UnitOfWork, _cacheHelper);
repo.AssignEntityPermission(entity, permission, userIds);
}
public IEnumerable<EntityPermission> GetPermissionsForEntity(int entityId)
{
var repo = new PermissionRepository<IContent>(UnitOfWork, _cacheHelper);
return repo.GetPermissionsForEntity(entityId);
}
/// <summary>
/// Adds/updates content/published xml
/// </summary>
/// <param name="content"></param>
/// <param name="xml"></param>
public void AddOrUpdateContentXml(IContent content, Func<IContent, XElement> xml)
{
var contentExists = Database.ExecuteScalar<int>("SELECT COUNT(nodeId) FROM cmsContentXml WHERE nodeId = @Id", new { Id = content.Id }) != 0;
_contentXmlRepository.AddOrUpdate(new ContentXmlEntity<IContent>(contentExists, content, xml));
}
/// <summary>
/// Used to remove the content xml for a content item
/// </summary>
/// <param name="content"></param>
public void DeleteContentXml(IContent content)
{
_contentXmlRepository.Delete(new ContentXmlEntity<IContent>(content));
}
/// <summary>
/// Adds/updates preview xml
/// </summary>
/// <param name="content"></param>
/// <param name="xml"></param>
public void AddOrUpdatePreviewXml(IContent content, Func<IContent, XElement> xml)
{
var previewExists =
Database.ExecuteScalar<int>("SELECT COUNT(nodeId) FROM cmsPreviewXml WHERE nodeId = @Id AND versionId = @Version",
new { Id = content.Id, Version = content.Version }) != 0;
_contentPreviewRepository.AddOrUpdate(new ContentPreviewEntity<IContent>(previewExists, content, xml));
}
/// <summary>
/// Gets paged content results
/// </summary>
/// <param name="query">Query to excute</param>
/// <param name="pageIndex">Page number</param>
/// <param name="pageSize">Page size</param>
/// <param name="totalRecords">Total records query would return without paging</param>
/// <param name="orderBy">Field to order by</param>
/// <param name="orderDirection">Direction to order by</param>
/// <param name="filter">Search text filter</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
public IEnumerable<IContent> GetPagedResultsByQuery(IQuery<IContent> query, int pageIndex, int pageSize, out int totalRecords,
string orderBy, Direction orderDirection, string filter = "")
{
//NOTE: This uses the GetBaseQuery method but that does not take into account the required 'newest' field which is
// what we always require for a paged result, so we'll ensure it's included in the filter
var args = new List<object>();
var sbWhere = new StringBuilder("AND (cmsDocument.newest = 1)");
if (filter.IsNullOrWhiteSpace() == false)
{
sbWhere.Append(" AND (cmsDocument." + SqlSyntaxContext.SqlSyntaxProvider.GetQuotedColumnName("text") + " LIKE @" + args.Count + ")");
args.Add("%" + filter + "%");
}
Func<Tuple<string, object[]>> filterCallback = () => new Tuple<string, object[]>(sbWhere.ToString(), args.ToArray());
return GetPagedResultsByQuery<DocumentDto, Content>(query, pageIndex, pageSize, out totalRecords,
new Tuple<string, string>("cmsDocument", "nodeId"),
ProcessQuery, orderBy, orderDirection,
filterCallback);
}
#endregion
#region IRecycleBinRepository members
protected override int RecycleBinId
{
get { return Constants.System.RecycleBinContent; }
}
#endregion
protected override string GetDatabaseFieldNameForOrderBy(string orderBy)
{
//Some custom ones
switch (orderBy.ToUpperInvariant())
{
case "NAME":
return "cmsDocument.text";
case "UPDATER":
//TODO: This isn't going to work very nicely because it's going to order by ID, not by letter
return "cmsDocument.documentUser";
}
return base.GetDatabaseFieldNameForOrderBy(orderBy);
}
private IEnumerable<IContent> ProcessQuery(Sql sql)
{
//NOTE: This doesn't allow properties to be part of the query
var dtos = Database.Fetch<DocumentDto, ContentVersionDto, ContentDto, NodeDto>(sql);
//nothing found
if (dtos.Any() == false) return Enumerable.Empty<IContent>();
//content types
//NOTE: This should be ok for an SQL 'IN' statement, there shouldn't be an insane amount of content types
var contentTypes = _contentTypeRepository.GetAll(dtos.Select(x => x.ContentVersionDto.ContentDto.ContentTypeId).ToArray())
.ToArray();
//NOTE: This should be ok for an SQL 'IN' statement, there shouldn't be an insane amount of content types
var templates = _templateRepository.GetAll(
dtos
.Where(dto => dto.TemplateId.HasValue && dto.TemplateId.Value > 0)
.Select(x => x.TemplateId.Value).ToArray())
.ToArray();
var dtosWithContentTypes = dtos
//This select into and null check are required because we don't have a foreign damn key on the contentType column
// http://issues.umbraco.org/issue/U4-5503
.Select(x => new { dto = x, contentType = contentTypes.FirstOrDefault(ct => ct.Id == x.ContentVersionDto.ContentDto.ContentTypeId) })
.Where(x => x.contentType != null)
.ToArray();
//Go get the property data for each document
var docDefs = dtosWithContentTypes.Select(d => new DocumentDefinition(
d.dto.NodeId,
d.dto.VersionId,
d.dto.ContentVersionDto.VersionDate,
d.dto.ContentVersionDto.ContentDto.NodeDto.CreateDate,
d.contentType));
var propertyData = GetPropertyCollection(sql, docDefs);
return dtosWithContentTypes.Select(d => CreateContentFromDto(
d.dto,
contentTypes.First(ct => ct.Id == d.dto.ContentVersionDto.ContentDto.ContentTypeId),
templates.FirstOrDefault(tem => tem.Id == (d.dto.TemplateId.HasValue ? d.dto.TemplateId.Value : -1)),
propertyData[d.dto.NodeId]));
}
/// <summary>
/// Private method to create a content object from a DocumentDto, which is used by Get and GetByVersion.
/// </summary>
/// <param name="d"></param>
/// <param name="contentType"></param>
/// <param name="template"></param>
/// <param name="propCollection"></param>
/// <returns></returns>
private IContent CreateContentFromDto(DocumentDto dto,
IContentType contentType,
ITemplate template,
Models.PropertyCollection propCollection)
{
var factory = new ContentFactory(contentType, NodeObjectTypeId, dto.NodeId);
var content = factory.BuildEntity(dto);
//Check if template id is set on DocumentDto, and get ITemplate if it is.
if (dto.TemplateId.HasValue && dto.TemplateId.Value > 0)
{
content.Template = template ?? _templateRepository.Get(dto.TemplateId.Value);
}
content.Properties = propCollection;
//on initial construction we don't want to have dirty properties tracked
// http://issues.umbraco.org/issue/U4-1946
((Entity)content).ResetDirtyProperties(false);
return content;
}
/// <summary>
/// Private method to create a content object from a DocumentDto, which is used by Get and GetByVersion.
/// </summary>
/// <param name="d"></param>
/// <param name="versionId"></param>
/// <param name="docSql"></param>
/// <returns></returns>
private IContent CreateContentFromDto(DocumentDto dto, Guid versionId, Sql docSql)
{
var contentType = _contentTypeRepository.Get(dto.ContentVersionDto.ContentDto.ContentTypeId);
var factory = new ContentFactory(contentType, NodeObjectTypeId, dto.NodeId);
var content = factory.BuildEntity(dto);
//Check if template id is set on DocumentDto, and get ITemplate if it is.
if (dto.TemplateId.HasValue && dto.TemplateId.Value > 0)
{
content.Template = _templateRepository.Get(dto.TemplateId.Value);
}
var docDef = new DocumentDefinition(dto.NodeId, versionId, content.UpdateDate, content.CreateDate, contentType);
var properties = GetPropertyCollection(docSql, new[] { docDef });
content.Properties = properties[dto.NodeId];
//on initial construction we don't want to have dirty properties tracked
// http://issues.umbraco.org/issue/U4-1946
((Entity)content).ResetDirtyProperties(false);
return content;
}
private string EnsureUniqueNodeName(int parentId, string nodeName, int id = 0)
{
if (EnsureUniqueNaming == false)
return nodeName;
var sql = new Sql();
sql.Select("*")
.From<NodeDto>()
.Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId && x.ParentId == parentId && x.Text.StartsWith(nodeName));
int uniqueNumber = 1;
var currentName = nodeName;
var dtos = Database.Fetch<NodeDto>(sql);
if (dtos.Any())
{
var results = dtos.OrderBy(x => x.Text, new SimilarNodeNameComparer());
foreach (var dto in results)
{
if(id != 0 && id == dto.NodeId) continue;
if (dto.Text.ToLowerInvariant().Equals(currentName.ToLowerInvariant()))
{
currentName = nodeName + string.Format(" ({0})", uniqueNumber);
uniqueNumber++;
}
}
}
return currentName;
}
}
}
| 46.19337 | 232 | 0.572085 | [
"MIT"
] | AdrianJMartin/Umbraco-CMS | src/Umbraco.Core/Persistence/Repositories/ContentRepository.cs | 41,807 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
using Azure.Core;
namespace Azure.Communication.Email.Models
{
public partial class EmailAttachment : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("name");
writer.WriteStringValue(Name);
writer.WritePropertyName("attachmentType");
writer.WriteStringValue(AttachmentType.ToString());
writer.WritePropertyName("contentBytesBase64");
writer.WriteStringValue(ContentBytesBase64);
writer.WriteEndObject();
}
}
}
| 28.25 | 64 | 0.673831 | [
"MIT"
] | damodaravadhani/azure-sdk-for-net | sdk/communication/Azure.Communication.Email/src/Generated/Models/EmailAttachment.Serialization.cs | 791 | C# |
using NHapi.Base.Parser;
using NHapi.Base;
using NHapi.Base.Log;
using System;
using System.Collections.Generic;
using NHapi.Model.V251.Segment;
using NHapi.Model.V251.Datatype;
using NHapi.Base.Model;
namespace NHapi.Model.V251.Group
{
///<summary>
///Represents the ORL_O22_OBSERVATION_REQUEST Group. A Group is an ordered collection of message
/// segments that can repeat together or be optionally in/excluded together.
/// This Group contains the following elements:
///<ol>
///<li>0: OBR (Observation Request) </li>
///<li>1: ORL_O22_SPECIMEN (a Group object) optional repeating</li>
///</ol>
///</summary>
[Serializable]
public class ORL_O22_OBSERVATION_REQUEST : AbstractGroup {
///<summary>
/// Creates a new ORL_O22_OBSERVATION_REQUEST Group.
///</summary>
public ORL_O22_OBSERVATION_REQUEST(IGroup parent, IModelClassFactory factory) : base(parent, factory){
try {
this.add(typeof(OBR), true, false);
this.add(typeof(ORL_O22_SPECIMEN), false, true);
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating ORL_O22_OBSERVATION_REQUEST - this is probably a bug in the source code generator.", e);
}
}
///<summary>
/// Returns OBR (Observation Request) - creates it if necessary
///</summary>
public OBR OBR {
get{
OBR ret = null;
try {
ret = (OBR)this.GetStructure("OBR");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns first repetition of ORL_O22_SPECIMEN (a Group object) - creates it if necessary
///</summary>
public ORL_O22_SPECIMEN GetSPECIMEN() {
ORL_O22_SPECIMEN ret = null;
try {
ret = (ORL_O22_SPECIMEN)this.GetStructure("SPECIMEN");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
///<summary>
///Returns a specific repetition of ORL_O22_SPECIMEN
/// * (a Group object) - creates it if necessary
/// throws HL7Exception if the repetition requested is more than one
/// greater than the number of existing repetitions.
///</summary>
public ORL_O22_SPECIMEN GetSPECIMEN(int rep) {
return (ORL_O22_SPECIMEN)this.GetStructure("SPECIMEN", rep);
}
/**
* Returns the number of existing repetitions of ORL_O22_SPECIMEN
*/
public int SPECIMENRepetitionsUsed {
get{
int reps = -1;
try {
reps = this.GetAll("SPECIMEN").Length;
} catch (HL7Exception e) {
string message = "Unexpected error accessing data - this is probably a bug in the source code generator.";
HapiLogFactory.GetHapiLog(GetType()).Error(message, e);
throw new System.Exception(message);
}
return reps;
}
}
/**
* Enumerate over the ORL_O22_SPECIMEN results
*/
public IEnumerable<ORL_O22_SPECIMEN> SPECIMENs
{
get
{
for (int rep = 0; rep < SPECIMENRepetitionsUsed; rep++)
{
yield return (ORL_O22_SPECIMEN)this.GetStructure("SPECIMEN", rep);
}
}
}
///<summary>
///Adds a new ORL_O22_SPECIMEN
///</summary>
public ORL_O22_SPECIMEN AddSPECIMEN()
{
return this.AddStructure("SPECIMEN") as ORL_O22_SPECIMEN;
}
///<summary>
///Removes the given ORL_O22_SPECIMEN
///</summary>
public void RemoveSPECIMEN(ORL_O22_SPECIMEN toRemove)
{
this.RemoveStructure("SPECIMEN", toRemove);
}
///<summary>
///Removes the ORL_O22_SPECIMEN at the given index
///</summary>
public void RemoveSPECIMENAt(int index)
{
this.RemoveRepetition("SPECIMEN", index);
}
}
}
| 29.097744 | 165 | 0.693798 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | AMCN41R/nHapi | src/NHapi.Model.V251/Group/ORL_O22_OBSERVATION_REQUEST.cs | 3,870 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Instance;
using Microsoft.Identity.Test.Common;
using Microsoft.Identity.Test.Common.Core.Mocks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Identity.Test.Unit.CoreTests.InstanceTests
{
[TestClass]
public class DstsAuthorityTest
{
private const string _tenantlessDstsAuthority = "https://foo.bar.test.core.azure-test.net/dstsv2/";
[TestMethod]
public void Validate_MinNumberOfSegments()
{
try
{
var instance = Authority.CreateAuthority(_tenantlessDstsAuthority);
Assert.Fail("test should have failed");
}
catch (Exception exc)
{
Assert.IsInstanceOfType(exc, typeof(ArgumentException));
Assert.AreEqual(MsalErrorMessage.DstsAuthorityUriInvalidPath, exc.Message);
}
}
[TestMethod]
public void CreateAuthorityFromTenantedWithTenantTest()
{
string tenantedAuth = _tenantlessDstsAuthority + Guid.NewGuid().ToString() + "/";
Authority authority = AuthorityTestHelper.CreateAuthorityFromUrl(tenantedAuth);
string updatedAuthority = authority.GetTenantedAuthority("other_tenant_id");
Assert.AreEqual(tenantedAuth, updatedAuthority, "Not changed, original authority already has tenant id");
string updatedAuthority2 = authority.GetTenantedAuthority("other_tenant_id", true);
Assert.AreEqual("https://foo.bar.test.core.azure-test.net/other_tenant_id/", updatedAuthority2, "Not changed with forced flag");
}
[TestMethod]
public void TenantlessAuthorityChanges()
{
string commonAuth = _tenantlessDstsAuthority + "common/";
Authority authority = AuthorityTestHelper.CreateAuthorityFromUrl(
commonAuth);
Assert.AreEqual("common", authority.TenantId);
}
}
}
| 37.20339 | 141 | 0.650114 | [
"MIT"
] | pavel-petrenko/microsoft-authentication-library-for-dotnet | tests/Microsoft.Identity.Test.Unit/CoreTests/InstanceTests/DstsAuthorityTest.cs | 2,197 | C# |
/* ==============================================================================
* 功能描述:PascalsTriangleII
* 创 建 者:gz
* 创建日期:2017/4/21 8:24:50
* ==============================================================================*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//Given an index k, return the kth row of the Pascal’s triangle.
//For example, given k = 3,
//Return [1,3,3,1].
//Note:
//Could you optimize your algorithm to use only O(k) extra space?
namespace Array.Lib
{
/// <summary>
/// 119 : Pascal’s Triangle II
/// </summary>
public class PascalsTriangleII
{
public IList<int> GetRow(int rowIndex)
{
if (rowIndex < 0) return new List<int>();
IList<int> levelList = new List<int>();
for (int i = 0; i <= rowIndex; i++)
{
int k = levelList.Count;
for (int j = k - 1; j >= 1; j--) //这个循环是最重要的一部分,巧妙的运用了Pascal三角的特点
{
levelList[j] = levelList[j - 1] + levelList[j];
}
levelList.Add(1);
}
return levelList;
}
}
}
| 28.452381 | 83 | 0.45272 | [
"MIT"
] | Devin-X/leetcode-csharp | Array/Array.Lib/PascalsTriangleII.cs | 1,277 | C# |
namespace UglyToad.PdfPig.Images.Png
{
using System.Collections.Generic;
internal static class Adam7
{
/// <summary>
/// For a given pass number (1 indexed) the scanline indexes of the lines included in that pass in the 8x8 grid.
/// </summary>
private static readonly IReadOnlyDictionary<int, int[]> PassToScanlineGridIndex = new Dictionary<int, int[]>
{
{ 1, new []{ 0 } },
{ 2, new []{ 0 } },
{ 3, new []{ 4 } },
{ 4, new []{ 0, 4 } },
{ 5, new []{ 2, 6 } },
{ 6, new[] { 0, 2, 4, 6 } },
{ 7, new[] { 1, 3, 5, 7 } }
};
private static readonly IReadOnlyDictionary<int, int[]> PassToScanlineColumnIndex = new Dictionary<int, int[]>
{
{ 1, new []{ 0 } },
{ 2, new []{ 4 } },
{ 3, new []{ 0, 4 } },
{ 4, new []{ 2, 6 } },
{ 5, new []{ 0, 2, 4, 6 } },
{ 6, new []{ 1, 3, 5, 7 } },
{ 7, new []{ 0, 1, 2, 3, 4, 5, 6, 7 } }
};
/*
* To go from raw image data to interlaced:
*
* An 8x8 grid is repeated over the image. There are 7 passes and the indexes in this grid correspond to the
* pass number including that pixel. Each row in the grid corresponds to a scanline.
*
* 1 6 4 6 2 6 4 6 - Scanline 0: pass 1 has pixel 0, 8, 16, etc. pass 2 has pixel 4, 12, 20, etc.
* 7 7 7 7 7 7 7 7
* 5 6 5 6 5 6 5 6
* 7 7 7 7 7 7 7 7
* 3 6 4 6 3 6 4 6
* 7 7 7 7 7 7 7 7
* 5 6 5 6 5 6 5 6
* 7 7 7 7 7 7 7 7
*
*
*
*/
public static int GetNumberOfScanlinesInPass(ImageHeader header, int pass)
{
var indices = PassToScanlineGridIndex[pass + 1];
var mod = header.Height % 8;
var fitsExactly = mod == 0;
if (fitsExactly)
{
return indices.Length * (header.Height / 8);
}
var additionalLines = 0;
for (var i = 0; i < indices.Length; i++)
{
if (indices[i] < mod)
{
additionalLines++;
}
}
return (indices.Length * (header.Height / 8)) + additionalLines;
}
public static int GetPixelsPerScanlineInPass(ImageHeader header, int pass)
{
var indices = PassToScanlineColumnIndex[pass + 1];
var mod = header.Width % 8;
var fitsExactly = mod == 0;
if (fitsExactly)
{
return indices.Length * (header.Width / 8);
}
var additionalColumns = 0;
for (int i = 0; i < indices.Length; i++)
{
if (indices[i] < mod)
{
additionalColumns++;
}
}
return (indices.Length * (header.Width / 8)) + additionalColumns;
}
public static (int x, int y) GetPixelIndexForScanlineInPass(ImageHeader header, int pass, int scanlineIndex, int indexInScanline)
{
var columnIndices = PassToScanlineColumnIndex[pass + 1];
var rows = PassToScanlineGridIndex[pass + 1];
var actualRow = scanlineIndex % rows.Length;
var actualCol = indexInScanline % columnIndices.Length;
var precedingRows = 8 * (scanlineIndex / rows.Length);
var precedingCols = 8 * (indexInScanline / columnIndices.Length);
return (precedingCols + columnIndices[actualCol], precedingRows + rows[actualRow]);
}
}
} | 32.745614 | 137 | 0.478971 | [
"Apache-2.0"
] | BobLd/PdfP | src/UglyToad.PdfPig/Images/Png/Adam7.cs | 3,735 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Web.V20180201
{
public static class GetWebAppFunction
{
/// <summary>
/// Function information.
/// </summary>
public static Task<GetWebAppFunctionResult> InvokeAsync(GetWebAppFunctionArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetWebAppFunctionResult>("azure-nextgen:web/v20180201:getWebAppFunction", args ?? new GetWebAppFunctionArgs(), options.WithVersion());
}
public sealed class GetWebAppFunctionArgs : Pulumi.InvokeArgs
{
/// <summary>
/// Function name.
/// </summary>
[Input("functionName", required: true)]
public string FunctionName { get; set; } = null!;
/// <summary>
/// Site name.
/// </summary>
[Input("name", required: true)]
public string Name { get; set; } = null!;
/// <summary>
/// Name of the resource group to which the resource belongs.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
public GetWebAppFunctionArgs()
{
}
}
[OutputType]
public sealed class GetWebAppFunctionResult
{
/// <summary>
/// Config information.
/// </summary>
public readonly object? Config;
/// <summary>
/// Config URI.
/// </summary>
public readonly string? ConfigHref;
/// <summary>
/// File list.
/// </summary>
public readonly ImmutableDictionary<string, string>? Files;
/// <summary>
/// Function App ID.
/// </summary>
public readonly string? FunctionAppId;
/// <summary>
/// Function URI.
/// </summary>
public readonly string? Href;
/// <summary>
/// Resource Id.
/// </summary>
public readonly string Id;
/// <summary>
/// The invocation URL
/// </summary>
public readonly string? InvokeUrlTemplate;
/// <summary>
/// Value indicating whether the function is disabled
/// </summary>
public readonly bool? IsDisabled;
/// <summary>
/// Kind of resource.
/// </summary>
public readonly string? Kind;
/// <summary>
/// The function language
/// </summary>
public readonly string? Language;
/// <summary>
/// Resource Name.
/// </summary>
public readonly string Name;
/// <summary>
/// Script URI.
/// </summary>
public readonly string? ScriptHref;
/// <summary>
/// Script root path URI.
/// </summary>
public readonly string? ScriptRootPathHref;
/// <summary>
/// Secrets file URI.
/// </summary>
public readonly string? SecretsFileHref;
/// <summary>
/// Test data used when testing via the Azure Portal.
/// </summary>
public readonly string? TestData;
/// <summary>
/// Test data URI.
/// </summary>
public readonly string? TestDataHref;
/// <summary>
/// Resource type.
/// </summary>
public readonly string Type;
[OutputConstructor]
private GetWebAppFunctionResult(
object? config,
string? configHref,
ImmutableDictionary<string, string>? files,
string? functionAppId,
string? href,
string id,
string? invokeUrlTemplate,
bool? isDisabled,
string? kind,
string? language,
string name,
string? scriptHref,
string? scriptRootPathHref,
string? secretsFileHref,
string? testData,
string? testDataHref,
string type)
{
Config = config;
ConfigHref = configHref;
Files = files;
FunctionAppId = functionAppId;
Href = href;
Id = id;
InvokeUrlTemplate = invokeUrlTemplate;
IsDisabled = isDisabled;
Kind = kind;
Language = language;
Name = name;
ScriptHref = scriptHref;
ScriptRootPathHref = scriptRootPathHref;
SecretsFileHref = secretsFileHref;
TestData = testData;
TestDataHref = testDataHref;
Type = type;
}
}
}
| 27.767045 | 188 | 0.541436 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Web/V20180201/GetWebAppFunction.cs | 4,887 | C# |
// SampSharp
// Copyright 2020 Tim Potze
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using SampSharp.Entities.SAMP.Commands.Parsers;
using SampSharp.Entities.Utilities;
namespace SampSharp.Entities.SAMP.Commands
{
/// <summary>
/// Represents a base for service which provides functionality for calling commands in system classes.
/// </summary>
public abstract class CommandServiceBase
{
private readonly IEntityManager _entityManager;
private readonly int _prefixParameters;
private readonly Dictionary<string, List<CommandData>> _commands = new Dictionary<string, List<CommandData>>();
/// <inheritdoc />
protected CommandServiceBase(IEntityManager entityManager, int prefixParameters)
{
if (prefixParameters < 0) throw new ArgumentOutOfRangeException(nameof(prefixParameters));
_entityManager = entityManager;
_prefixParameters = prefixParameters;
CreateCommandsFromAssemblies(prefixParameters);
}
/// <summary>
/// Validates and corrects the specified <paramref name="inputText" />.
/// </summary>
/// <param name="inputText">The text to validate. The text can be corrected to remove symbols which should not be processed.</param>
/// <returns><c>true</c> if the inputText text is valid.</returns>
protected virtual bool ValidateInputText(ref string inputText)
{
return !string.IsNullOrEmpty(inputText);
}
/// <summary>
/// Invokes a command based on the specified <paramref name="inputText"/>.
/// </summary>
/// <param name="services">A service provider.</param>
/// <param name="prefix">The prefix.</param>
/// <param name="inputText">The inputText.</param>
/// <returns>The result</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="prefix"/> is null when it must contain values.</exception>
/// <exception cref="ArgumentException">Thrown if <paramref name="prefix"/> is empty when it must contain values.</exception>
protected InvokeResult Invoke(IServiceProvider services, object[] prefix, string inputText)
{
if (_prefixParameters > 0 && prefix == null)
throw new ArgumentNullException(nameof(prefix));
if (_prefixParameters > 0 && prefix.Length != _prefixParameters)
throw new ArgumentException($"The prefix must contain {_prefixParameters} values.", nameof(prefix));
if (!ValidateInputText(ref inputText))
return InvokeResult.CommandNotFound;
// Find name of the command by the first word
var index = inputText.IndexOf(" ", StringComparison.InvariantCulture);
var name = index < 0 ? inputText : inputText.Substring(0, index);
var result = false;
var invalidParameters = false;
// TODO: Commands in groups would have spaces in them, the logic above would not work.
// Skip command name in inputText for the command
inputText = inputText.Substring(name.Length);
// Find commands with the name
if (!_commands.TryGetValue(name, out var commands))
return InvokeResult.CommandNotFound;
foreach (var command in commands)
{
var cmdInput = inputText;
// Parse the command arguments using the parsers provided by the command
var accept = true;
var useDefaultValue = false;
for (var i = 0; i < command.Info.Parameters.Length; i++)
{
var parameter = command.Info.Parameters[i];
if (useDefaultValue)
{
command.Arguments[i + _prefixParameters] = parameter.DefaultValue;
continue;
}
if (parameter.Parser.TryParse(services, ref cmdInput, out command.Arguments[i + _prefixParameters]))
continue;
if (parameter.IsRequired)
{
accept = false;
break;
}
useDefaultValue = true;
command.Arguments[i + _prefixParameters] = parameter.DefaultValue;
}
// If parsing succeeded, invoke the command
if (accept)
{
if (_prefixParameters > 0)
Array.Copy(prefix, command.Arguments, _prefixParameters);
if (services.GetService(command.SystemType) is ISystem system)
{
var commandResult = command.Invoke(system, command.Arguments, services, _entityManager);
// Check if execution was successful
if (!(commandResult is bool bResult && !bResult) &&
!(commandResult is int iResult && iResult == 0)) result = true;
}
}
else
{
invalidParameters = true;
}
Array.Clear(command.Arguments, 0, command.Arguments.Length);
if (result)
return InvokeResult.Success;
}
if (!invalidParameters)
return InvokeResult.CommandNotFound;
var usageMessage = GetUsageMessage(commands.Select(c => c.Info).ToArray());
return new InvokeResult(InvokeResponse.InvalidArguments, usageMessage);
}
/// <summary>
/// Scans for methods in <see cref="ISystem"/> which should be considered to be compiled as a command.
/// </summary>
/// <param name="scanner">A scanner which is already limited to members of types which implement <see cref="ISystem"/>.</param>
/// <returns>The methods which provide commands.</returns>
protected abstract IEnumerable<(MethodInfo method, ICommandMethodInfo commandInfo)> ScanMethods(
AssemblyScanner scanner);
private IEnumerable<(MethodInfo method, ICommandMethodInfo commandInfo)> ScanMethods()
{
var scanner = new AssemblyScanner()
.IncludeAllAssemblies()
.IncludeNonPublicMembers()
.Implements<ISystem>();
return ScanMethods(scanner);
}
private static string CommandText(CommandInfo command)
{
return command.Parameters.Length == 0
? $"Usage: {command.Name}"
: $"Usage: {command.Name} " + string.Join(" ",
command.Parameters.Select(arg => arg.IsRequired ? $"[{arg.Name}]" : $"<{arg.Name}>"));
}
/// <summary>
/// Gets the usage message for one or multiple specified <paramref name="commands"/>.
/// </summary>
/// <param name="commands">The commands to get the usage message for. If multiple commands are supplied they can be assumed to be multiple overloads of the same command.</param>
/// <returns>The usage message for the commands.</returns>
protected virtual string GetUsageMessage(CommandInfo[] commands)
{
return commands.Length == 1
? CommandText(commands[0])
: $"Usage: {string.Join(" -or- ", commands.Select(CommandText))}";
}
/// <summary>
/// Creates the parameter parser for the parameter at the specified <paramref name="index"/> in the <paramref name="parameters"/> array..
/// </summary>
/// <param name="parameters">An array which contains all parameters.</param>
/// <param name="index">The index of the parameter to get the parser for.</param>
/// <returns>A newly created parameter parser or null if no parser could be made for the specified parameter.</returns>
protected virtual ICommandParameterParser CreateParameterParser(ParameterInfo[] parameters, int index)
{
var parameter = parameters[index];
if(parameter.ParameterType == typeof(int))
return new IntParser();
if (parameter.ParameterType == typeof(string))
return index == parameters.Length - 1
? (ICommandParameterParser) new StringParser()
: new WordParser();
if(parameter.ParameterType == typeof(float))
return new FloatParser();
if(parameter.ParameterType == typeof(double))
return new DoubleParser();
if(parameter.ParameterType == typeof(Player))
return new PlayerParser();
if(parameter.ParameterType == typeof(Vehicle))
return new EntityParser(SampEntities.VehicleType);
return parameter.ParameterType.IsEnum
? new EnumParser(parameter.ParameterType)
: null;
}
/// <summary>
/// Tries to collect parameter information.
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <param name="prefixParameters">The number of prefix parameters.</param>
/// <param name="result">The collected parameter information.</param>
/// <returns><c>true</c> if the parameters could be collected; otherwise <c>false</c>.</returns>
protected virtual bool TryCollectParameters(ParameterInfo[] parameters, int prefixParameters, out CommandParameterInfo[] result)
{
if (parameters.Length < prefixParameters)
{
result = null;
return false;
}
var list = new List<CommandParameterInfo>();
// Parameter index in intermediate parameters array between parsing and invoking.
var parameterIndex = prefixParameters;
var optionalFound = false;
for (var i = prefixParameters; i < parameters.Length; i++)
{
var parameter = parameters[i];
var attribute = parameter.GetCustomAttribute<CommandParameterAttribute>();
var name = parameter.Name;
ICommandParameterParser parser = null;
if (!string.IsNullOrWhiteSpace(attribute?.Name))
name = attribute.Name;
// Prefer parser supplied by parameter attribute
if (attribute?.Parser != null && typeof(ICommandParameterParser).IsAssignableFrom(attribute.Parser))
parser = Activator.CreateInstance(attribute.Parser) as ICommandParameterParser;
if (parser == null)
parser = CreateParameterParser(parameters, i);
if (parser == null)
{
// The parameter is injected by DI.
parameterIndex++;
continue;
}
var optional = parameter.HasDefaultValue;
// Don't allow required parameters after optional parameters.
if (!optional && optionalFound)
{
result = null;
return false;
}
optionalFound |= optional;
list.Add(new CommandParameterInfo(name, parser, !optional, parameter.DefaultValue, parameterIndex++));
}
result = list.ToArray();
return true;
}
/// <summary>
/// Extracts a command name from a method.
/// </summary>
/// <param name="method">The method to extract the command name from.</param>
/// <returns>The extracted command name.</returns>
protected virtual string GetCommandName(MethodInfo method)
{
var name = method.Name.ToLowerInvariant();
if (name.EndsWith("command"))
name = name.Substring(0, name.Length - 7);
return name;
}
private void CreateCommandsFromAssemblies(int prefixParameters)
{
var methods = ScanMethods();
foreach (var (method, commandInfo) in methods)
{
// Determine command name.
var name = commandInfo.Name ?? GetCommandName(method);
if (name == null)
continue;
// Validate acceptable return type.
if (method.ReturnType != typeof(bool) &&
method.ReturnType != typeof(int) &&
method.ReturnType != typeof(void))
continue;
var methodParameters = method.GetParameters();
// Determine command parameter types.
if (!TryCollectParameters(methodParameters, prefixParameters, out var parameters))
continue;
var info = new CommandInfo(name, parameters);
var argsPtr = 0; // The current pointer in the event arguments array.
var parameterSources = methodParameters
.Select(inf => new MethodParameterSource(inf))
.ToArray();
// Determine the source of each parameter.
for (var i = 0; i < parameterSources.Length; i++)
{
var source = parameterSources[i];
var type = source.Info.ParameterType;
if (typeof(Component).IsAssignableFrom(type))
{
// Components are provided by the entity in the arguments array of the event.
source.ParameterIndex = argsPtr++;
source.IsComponent = true;
}
else if (info.Parameters.FirstOrDefault(p => p.Index == i) != null)
{
// Default types are passed straight trough.
source.ParameterIndex = argsPtr++;
}
else
{
// Other types are provided trough Dependency Injection.
source.IsService = true;
}
}
var data = new CommandData
{
Arguments = new object[info.Parameters.Length + prefixParameters],
Info = info,
Invoke = MethodInvokerFactory.Compile(method, parameterSources, false),
SystemType = method.DeclaringType
};
if (!_commands.TryGetValue(info.Name, out var lst))
lst = _commands[info.Name] = new List<CommandData>();
lst.Add(data);
}
}
private class CommandData
{
public object[] Arguments;
public CommandInfo Info;
public MethodInvoker Invoke;
public Type SystemType;
}
}
} | 41.573684 | 185 | 0.56178 | [
"Apache-2.0"
] | BlasterDv/SampSharp | src/SampSharp.Entities/SAMP/Commands/CommandServiceBase.cs | 15,800 | C# |
/*************************************************************************
* Copyright © 2017-2018 Mogoson. All rights reserved.
*------------------------------------------------------------------------
* File : LimitCrankEditor.cs
* Description : Custom editor for LimitCrank.
*------------------------------------------------------------------------
* Author : Mogoson
* Version : 1.0
* Date : 4/11/2018
* Description : Initial development version.
*************************************************************************/
using UnityEditor;
using UnityEngine;
namespace MGS.Machinery
{
[CustomEditor(typeof(LimitCrank), true)]
[CanEditMultipleObjects]
public class LimitCrankEditor : FreeCrankEditor
{
#region Field and Property
protected new LimitCrank Target { get { return target as LimitCrank; } }
#endregion
#region Protected Method
protected override void DrawArea()
{
var minAxis = Quaternion.AngleAxis(Target.range.min, Axis) * ZeroAxis;
var maxAxis = Quaternion.AngleAxis(Target.range.max, Axis) * ZeroAxis;
Handles.color = TransparentBlue;
Handles.DrawSolidArc(Target.transform.position, Axis, minAxis, Target.range.max - Target.range.min, FixedAreaRadius);
Handles.color = Blue;
DrawSphereArrow(Target.transform.position, minAxis, FixedArrowLength, NodeSize, "Min");
DrawSphereArrow(Target.transform.position, maxAxis, FixedArrowLength, NodeSize, "Max");
}
#endregion
#region Public Method
public override void OnInspectorGUI()
{
EditorGUI.BeginChangeCheck();
DrawDefaultInspector();
if (EditorGUI.EndChangeCheck())
{
Target.range.max = Mathf.Clamp(Target.range.max, Target.range.min, float.MaxValue);
}
}
#endregion
}
} | 37.320755 | 129 | 0.530334 | [
"Apache-2.0"
] | mogoson/CodeProject | MachineryEditor/Crank/LimitCrankEditor.cs | 1,981 | C# |
// <copyright file="CloneableStream.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
namespace Microsoft.Azure.Networking.Infrastructure.RingMaster.Backend.HelperTypes
{
using System;
using System.IO;
/// <summary>
/// Class CloneableStream abstracts a stream that can be cloned
/// </summary>
public class CloneableStream : Stream, ICloneableStream
{
/// <summary>
/// The function to obtain a clone
/// </summary>
private readonly Func<Stream> getClone;
/// <summary>
/// The stream instance that can be cloned
/// </summary>
private Stream stream;
/// <summary>
/// Initializes a new instance of the <see cref="CloneableStream"/> class.
/// </summary>
/// <param name="getClone">The function to clone the stream.</param>
public CloneableStream(Func<Stream> getClone)
: this(getClone?.Invoke(), getClone)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CloneableStream"/> class.
/// </summary>
/// <param name="thisStream">The instance for the stream.</param>
/// <param name="getClone">The function to clone the stream</param>
/// <exception cref="System.ArgumentNullException">getClone</exception>
public CloneableStream(Stream thisStream, Func<Stream> getClone)
{
if (thisStream == null)
{
throw new ArgumentNullException(nameof(thisStream));
}
if (getClone == null)
{
throw new ArgumentNullException(nameof(getClone));
}
this.getClone = getClone;
this.stream = thisStream;
}
/// <summary>
/// Gets a value indicating whether the current stream supports reading when overridden in a derived class
/// </summary>
/// <value><c>true</c> if this instance can read; otherwise, <c>false</c>.</value>
public override bool CanRead => this.stream.CanRead;
/// <summary>
/// Gets a value indicating whether the current stream supports seeking when overridden in a derived class
/// </summary>
/// <value><c>true</c> if this instance can seek; otherwise, <c>false</c>.</value>
public override bool CanSeek => this.stream.CanSeek;
/// <summary>
/// Gets a value indicating whether the current stream supports writing when overridden in a derived class
/// </summary>
/// <value><c>true</c> if this instance can write; otherwise, <c>false</c>.</value>
public override bool CanWrite => this.stream.CanWrite;
/// <summary>
/// Gets the length in bytes of the stream when overridden in a derived class
/// </summary>
/// <value>The length.</value>
public override long Length => this.stream.Length;
/// <summary>
/// Gets or sets the position within the current stream when overridden in a derived class
/// </summary>
/// <value>The position.</value>
public override long Position
{
get
{
return this.stream.Position;
}
set
{
this.Seek(value, SeekOrigin.Begin);
}
}
/// <summary>
/// Clones the stream.
/// </summary>
/// <returns>cloned Stream</returns>
public Stream CloneStream()
{
return new CloneableStream(this.getClone(), this.getClone);
}
/// <summary>
/// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.
/// </summary>
public override void Flush()
{
this.stream.Flush();
}
/// <summary>
/// Reads the specified buffer.
/// </summary>
/// <param name="buffer">The buffer.</param>
/// <param name="offset">The offset.</param>
/// <param name="count">The count.</param>
/// <returns>System.Int32.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
return this.stream.Read(buffer, offset, count);
}
/// <summary>
/// When overridden in a derived class, sets the position within the current stream.
/// </summary>
/// <param name="offset">A byte offset relative to the <paramref name="origin" /> parameter.</param>
/// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin" /> indicating the reference point used to obtain the new position.</param>
/// <returns>The new position within the current stream.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
return this.stream.Seek(offset, origin);
}
/// <summary>
/// When overridden in a derived class, sets the length of the current stream.
/// </summary>
/// <param name="value">The desired length of the current stream in bytes.</param>
public override void SetLength(long value)
{
this.stream.SetLength(value);
}
/// <summary>
/// Writes the specified buffer.
/// </summary>
/// <param name="buffer">The buffer.</param>
/// <param name="offset">The offset.</param>
/// <param name="count">The count.</param>
public override void Write(byte[] buffer, int offset, int count)
{
this.stream.Write(buffer, offset, count);
}
/// <summary>
/// Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. Instead of calling this method, ensure that the stream is properly disposed.
/// </summary>
public override void Close()
{
this.stream?.Close();
this.stream = null;
base.Close();
}
}
} | 36.982036 | 212 | 0.574806 | [
"MIT"
] | Azure/RingMaster | src/Backend/HelperTypes/src/CloneableStream.cs | 6,178 | C# |
#if REGEX
using System.Text.RegularExpressions;
namespace AtraBase.Toolkit.Extensions;
/// <summary>
/// Adds some LINQ-esque methods to the Regex class.
/// </summary>
public static class RegexExtensions
{
/// <summary>
/// Converts a Match with named matchgroups into a dictionary.
/// </summary>
/// <param name="match">Regex matchgroup.</param>
/// <param name="namedOnly">Whether or not to only use named groups.</param>
/// <returns>Dictionary with the name of the matchgroup as the key and the value as the value.</returns>
[Pure]
public static Dictionary<string, string> MatchGroupsToDictionary(this Match match, bool namedOnly = true)
{
Dictionary<string, string> result = new();
foreach (Group group in match.Groups)
{
// Microsoft doesn't really give a better way to exclude unnamed groups, which are numbers as strings.
if (!namedOnly || !int.TryParse(group.Name, out _))
{
result[group.Name] = group.Value;
}
}
return result;
}
/// <summary>
/// Converts a Match with named matchgroups into a dictionary.
/// </summary>
/// <typeparam name="TKey">Type for key.</typeparam>
/// <typeparam name="TValue">Type for value.</typeparam>
/// <param name="match">Match with named matchgroups.</param>
/// <param name="keyselector">Function to apply to all keys.</param>
/// <param name="valueselector">Function to apply to all values.</param>
/// <param name="namedOnly">Whether or not to only use named groups.</param>
/// <returns>The dictionary.</returns>
[Pure]
public static Dictionary<TKey, TValue> MatchGroupsToDictionary<TKey, TValue>(
this Match match,
Func<string, TKey> keyselector,
Func<string, TValue> valueselector,
bool namedOnly = true)
where TKey : notnull
{
Dictionary<TKey, TValue> result = new();
foreach (Group group in match.Groups)
{
// Microsoft doesn't really give a better way to exclude unnamed groups, which are numbers as strings.
if (!namedOnly || !int.TryParse(group.Name, out _))
{
result[keyselector(group.Name)] = valueselector(group.Value);
}
}
return result;
}
/// <summary>
/// Updates a dictionary with the values of a match group, if valid.
/// </summary>
/// <param name="dictionary">Dictionary to update.</param>
/// <param name="match">Match with named matchgroups.</param>
/// <param name="namedOnly">Whether or not to only use named groups.</param>
/// <returns>The dictionary (for chaining).</returns>
public static IDictionary<string, int> Update(
this IDictionary<string, int> dictionary,
Match? match,
bool namedOnly = true)
{
if (match is not null)
{
foreach (Group group in match.Groups)
{
// Microsoft doesn't really give a better way to exclude unnamed groups, which are numbers as strings.
if (!namedOnly || !int.TryParse(group.Name, out _))
{
if (int.TryParse(group.Value, out int val))
{
dictionary[group.Name] = val;
}
}
}
}
return dictionary;
}
}
#endif | 37.043011 | 118 | 0.594775 | [
"MIT"
] | atravita-mods/AtraBase | Toolkit/Extensions/RegexExtensions.cs | 3,447 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18051
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace StringConsumer.Console.ServiceReferenceString {
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="ServiceReferenceString.IServiceString")]
public interface IServiceString {
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IServiceString/NumberOfOccurences", ReplyAction="http://tempuri.org/IServiceString/NumberOfOccurencesResponse")]
int NumberOfOccurences(string first, string second);
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IServiceString/NumberOfOccurences", ReplyAction="http://tempuri.org/IServiceString/NumberOfOccurencesResponse")]
System.Threading.Tasks.Task<int> NumberOfOccurencesAsync(string first, string second);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public interface IServiceStringChannel : StringConsumer.Console.ServiceReferenceString.IServiceString, System.ServiceModel.IClientChannel {
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class ServiceStringClient : System.ServiceModel.ClientBase<StringConsumer.Console.ServiceReferenceString.IServiceString>, StringConsumer.Console.ServiceReferenceString.IServiceString {
public ServiceStringClient() {
}
public ServiceStringClient(string endpointConfigurationName) :
base(endpointConfigurationName) {
}
public ServiceStringClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public ServiceStringClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public ServiceStringClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress) {
}
public int NumberOfOccurences(string first, string second) {
return base.Channel.NumberOfOccurences(first, second);
}
public System.Threading.Tasks.Task<int> NumberOfOccurencesAsync(string first, string second) {
return base.Channel.NumberOfOccurencesAsync(first, second);
}
}
}
| 49.327869 | 203 | 0.680292 | [
"MIT"
] | niki-funky/Telerik_Academy | Web Development/Web_and_Cloud/03. WCF/05. WCF/05. StringConsumer.Console/Service References/ServiceReferenceString/Reference.cs | 3,011 | C# |
using app.Operations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace app.Parser
{
public class AlienMessageParser
{
public static Dictionary<string, IToken> Variables = new Dictionary<string, IToken>();
public static Dictionary<IToken, IToken> ReducedCache = new Dictionary<IToken, IToken>();
private List<string[]> _lines;
public AlienMessageParser(string message)
{
_lines = message.Split(
new[] { "\r\n", "\r", "\n" },
StringSplitOptions.None
).Select(x => x.Split(" ", StringSplitOptions.RemoveEmptyEntries)).ToList();
}
public IToken interactToken;
public static IToken lastInteractResult;
public IToken Interact(int x, int y)
{
System.Diagnostics.Trace.WriteLine($"Interact({x}, {y});");
var t = new Thread(() =>
{
interactToken = Reduce(ApOperator.Acquire(interactToken, ConsOperator.Acquire(ConstantOperator.Acquire(x), ConstantOperator.Acquire(y))));
}, 1024 * 1024 * 1024);
t.Start();
t.Join();
ClearCaches();
GC.Collect();
GC.WaitForPendingFinalizers();
return lastInteractResult;
}
public IToken SkipToUniverse()
{
Interact(0, 0);
Interact(0, 0);
Interact(0, 0);
Interact(0, 0);
Interact(0, 0);
Interact(0, 0);
Interact(0, 0);
Interact(0, 0);
Interact(8, 4);
Interact(2, -8);
Interact(3, 6);
Interact(0, -14);
Interact(-4, 10);
Interact(9, -3);
Interact(-4, 10);
return Interact(1, 4);
}
public static void ClearCaches()
{
ReducedCache.Clear();
BComb.Cache.Clear();
CComb.Cache.Clear();
SComb.Cache.Clear();
KComb.Cache.Clear();
ApOperator.Cache.Clear();
ConsOperator.Cache.Clear();
LateBoundToken.Cache.Clear();
DivOperator.Cache.Clear();
MulOperator.Cache.Clear();
AddOperator.Cache.Clear();
EqOperator.Cache.Clear();
LtOperator.Cache.Clear();
ConstantOperator.Cache.Clear();
VarOperator.Cache.Clear();
}
public void Eval()
{
foreach (var line in _lines.Take(_lines.Count - 1))
{
ParseLine(line);
}
var t = new Thread(() =>
{
foreach (var key in Variables.Keys.OrderBy(x => x).ToList())
{
Console.WriteLine($"precompiling {key}");
Variables[key] = Reduce(Variables[key]);
}
}, 1024 * 1024 * 1024);
t.Start();
t.Join();
var last = ParseTokens(_lines.Last().Skip(2).ToArray());
interactToken = Reduce(last);
}
public void ParseLine(string[] ops)
{
if (ops[0].StartsWith(":")) // variable assignment
{
Variables[ops[0]] = ParseTokens(ops.Skip(2).ToArray());
}
}
public static IToken Reduce(IToken token)
{
if (token == null)
return null;
//if (name != null)
// Console.WriteLine($" Reducing {name}");
if (ReducedCache.ContainsKey(token))
return ReducedCache[token];
Stack<IToken> stack = new Stack<IToken>();
if (token is LateBoundToken t)
return Reduce(Variables[t.Id]);
if (token is ApOperator ap)
{
stack.Push(ap.x);
stack.Push(ap.f);
}
else
{
return token;
}
while (stack.Count > 1)
{
var f = stack.Pop();
if (f is ApOperator ff)
{
stack.Push(ff.x);
stack.Push(ff.f);
continue;
}
var x = stack.Pop();
if (f.SkipRight)
{
stack.Push(f.Apply(null));
continue;
}
if (f.SkipLeft)
{
stack.Push(x); // wrong?
continue;
}
while (f is LateBoundToken lb)
f = Reduce(Variables[lb.Id]);
while (x is LateBoundToken lx)
x = Reduce(Variables[lx.Id]);
stack.Push(f.Apply(x));
}
var bleh = stack.Pop();
if (bleh is ApOperator woot)
{
var reduced = Reduce(woot);
ReducedCache[token] = reduced;
return reduced;
}
ReducedCache[token] = bleh;
return bleh;
}
public IToken ParseTokens(string[] ops)
{
var stack = new Stack<ApOperator>();
IToken token = null;
for (int i = 0; i < ops.Length; i++)
{
var op = ops[i];
switch (op)
{
case "ap":
token = new ApOperator();
break;
case "inc":
token = IncOperator.Acquire();
break;
case "dec":
token = DecOperator.Acquire();
break;
case "neg":
token = NegOperator.Acquire();
break;
case "add":
token = AddOperator.Acquire();
break;
case "mul":
token = MulOperator.Acquire();
break;
//case "l":
// token = new LOperator();
// break;
case "div":
token = DivOperator.Acquire();
break;
//case "pwr2":
// return (new Pwr2Operator(), index);
case "t":
token = KComb.Acquire();
break;
//case "f":
// return (new FComb(), index);
case "s":
token = SComb.Acquire();
break;
case "c":
token = CComb.Acquire();
break;
case "b":
token = BComb.Acquire();
break;
case "i":
token = IComb.Acquire();
break;
case "cons":
case "vec":
token = ConsOperator.Acquire();
break;
case "car":
token = CarOperator.Acquire();
break;
case "cdr":
token = CdrOperator.Acquire();
break;
case "nil":
token = NilOperator.Acquire();
break;
case "isnil":
token = IsNilOperator.Acquire();
break;
case "eq":
token = EqOperator.Acquire();
break;
case "if0":
token = new If0Operator();
break;
case "lt":
token = LtOperator.Acquire();
break;
//case "mod":
// token = new ModOperator();
// break;
//case "dem":
// token = new DemodOperator();
// break;
case "interact":
token = new InteractOperator();
break;
default:
if (decimal.TryParse(op, out var constant)) // int constant
{
token = ConstantOperator.Acquire(decimal.Parse(op));
}
else if (op.StartsWith("x"))
{
token = VarOperator.Acquire(op);
}
else if (op.StartsWith(":")) // variable reference
{
token = LateBoundToken.Acquire(op);
}
else
throw new InvalidOperationException();
break;
}
if (stack.Count == 0)
{
if (!(token is ApOperator))
{
if (i != ops.Length - 1)
throw new InvalidOperationException();
return token;
}
stack.Push((ApOperator)token);
}
else
{
var top = stack.Peek();
if (top.f == null)
{
top.f = token;
if (token is ApOperator ap)
stack.Push(ap);
}
else if (top.x == null)
{
top.x = token;
if (token is ApOperator ap)
stack.Push(ap);
else
while (stack.Count > 0 && stack.Peek().x != null)
{
token = stack.Pop();
}
}
else
throw new InvalidOperationException();
}
}
if (stack.Count == 1)
return stack.Pop();
return token;
}
}
} | 29.030055 | 154 | 0.368282 | [
"MIT"
] | tstivers/icfp2020 | app/Parser/AlienMessageParser.cs | 10,627 | C# |
using System;
using Nimbus.Configuration;
namespace Nimbus.Tests.Common.TestScenarioGeneration.ConfigurationSources.IoCContainers
{
public class ContainerConfiguration
{
public Func<BusBuilderConfiguration, BusBuilderConfiguration> ApplyContainerDefaults { get; set; }
}
} | 29.3 | 106 | 0.795222 | [
"MIT"
] | dicko2/Nimbus | src/Tests/Nimbus.Tests.Common/TestScenarioGeneration/ConfigurationSources/IoCContainers/ContainerConfiguration.cs | 293 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Utils
{
/// <summary>
/// 线程工具类
/// </summary>
public static class RunHelper
{
#region 变量属性事件
#endregion
#region 线程中执行
/// <summary>
/// 线程中执行
/// </summary>
public static Task Run(this TaskScheduler scheduler, Action<object> doWork, object arg = null, Action<Exception> errorAction = null)
{
return Task.Factory.StartNew((obj) =>
{
try
{
doWork(obj);
}
catch (Exception ex)
{
if (errorAction != null) errorAction(ex);
LogUtil.Error(ex, "RunHelper.Run错误");
}
}, arg, CancellationToken.None, TaskCreationOptions.None, scheduler);
}
#endregion
#region 线程中执行
/// <summary>
/// 线程中执行
/// </summary>
public static Task Run(this TaskScheduler scheduler, Action doWork, Action<Exception> errorAction = null)
{
return Task.Factory.StartNew(() =>
{
try
{
doWork();
}
catch (Exception ex)
{
if (errorAction != null) errorAction(ex);
LogUtil.Error(ex, "RunHelper.Run错误");
}
}, CancellationToken.None, TaskCreationOptions.None, scheduler);
}
#endregion
#region 线程中执行
/// <summary>
/// 线程中执行
/// </summary>
public static Task<T> Run<T>(this TaskScheduler scheduler, Func<object, T> doWork, object arg = null, Action<Exception> errorAction = null)
{
return Task.Factory.StartNew<T>((obj) =>
{
try
{
return doWork(obj);
}
catch (Exception ex)
{
if (errorAction != null) errorAction(ex);
LogUtil.Error(ex, "RunHelper.Run错误");
return default(T);
}
}, arg, CancellationToken.None, TaskCreationOptions.None, scheduler);
}
#endregion
#region 线程中执行
/// <summary>
/// 线程中执行
/// </summary>
public static Task<T> Run<T>(this TaskScheduler scheduler, Func<T> doWork, Action<Exception> errorAction = null)
{
return Task.Factory.StartNew<T>(() =>
{
try
{
return doWork();
}
catch (Exception ex)
{
if (errorAction != null) errorAction(ex);
LogUtil.Error(ex, "RunHelper.Run错误");
return default(T);
}
}, CancellationToken.None, TaskCreationOptions.None, scheduler);
}
#endregion
#region 线程中执行
/// <summary>
/// 线程中执行
/// </summary>
public static async Task<T> RunAsync<T>(this TaskScheduler scheduler, Func<object, T> doWork, object arg = null, Action<Exception> errorAction = null)
{
return await Task.Factory.StartNew<T>((obj) =>
{
try
{
return doWork(obj);
}
catch (Exception ex)
{
if (errorAction != null) errorAction(ex);
LogUtil.Error(ex, "RunHelper.RunAsync错误");
return default(T);
}
}, arg, CancellationToken.None, TaskCreationOptions.None, scheduler);
}
#endregion
#region 线程中执行
/// <summary>
/// 线程中执行
/// </summary>
public static async Task<T> RunAsync<T>(this TaskScheduler scheduler, Func<T> doWork, Action<Exception> errorAction = null)
{
return await Task.Factory.StartNew<T>(() =>
{
try
{
return doWork();
}
catch (Exception ex)
{
if (errorAction != null) errorAction(ex);
LogUtil.Error(ex, "RunHelper.RunAsync错误");
return default(T);
}
}, CancellationToken.None, TaskCreationOptions.None, scheduler);
}
#endregion
#region 线程中执行
/// <summary>
/// 线程中执行
/// </summary>
public static async Task RunAsync(this TaskScheduler scheduler, Action<object> doWork, object arg = null, Action<Exception> errorAction = null)
{
await Task.Factory.StartNew((obj) =>
{
try
{
doWork(obj);
}
catch (Exception ex)
{
if (errorAction != null) errorAction(ex);
LogUtil.Error(ex, "RunHelper.RunAsync错误");
}
}, arg, CancellationToken.None, TaskCreationOptions.None, scheduler);
}
#endregion
#region 线程中执行
/// <summary>
/// 线程中执行
/// </summary>
public static async Task RunAsync(this TaskScheduler scheduler, Action doWork, Action<Exception> errorAction = null)
{
await Task.Factory.StartNew(() =>
{
try
{
doWork();
}
catch (Exception ex)
{
if (errorAction != null) errorAction(ex);
LogUtil.Error(ex, "RunHelper.RunAsync错误");
}
}, CancellationToken.None, TaskCreationOptions.None, scheduler);
}
#endregion
}
}
| 31.093264 | 158 | 0.459757 | [
"MIT"
] | 0611163/DBHelper | DBHelper/Utils/RunHelper.cs | 6,217 | C# |
using System;
using System.Collections.Generic;
using SocialMediaAuthentication.Services;
using UIKit;
using Xamarin.Auth;
namespace SocialMediaAuthentication.iOS.Services
{
public class iOSOAuth2Authenticator : OAuth2Authenticator
{
public iOSOAuth2Authenticator(string clientId, string scope, Uri authorizeUrl, Uri redirectUrl) : base(clientId, scope, authorizeUrl, redirectUrl)
{
}
protected override void OnPageEncountered(Uri url, IDictionary<string, string> query, IDictionary<string, string> fragment)
{
if (UrlMatchesRedirect(url))
base.OnPageEncountered(url, query, fragment);
}
}
public class OAuth2Service : IOAuth2Service
{
public event EventHandler<string> OnSuccess = delegate { };
public event EventHandler OnCancel = delegate { };
public event EventHandler<string> OnError = delegate { };
public void Authenticate(string clientId, string scope, Uri authorizeUrl, Uri redirectUrl)
{
var window = UIApplication.SharedApplication.KeyWindow;
var vc = window.RootViewController;
while (vc.PresentedViewController != null)
{
vc = vc.PresentedViewController;
}
var auth = new iOSOAuth2Authenticator(
clientId: clientId, // your OAuth2 client id
scope: scope, // the scopes for the particular API you're accessing, delimited by "+" symbols
authorizeUrl: authorizeUrl, // the auth URL for the service
redirectUrl: redirectUrl); // the redirect URL for the service
auth.AllowCancel = true;
auth.ShowErrors = false;
EventHandler<AuthenticatorErrorEventArgs> errorDelegate = null;
EventHandler<AuthenticatorCompletedEventArgs> completedDelegate = null;
errorDelegate = (sender, eventArgs) =>
{
OnError?.Invoke(this, eventArgs.Message);
auth.Error -= errorDelegate;
auth.Completed -= completedDelegate;
};
completedDelegate = (sender, eventArgs) => {
// UI presented, so it's up to us to dimiss it on iOS
// dismiss ViewController with UIWebView or SFSafariViewController
vc.DismissViewController(true, null);
if (eventArgs.IsAuthenticated)
{
OnSuccess?.Invoke(this, eventArgs.Account.Properties["access_token"]);
}
else
{
// The user cancelled
OnCancel?.Invoke(this, EventArgs.Empty);
}
auth.Error -= errorDelegate;
auth.Completed -= completedDelegate;
};
auth.Error += errorDelegate;
auth.Completed += completedDelegate;
vc.PresentViewController(auth.GetUI(), true, null);
}
}
}
| 32.319149 | 154 | 0.594799 | [
"MIT"
] | AbdulArif/SocialMediaAuthentication | SocialMediaAuthentication.iOS/Services/OAuth2Service.cs | 3,040 | C# |
namespace Paperspace
{
using Newtonsoft.Json;
public class MachineAvailability
{
[JsonProperty("available")]
public bool Available
{
get;
set;
}
}
}
| 14.866667 | 36 | 0.511211 | [
"MIT"
] | BaristaLabs/paperspace.net | src/Paperspace/Models/Response/MachineAvailability.cs | 225 | C# |
using System;
using System.Linq;
using Sandbox;
namespace MidAir.GameStates
{
public class BaseGameState
{
protected RealTimeSince stateStart;
public BaseGameState()
{
stateStart = 0;
}
public virtual string StateName() => GetType().ToString();
public virtual string StateTime()
{
var timeEndSpan = TimeSpan.FromSeconds( stateStart );
var minutes = timeEndSpan.Minutes;
var seconds = timeEndSpan.Seconds;
return $"{minutes:D2}:{seconds:D2}";
}
public virtual void Tick() { }
protected void SetState( BaseGameState newState )
{
(Game.Current as Game).CurrentState = newState;
}
protected int GetPlayerCount() => Client.All.Count();
public virtual void OnKill( Client attackerClient, Client victimClient ) { }
public virtual void OnDeath( Client cl ) { }
public virtual void OnPlayerJoin( Client cl ) { }
public virtual void OnPlayerLeave( Client cl ) { }
}
}
| 21.022727 | 78 | 0.703784 | [
"MIT"
] | rndtrash/sbox-midair | code/GameStates/BaseGameState.cs | 927 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace RealEstateAgency.Migrations
{
public partial class Propertyremovedfrombookofcomplaints : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_BookOfComplaints_Properties_PropertyId",
table: "BookOfComplaints");
migrationBuilder.DropIndex(
name: "IX_BookOfComplaints_PropertyId",
table: "BookOfComplaints");
migrationBuilder.DropColumn(
name: "PropertyId",
table: "BookOfComplaints");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "PropertyId",
table: "BookOfComplaints",
type: "int",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_BookOfComplaints_PropertyId",
table: "BookOfComplaints",
column: "PropertyId");
migrationBuilder.AddForeignKey(
name: "FK_BookOfComplaints_Properties_PropertyId",
table: "BookOfComplaints",
column: "PropertyId",
principalTable: "Properties",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}
| 32.866667 | 72 | 0.577417 | [
"MIT"
] | Tarik-Colakhodzic/Real-estate-agency | RealEstateAgency/RealEstateAgency/Migrations/20220111221452_Property removed from book of complaints.cs | 1,481 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace Projeto.Presentation.Models
{
public class UsuarioCadastroViewModel
{
[MinLength(3, ErrorMessage = "Informe no mínimo {1} caracteres.")]
[MaxLength(50, ErrorMessage = "Informe no máximo {1} caracteres.")]
[Required(ErrorMessage ="Informe o nome.")]
public string Nome { get; set; }
[EmailAddress(ErrorMessage = "Informe um endereço de email válido.")]
[Required(ErrorMessage = "Informe o e-mail.")]
public string Email { get; set; }
[Required(ErrorMessage = "Informe a permissão do usuário.")]
public string Permissao { get; set; }
[Required(ErrorMessage = "Informe o login.")]
public string Login { get; set; }
[Required(ErrorMessage = "Informe a senha.")]
public string Senha { get; set; }
[Compare("Senha", ErrorMessage ="Senhas não conferem.")]
[Required(ErrorMessage = "Confirme a senha.")]
public string SenhaConfirm { get; set; }
}
} | 32.257143 | 77 | 0.645704 | [
"MIT"
] | ArthurJohnsoon/Teste | Projeto.Presentation/Models/UsuarioCadastroViewModel.cs | 1,138 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace IdentityTest.Data.Migrations
{
public partial class CreateIdentitySchema : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
ConcurrencyStamp = table.Column<string>(nullable: true),
Name = table.Column<string>(maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(maxLength: 256, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
LoginProvider = table.Column<string>(nullable: false),
Name = table.Column<string>(nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false),
ConcurrencyStamp = table.Column<string>(nullable: true),
Email = table.Column<string>(maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
LockoutEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
PasswordHash = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
SecurityStamp = table.Column<string>(nullable: true),
TwoFactorEnabled = table.Column<bool>(nullable: false),
UserName = table.Column<string>(maxLength: 256, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(nullable: false),
ProviderKey = table.Column<string>(nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName");
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_UserId",
table: "AspNetUserRoles",
column: "UserId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}
| 42.027273 | 122 | 0.501839 | [
"MIT"
] | Microhive/GDPR-Consent-Tools | TestProjects/IdentityTest/Migrations/00000000000000_CreateIdentitySchema.cs | 9,248 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class TypeDeclarationSyntaxExtensions
{
public static TypeDeclarationSyntax AddMembers(
this TypeDeclarationSyntax node, params MemberDeclarationSyntax[] members)
{
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
return ((ClassDeclarationSyntax)node).AddMembers(members);
case SyntaxKind.InterfaceDeclaration:
return ((InterfaceDeclarationSyntax)node).AddMembers(members);
case SyntaxKind.StructDeclaration:
return ((StructDeclarationSyntax)node).AddMembers(members);
default:
throw ExceptionUtilities.UnexpectedValue(node.Kind());
}
}
public static TypeDeclarationSyntax WithMembers(
this TypeDeclarationSyntax node, SyntaxList<MemberDeclarationSyntax> members)
{
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
return ((ClassDeclarationSyntax)node).WithMembers(members);
case SyntaxKind.InterfaceDeclaration:
return ((InterfaceDeclarationSyntax)node).WithMembers(members);
case SyntaxKind.StructDeclaration:
return ((StructDeclarationSyntax)node).WithMembers(members);
default:
throw ExceptionUtilities.UnexpectedValue(node.Kind());
}
}
public static TypeDeclarationSyntax WithAttributeLists(
this TypeDeclarationSyntax node, SyntaxList<AttributeListSyntax> attributes)
{
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
return ((ClassDeclarationSyntax)node).WithAttributeLists(attributes);
case SyntaxKind.InterfaceDeclaration:
return ((InterfaceDeclarationSyntax)node).WithAttributeLists(attributes);
case SyntaxKind.StructDeclaration:
return ((StructDeclarationSyntax)node).WithAttributeLists(attributes);
default:
throw ExceptionUtilities.UnexpectedValue(node.Kind());
}
}
public static TypeDeclarationSyntax WithIdentifier(
this TypeDeclarationSyntax node, SyntaxToken identifier)
{
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
return ((ClassDeclarationSyntax)node).WithIdentifier(identifier);
case SyntaxKind.InterfaceDeclaration:
return ((InterfaceDeclarationSyntax)node).WithIdentifier(identifier);
case SyntaxKind.StructDeclaration:
return ((StructDeclarationSyntax)node).WithIdentifier(identifier);
default:
throw ExceptionUtilities.UnexpectedValue(node.Kind());
}
}
public static TypeDeclarationSyntax WithModifiers(
this TypeDeclarationSyntax node, SyntaxTokenList modifiers)
{
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
return ((ClassDeclarationSyntax)node).WithModifiers(modifiers);
case SyntaxKind.InterfaceDeclaration:
return ((InterfaceDeclarationSyntax)node).WithModifiers(modifiers);
case SyntaxKind.StructDeclaration:
return ((StructDeclarationSyntax)node).WithModifiers(modifiers);
default:
throw ExceptionUtilities.UnexpectedValue(node.Kind());
}
}
public static TypeDeclarationSyntax WithTypeParameterList(
this TypeDeclarationSyntax node, TypeParameterListSyntax list)
{
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
return ((ClassDeclarationSyntax)node).WithTypeParameterList(list);
case SyntaxKind.InterfaceDeclaration:
return ((InterfaceDeclarationSyntax)node).WithTypeParameterList(list);
case SyntaxKind.StructDeclaration:
return ((StructDeclarationSyntax)node).WithTypeParameterList(list);
default:
throw ExceptionUtilities.UnexpectedValue(node.Kind());
}
}
public static TypeDeclarationSyntax WithBaseList(
this TypeDeclarationSyntax node, BaseListSyntax list)
{
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
return ((ClassDeclarationSyntax)node).WithBaseList(list);
case SyntaxKind.InterfaceDeclaration:
return ((InterfaceDeclarationSyntax)node).WithBaseList(list);
case SyntaxKind.StructDeclaration:
return ((StructDeclarationSyntax)node).WithBaseList(list);
default:
throw ExceptionUtilities.UnexpectedValue(node.Kind());
}
}
public static TypeDeclarationSyntax WithConstraintClauses(
this TypeDeclarationSyntax node, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses)
{
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
return ((ClassDeclarationSyntax)node).WithConstraintClauses(constraintClauses);
case SyntaxKind.InterfaceDeclaration:
return ((InterfaceDeclarationSyntax)node).WithConstraintClauses(constraintClauses);
case SyntaxKind.StructDeclaration:
return ((StructDeclarationSyntax)node).WithConstraintClauses(constraintClauses);
default:
throw ExceptionUtilities.UnexpectedValue(node.Kind());
}
}
public static TypeDeclarationSyntax WithOpenBraceToken(
this TypeDeclarationSyntax node, SyntaxToken openBrace)
{
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
return ((ClassDeclarationSyntax)node).WithOpenBraceToken(openBrace);
case SyntaxKind.InterfaceDeclaration:
return ((InterfaceDeclarationSyntax)node).WithOpenBraceToken(openBrace);
case SyntaxKind.StructDeclaration:
return ((StructDeclarationSyntax)node).WithOpenBraceToken(openBrace);
default:
throw ExceptionUtilities.UnexpectedValue(node.Kind());
}
}
public static TypeDeclarationSyntax WithCloseBraceToken(
this TypeDeclarationSyntax node, SyntaxToken closeBrace)
{
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
return ((ClassDeclarationSyntax)node).WithCloseBraceToken(closeBrace);
case SyntaxKind.InterfaceDeclaration:
return ((InterfaceDeclarationSyntax)node).WithCloseBraceToken(closeBrace);
case SyntaxKind.StructDeclaration:
return ((StructDeclarationSyntax)node).WithCloseBraceToken(closeBrace);
default:
throw ExceptionUtilities.UnexpectedValue(node.Kind());
}
}
public static IList<bool> GetInsertionIndices(this TypeDeclarationSyntax destination, CancellationToken cancellationToken)
{
var members = destination.Members;
var indices = new List<bool>();
if (members.Count == 0)
{
var start = destination.OpenBraceToken.Span.End;
var end = GetEndToken(destination).SpanStart;
indices.Add(!destination.OverlapsHiddenPosition(TextSpan.FromBounds(start, end), cancellationToken));
}
else
{
var start = destination.OpenBraceToken.Span.End;
var end = destination.Members.First().SpanStart;
indices.Add(!destination.OverlapsHiddenPosition(TextSpan.FromBounds(start, end), cancellationToken));
for (int i = 0; i < members.Count - 1; i++)
{
var member1 = members[i];
var member2 = members[i + 1];
indices.Add(!destination.OverlapsHiddenPosition(member1, member2, cancellationToken));
}
start = members.Last().Span.End;
end = GetEndToken(destination).SpanStart;
indices.Add(!destination.OverlapsHiddenPosition(TextSpan.FromBounds(start, end), cancellationToken));
}
return indices;
}
private static SyntaxToken GetEndToken(SyntaxNode node)
{
var lastToken = node.GetLastToken(includeZeroWidth: true, includeSkipped: true);
if (lastToken.IsMissing)
{
var nextToken = lastToken.GetNextToken(includeZeroWidth: true, includeSkipped: true);
if (nextToken.RawKind != 0)
{
return nextToken;
}
}
return lastToken;
}
public static IEnumerable<BaseTypeSyntax> GetAllBaseListTypes(this TypeDeclarationSyntax typeNode, SemanticModel model, CancellationToken cancellationToken)
{
Contract.ThrowIfNull(typeNode);
IEnumerable<BaseTypeSyntax> baseListTypes = SpecializedCollections.EmptyEnumerable<BaseTypeSyntax>();
var isPartialType = typeNode.Modifiers.Any(m => m.Kind() == SyntaxKind.PartialKeyword);
if (isPartialType)
{
var typeSymbol = model.GetDeclaredSymbol(typeNode, cancellationToken);
if (typeSymbol != null)
{
foreach (var syntaxRef in typeSymbol.DeclaringSyntaxReferences)
{
var typeDecl = syntaxRef.GetSyntax(cancellationToken) as TypeDeclarationSyntax;
if (typeDecl != null && typeDecl.BaseList != null)
{
baseListTypes = baseListTypes.Concat(typeDecl.BaseList.Types);
}
}
}
}
else if (typeNode.BaseList != null)
{
return typeNode.BaseList.Types;
}
return baseListTypes;
}
private static SyntaxToken EnsureToken(SyntaxToken token, bool prependNewLineIfMissing = false, bool appendNewLineIfMissing = false)
{
if (token.IsMissing)
{
var leadingTrivia = prependNewLineIfMissing ? token.LeadingTrivia.Insert(0, SyntaxFactory.CarriageReturnLineFeed) : token.LeadingTrivia;
var trailingTrivia = appendNewLineIfMissing ? token.TrailingTrivia.Insert(0, SyntaxFactory.CarriageReturnLineFeed) : token.TrailingTrivia;
return SyntaxFactory.Token(leadingTrivia, token.Kind(), trailingTrivia).WithAdditionalAnnotations(Formatter.Annotation);
}
return token;
}
private static void EnsureAndGetBraceTokens(
BaseTypeDeclarationSyntax typeDeclaration,
bool hasMembers,
out SyntaxToken openBrace,
out SyntaxToken closeBrace)
{
openBrace = EnsureToken(typeDeclaration.OpenBraceToken);
closeBrace = EnsureToken(typeDeclaration.CloseBraceToken, appendNewLineIfMissing: true);
if (!hasMembers)
{
// Bug 539673: If there are no members, take any trivia that
// belongs to the end brace and attach it to the opening brace.
int index = -1;
var leadingTrivia = closeBrace.LeadingTrivia;
for (int i = leadingTrivia.Count - 1; i >= 0; i--)
{
if (!leadingTrivia[i].IsWhitespaceOrEndOfLine())
{
index = i;
break;
}
}
if (index != -1)
{
openBrace = openBrace.WithTrailingTrivia(
openBrace.TrailingTrivia.Concat(closeBrace.LeadingTrivia.Take(index + 1)));
closeBrace = closeBrace.WithLeadingTrivia(
closeBrace.LeadingTrivia.Skip(index + 1));
}
}
}
public static TypeDeclarationSyntax EnsureOpenAndCloseBraceTokens(
this TypeDeclarationSyntax typeDeclaration)
{
EnsureAndGetBraceTokens(typeDeclaration, typeDeclaration.Members.Count > 0, out var openBrace, out var closeBrace);
return typeDeclaration.WithOpenBraceToken(openBrace).WithCloseBraceToken(closeBrace);
}
public static EnumDeclarationSyntax EnsureOpenAndCloseBraceTokens(
this EnumDeclarationSyntax typeDeclaration)
{
EnsureAndGetBraceTokens(typeDeclaration, typeDeclaration.Members.Count > 0, out var openBrace, out var closeBrace);
return typeDeclaration.WithOpenBraceToken(openBrace).WithCloseBraceToken(closeBrace);
}
}
}
| 44.025078 | 164 | 0.599402 | [
"Apache-2.0"
] | Trieste-040/https-github.com-dotnet-roslyn | src/Workspaces/CSharp/Portable/Extensions/TypeDeclarationSyntaxExtensions.cs | 14,046 | C# |
// <copyright file="ChatRoom.cs" company="MUnique">
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </copyright>
namespace MUnique.OpenMU.ChatServer
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.Extensions.Logging;
using MUnique.OpenMU.Interfaces;
/// <summary>
/// This class represents a Chat Room.
/// </summary>
internal sealed class ChatRoom : IDisposable
{
private readonly ILogger<ChatRoom> logger;
/// <summary>
/// Nicknames of the registered Clients.
/// </summary>
private readonly IList<ChatServerAuthenticationInfo> registeredClients;
/// <summary>
/// Gets the <see cref="IChatClient"/>s which are currently connected to the ChatRoom.
/// </summary>
private readonly List<IChatClient> connectedClients;
private ReaderWriterLockSlim lockSlim = new ReaderWriterLockSlim();
private int lastUsedClientIndex = -1;
private bool isClosing;
/// <summary>
/// Initializes a new instance of the <see cref="ChatRoom" /> class.
/// </summary>
/// <param name="roomId">The room identifier.</param>
/// <param name="logger">The logger.</param>
public ChatRoom(ushort roomId, ILogger<ChatRoom> logger)
{
this.logger = logger;
this.logger.LogDebug($"Creating room {roomId}");
this.connectedClients = new List<IChatClient>(2);
this.registeredClients = new List<ChatServerAuthenticationInfo>(2);
this.RoomId = roomId;
this.AuthenticationRequiredUntil = DateTime.Now.AddSeconds(10);
}
/// <summary>
/// Gets the currently connected clients.
/// </summary>
public IReadOnlyCollection<IChatClient> ConnectedClients => this.connectedClients;
/// <summary>
/// Gets the id of the Chat Room.
/// </summary>
public ushort RoomId { get; }
/// <summary>
/// Gets a datetime indicating until a authentication is required.
/// </summary>
public DateTime AuthenticationRequiredUntil { get; private set; }
/// <summary>
/// Gets or sets the room closed event handler.
/// </summary>
public EventHandler<ChatRoomClosedEventArgs> RoomClosed { get; set; }
/// <summary>
/// Registers a chat client to the chatroom. this is only called
/// by the game server which will send id to the participants
/// over the games connection.
/// </summary>
/// <param name="authenticationInfo">Authentication information of the participant.</param>
public void RegisterClient(ChatServerAuthenticationInfo authenticationInfo)
{
if (this.isClosing)
{
throw new ObjectDisposedException("Chat room is already disposed.");
}
if (authenticationInfo.RoomId != this.RoomId)
{
throw new ArgumentException(
$"The RoomId of the authentication info ({authenticationInfo.RoomId}) does not match with this RoomId ({this.RoomId}).");
}
this.AuthenticationRequiredUntil = authenticationInfo.AuthenticationRequiredUntil;
this.registeredClients.Add(authenticationInfo);
}
/// <summary>
/// Gets the index of the next client.
/// </summary>
/// <returns>The index of the next client.</returns>
public byte GetNextClientIndex()
{
var clientIndex = Interlocked.Increment(ref this.lastUsedClientIndex);
return (byte)clientIndex;
}
/// <summary>
/// Closes this chat room by disconnecting all clients.
/// </summary>
public void Close()
{
this.Dispose();
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "lockSlim", Justification = "Null-conditional confuses the code analysis.")]
public void Dispose()
{
var localLockSlim = this.lockSlim;
if (this.isClosing || localLockSlim is null)
{
return;
}
this.isClosing = true;
this.lockSlim = null;
this.logger.LogDebug($"Disposing room {this.RoomId}...");
this.registeredClients.Clear();
localLockSlim.EnterWriteLock();
try
{
foreach (var client in this.connectedClients)
{
client.LogOff();
}
this.connectedClients.Clear();
this.RoomClosed?.Invoke(this, new ChatRoomClosedEventArgs(this));
this.RoomClosed = null;
}
finally
{
localLockSlim.ExitWriteLock();
}
localLockSlim.Dispose();
this.logger.LogDebug($"Room {this.RoomId} disposed.");
}
/// <summary>
/// The specified client will join the chatroom, if its registered. The Nickname is set to the clients object.
/// </summary>
/// <param name="chatClient">The chat client.</param>
/// <returns>True, if the <paramref name="chatClient"/> provides the correct registered id with it's token.</returns>
internal bool TryJoin(IChatClient chatClient)
{
if (chatClient is null)
{
throw new ArgumentNullException(nameof(chatClient));
}
if (this.isClosing)
{
throw new ObjectDisposedException("Chat room is already disposed.");
}
this.logger.LogDebug($"Client {chatClient.Index} is trying to join the room {this.RoomId} with token '{chatClient.AuthenticationToken}'");
this.lockSlim.EnterWriteLock();
try
{
ChatServerAuthenticationInfo authenticationInformation = this.registeredClients.FirstOrDefault(info => string.Equals(info.AuthenticationToken, chatClient.AuthenticationToken));
if (authenticationInformation != null)
{
if (authenticationInformation.AuthenticationRequiredUntil < DateTime.Now)
{
this.logger.LogInformation($"Client {chatClient.Index} has tried to join the room {this.RoomId} with token '{chatClient.AuthenticationToken}', but was too late. It was valid until {authenticationInformation.AuthenticationRequiredUntil}.");
}
else
{
chatClient.Nickname = authenticationInformation.ClientName;
chatClient.Index = authenticationInformation.Index;
this.registeredClients.Remove(authenticationInformation);
this.SendChatRoomClientUpdate(chatClient, ChatRoomClientUpdateType.Joined);
this.connectedClients.Add(chatClient);
chatClient.SendChatRoomClientList(this.connectedClients);
return true;
}
}
else
{
this.logger.LogInformation($"Client {chatClient.Index} has tried to join the room {this.RoomId} with token '{chatClient.AuthenticationToken}', but was not registered.");
}
}
finally
{
this.lockSlim.ExitWriteLock();
}
return false;
}
/// <summary>
/// The specified client will leave the chatroom.
/// If the chatroom is empty then, it will be removed from the manager.
/// </summary>
/// <param name="chatClient">The chat client.</param>
internal void Leave(IChatClient chatClient)
{
if (this.isClosing)
{
return;
}
this.logger.LogDebug($"Chat client ({chatClient}) is leaving.");
this.lockSlim.EnterWriteLock();
try
{
this.connectedClients.Remove(chatClient);
}
finally
{
this.lockSlim.ExitWriteLock();
}
bool roomIsEmpty;
this.lockSlim.EnterReadLock();
try
{
roomIsEmpty = this.connectedClients.Count < 1;
if (!roomIsEmpty)
{
this.SendChatRoomClientUpdate(chatClient, ChatRoomClientUpdateType.Left);
}
}
finally
{
this.lockSlim.ExitReadLock();
}
if (roomIsEmpty)
{
this.Close();
}
}
/// <summary>
/// Sends a Message to all chat clients.
/// </summary>
/// <param name="senderId">The sender identifier.</param>
/// <param name="message">The message.</param>
internal void SendMessage(byte senderId, string message)
{
if (this.isClosing)
{
return;
}
this.lockSlim.EnterReadLock();
try
{
this.connectedClients.ForEach(c => c.SendMessage(senderId, message));
}
finally
{
this.lockSlim.ExitReadLock();
}
}
private void SendChatRoomClientUpdate(IChatClient updatedClient, ChatRoomClientUpdateType updateType)
{
foreach (var client in this.connectedClients)
{
client.SendChatRoomClientUpdate(updatedClient.Index, updatedClient.Nickname, updateType);
}
}
}
}
| 36.494624 | 263 | 0.559811 | [
"MIT"
] | Tocher/OpenMU | src/ChatServer/ChatRoom.cs | 10,184 | C# |
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using System;
using DG.Tweening;
namespace IATK
{
[ExecuteInEditMode]
public class ScatterplotVisualisation : AbstractVisualisation
{
public override void CreateVisualisation()
{
string savedName = name;
foreach (View v in viewList)
{
DestroyImmediate(v.gameObject);
}
viewList.Clear();
// Create new
Dictionary<CreationConfiguration.Axis, string> axies = new Dictionary<CreationConfiguration.Axis, string>();
if (visualisationReference.xDimension.Attribute != "" && visualisationReference.xDimension.Attribute != "Undefined")
{
axies.Add(CreationConfiguration.Axis.X, visualisationReference.xDimension.Attribute);
}
if (visualisationReference.yDimension.Attribute != "" && visualisationReference.yDimension.Attribute != "Undefined")
{
axies.Add(CreationConfiguration.Axis.Y, visualisationReference.yDimension.Attribute);
}
if (visualisationReference.zDimension.Attribute != "" && visualisationReference.zDimension.Attribute != "Undefined")
{
axies.Add(CreationConfiguration.Axis.Z, visualisationReference.zDimension.Attribute);
}
if (creationConfiguration == null)
creationConfiguration = new CreationConfiguration(visualisationReference.geometry, axies);
else
{
creationConfiguration.Geometry = visualisationReference.geometry;
creationConfiguration.Axies = axies;
creationConfiguration.LinkingDimension = visualisationReference.linkingDimension;
creationConfiguration.Size = visualisationReference.size;
creationConfiguration.MinSize = visualisationReference.minSize;
creationConfiguration.MaxSize = visualisationReference.maxSize;
}
View view = CreateSimpleVisualisation(creationConfiguration);
if (view != null)
{
view.transform.localPosition = Vector3.zero;
view.transform.SetParent(transform, false);
view.onViewChangeEvent += UpdateVisualisation; // Receive notifications when the view configuration changes
viewList.Add(view);
}
if (viewList.Count > 0 && visualisationReference.colourDimension != "Undefined")
{
for (int i = 0; i < viewList.Count; i++)
{
viewList[i].SetColors(mapColoursContinuous(visualisationReference.dataSource[visualisationReference.colourDimension].Data));
}
}
else if (viewList.Count > 0 && visualisationReference.colorPaletteDimension != "Undefined")
{
for (int i = 0; i < viewList.Count; i++)
{
viewList[i].SetColors(mapColoursPalette(visualisationReference.dataSource[visualisationReference.colorPaletteDimension].Data, visualisationReference.coloursPalette));
}
}
else if (viewList.Count > 0 && visualisationReference.colour != null)
{
for (int i = 0; i < viewList.Count; i++)
{
Color[] colours = viewList[i].GetColors();
for (int j = 0; j < colours.Length; ++j)
{
colours[j] = visualisationReference.colour;
}
viewList[i].SetColors(colours);
}
}
if (viewList.Count > 0)
{
for (int i = 0; i < viewList.Count; i++)
{
viewList[i].SetSize(visualisationReference.size);
viewList[i].SetMinSize(visualisationReference.minSize);
viewList[i].SetMaxSize(visualisationReference.maxSize);
viewList[i].SetMinNormX(visualisationReference.xDimension.minScale);
viewList[i].SetMaxNormX(visualisationReference.xDimension.maxScale);
viewList[i].SetMinNormY(visualisationReference.yDimension.minScale);
viewList[i].SetMaxNormY(visualisationReference.yDimension.maxScale);
viewList[i].SetMinNormZ(visualisationReference.zDimension.minScale);
viewList[i].SetMaxNormZ(visualisationReference.zDimension.maxScale);
viewList[i].SetMinX(visualisationReference.xDimension.minFilter);
viewList[i].SetMaxX(visualisationReference.xDimension.maxFilter);
viewList[i].SetMinY(visualisationReference.yDimension.minFilter);
viewList[i].SetMaxY(visualisationReference.yDimension.maxFilter);
viewList[i].SetMinZ(visualisationReference.zDimension.minFilter);
viewList[i].SetMaxZ(visualisationReference.zDimension.maxFilter);
}
}
if (viewList.Count > 0 && visualisationReference.sizeDimension != "Undefined")
{
for (int i = 0; i < viewList.Count; i++)
{
viewList[i].SetSizeChannel(visualisationReference.dataSource[visualisationReference.sizeDimension].Data);
}
}
name = savedName;
}
public override void UpdateVisualisation(PropertyType propertyType){
if (viewList.Count == 0)
CreateVisualisation();
if (viewList.Count != 0)
switch (propertyType)
{
case AbstractVisualisation.PropertyType.X:
if (visualisationReference.xDimension.Attribute.Equals("Undefined"))
{
viewList[0].ZeroPosition(0);
viewList[0].TweenPosition();
}
else
{
viewList[0].UpdateXPositions(visualisationReference.dataSource[visualisationReference.xDimension.Attribute].Data);
viewList[0].TweenPosition();
}
if (creationConfiguration.Axies.ContainsKey(CreationConfiguration.Axis.X))
{
creationConfiguration.Axies[CreationConfiguration.Axis.X] = visualisationReference.xDimension.Attribute;
}
else
{
creationConfiguration.Axies.Add(CreationConfiguration.Axis.X, visualisationReference.xDimension.Attribute);
}
break;
case AbstractVisualisation.PropertyType.Y:
if (visualisationReference.yDimension.Attribute.Equals("Undefined"))
{
viewList[0].ZeroPosition(1);
viewList[0].TweenPosition();
}
else
{
viewList[0].UpdateYPositions(visualisationReference.dataSource[visualisationReference.yDimension.Attribute].Data);
viewList[0].TweenPosition();
}
if (creationConfiguration.Axies.ContainsKey(CreationConfiguration.Axis.Y))
{
creationConfiguration.Axies[CreationConfiguration.Axis.Y] = visualisationReference.yDimension.Attribute;
}
else
{
creationConfiguration.Axies.Add(CreationConfiguration.Axis.Y, visualisationReference.yDimension.Attribute);
}
break;
case AbstractVisualisation.PropertyType.Z:
if (visualisationReference.zDimension.Attribute.Equals("Undefined"))
{
viewList[0].ZeroPosition(2);
viewList[0].TweenPosition();
}
else
{
viewList[0].UpdateZPositions(visualisationReference.dataSource[visualisationReference.zDimension.Attribute].Data);
viewList[0].TweenPosition();
}
if (creationConfiguration.Axies.ContainsKey(CreationConfiguration.Axis.Z))
{
creationConfiguration.Axies[CreationConfiguration.Axis.Z] = visualisationReference.zDimension.Attribute;
}
else
{
creationConfiguration.Axies.Add(CreationConfiguration.Axis.Z, visualisationReference.zDimension.Attribute);
}
break;
case AbstractVisualisation.PropertyType.Colour:
if (visualisationReference.colourDimension != "Undefined")
{
for (int i = 0; i < viewList.Count; i++)
viewList[i].SetColors(mapColoursContinuous(visualisationReference.dataSource[visualisationReference.colourDimension].Data));
}
else if (visualisationReference.colorPaletteDimension != "Undefined")
{
for (int i = 0; i < viewList.Count; i++)
{
viewList[i].SetColors(mapColoursPalette(visualisationReference.dataSource[visualisationReference.colorPaletteDimension].Data, visualisationReference.coloursPalette));
}
}
else
{
for (int i = 0; i < viewList.Count; i++)
{
Color[] colours = viewList[0].GetColors();
for (int j = 0; j < colours.Length; ++j)
{
colours[j] = visualisationReference.colour;
}
viewList[i].SetColors(colours);
}
}
creationConfiguration.ColourDimension = visualisationReference.colourDimension;
creationConfiguration.colourKeys = visualisationReference.dimensionColour;
creationConfiguration.colour = visualisationReference.colour;
break;
case AbstractVisualisation.PropertyType.Size:
{
for (int i = 0; i < viewList.Count; i++)
{
if (visualisationReference.sizeDimension != "Undefined")
{
viewList[i].SetSizeChannel(visualisationReference.dataSource[visualisationReference.sizeDimension].Data);
}
else
{
viewList[i].SetSizeChannel(Enumerable.Repeat(0f, visualisationReference.dataSource[0].Data.Length).ToArray());
}
}
creationConfiguration.SizeDimension = visualisationReference.sizeDimension;
viewList[0].TweenSize();
break;
}
case PropertyType.SizeValues:
for (int i = 0; i < viewList.Count; i++)
{
viewList[i].SetSize(visualisationReference.size);
viewList[i].SetMinSize(visualisationReference.minSize); // Data is normalised
viewList[i].SetMaxSize(visualisationReference.maxSize);
}
creationConfiguration.Size = visualisationReference.size;
creationConfiguration.MinSize = visualisationReference.minSize;
creationConfiguration.MaxSize = visualisationReference.maxSize;
break;
case AbstractVisualisation.PropertyType.LinkingDimension:
creationConfiguration.LinkingDimension = visualisationReference.linkingDimension;
string xDimension = visualisationReference.xDimension.Attribute;
string yDimension = visualisationReference.yDimension.Attribute;
string linkingDimension = visualisationReference.linkingDimension;
float[] newAggregatedYValues = new float[0];
if (xDimension != "Undefined" && yDimension != "Undefined" && linkingDimension != "Undefined")
{
float[] xData = visualisationReference.dataSource[xDimension].Data;
float[] yData = visualisationReference.dataSource[yDimension].Data;
float[] linkingData = visualisationReference.dataSource[linkingDimension].Data;
// Create new list of pairs where Item1 is the x dimension, Item2 is the linking dimension
List<Tuple<float, float>> pairs = new List<Tuple<float, float>>();
for (int i = 0; i < visualisationReference.dataSource.DataCount; i++)
{
pairs.Add(new Tuple<float, float>(xData[i], linkingData[i]));
}
// Sort by x dimension values, then by linking values
var sort = pairs.Select((value, index) => new { value, index }).OrderBy(x => x.value.Item1).ThenBy(x => x.value.Item2).ToList();
//List<float> sortedXValues = sort.Select(x => x.value.Item1).ToList();
//List<float> sortedLinkingValues = sort.Select(x => x.value.Item2).ToList();
//List<int> sortedIndices = sort.Select(x => x.index).ToList();
List<int> associatedIndices = new List<int>();
newAggregatedYValues = new float[visualisationReference.dataSource.DataCount];
int count = 0;
double total = 0;
float previousX = Mathf.Infinity;
float previousLinking = Mathf.Infinity;
float avg;
for (int i = 0; i < sort.Count; i++)
{
float currentX = sort[i].value.Item1;
float currentLinking = sort[i].value.Item2;
// If now looking at a new x, linking group
if (previousLinking != currentLinking || previousX != currentX)
{
// Calculate average
avg = (float)(total / count);
// Back-fill the values of the averages to the associated indices
foreach (int idx in associatedIndices)
{
newAggregatedYValues[idx] = avg;
}
associatedIndices.Clear();
count = 0;
total = 0;
}
previousX = currentX;
previousLinking = currentLinking;
int actualIndex = sort[i].index;
total += yData[actualIndex];
count++;
associatedIndices.Add(actualIndex);
}
// Do one last final check
avg = (float)(total / count);
// Back-fill the values of the averages to the associated indices
foreach (int idx in associatedIndices)
{
newAggregatedYValues[idx] = avg;
}
}
CreateVisualisation(); // needs to recreate the visualsiation because the mesh properties have changed
if (newAggregatedYValues.Length > 0)
{
viewList[0].UpdateYPositions(newAggregatedYValues);
}
break;
case AbstractVisualisation.PropertyType.GeometryType:
creationConfiguration.Geometry = visualisationReference.geometry;
CreateVisualisation(); // needs to recreate the visualsiation because the mesh properties have changed
break;
case AbstractVisualisation.PropertyType.Scaling:
for (int i = 0; i < viewList.Count; i++)
{
viewList[i].SetMinNormX(visualisationReference.xDimension.minScale);
viewList[i].SetMaxNormX(visualisationReference.xDimension.maxScale);
viewList[i].SetMinNormY(visualisationReference.yDimension.minScale);
viewList[i].SetMaxNormY(visualisationReference.yDimension.maxScale);
viewList[i].SetMinNormZ(visualisationReference.zDimension.minScale);
viewList[i].SetMaxNormZ(visualisationReference.zDimension.maxScale);
}
break;
case AbstractVisualisation.PropertyType.DimensionFiltering:
for (int i = 0; i < viewList.Count; i++)
{
viewList[i].SetMinX(visualisationReference.xDimension.minFilter);
viewList[i].SetMaxX(visualisationReference.xDimension.maxFilter);
viewList[i].SetMinY(visualisationReference.yDimension.minFilter);
viewList[i].SetMaxY(visualisationReference.yDimension.maxFilter);
viewList[i].SetMinZ(visualisationReference.zDimension.minFilter);
viewList[i].SetMaxZ(visualisationReference.zDimension.maxFilter);
}
break;
case AbstractVisualisation.PropertyType.AttributeFiltering:
if (visualisationReference.attributeFilters!=null)
{
foreach (var viewElement in viewList)
{
float[] isFiltered = new float[visualisationReference.dataSource.DataCount];
for (int i = 0; i < visualisationReference.dataSource.DimensionCount; i++)
{
foreach (AttributeFilter attrFilter in visualisationReference.attributeFilters)
{
if (attrFilter.Attribute == visualisationReference.dataSource[i].Identifier)
{
float minFilteringValue = UtilMath.normaliseValue(attrFilter.minFilter, 0f, 1f, attrFilter.minScale, attrFilter.maxScale);
float maxFilteringValue = UtilMath.normaliseValue(attrFilter.maxFilter, 0f, 1f, attrFilter.minScale, attrFilter.maxScale);
for (int j = 0; j < isFiltered.Length; j++)
{
isFiltered[j] = (visualisationReference.dataSource[i].Data[j] < minFilteringValue || visualisationReference.dataSource[i].Data[j] > maxFilteringValue) ? 1.0f : isFiltered[j];
}
}
}
}
// map the filtered attribute into the normal channel of the bigmesh
foreach (View v in viewList)
{
v.SetFilterChannel(isFiltered);
}
}
}
break;
case PropertyType.VisualisationType:
break;
case PropertyType.BlendDestinationMode:
float bmds = (int)(System.Enum.Parse(typeof(UnityEngine.Rendering.BlendMode), visualisationReference.blendingModeDestination));
for (int i = 0; i < viewList.Count; i++)
{
viewList[i].SetBlendindDestinationMode(bmds);
}
break;
case PropertyType.BlendSourceMode:
float bmd = (int)(System.Enum.Parse(typeof(UnityEngine.Rendering.BlendMode), visualisationReference.blendingModeSource));
for (int i = 0; i < viewList.Count; i++)
{
viewList[i].SetBlendingSourceMode(bmd);
}
break;
default:
break;
}
//if (visualisationReference.geometry != GeometryType.Undefined)// || visualisationType == VisualisationTypes.PARALLEL_COORDINATES)
// SerializeViewConfiguration(creationConfiguration);
//Update any label on the corresponding axes
UpdateVisualisationAxes(propertyType);
}
protected void UpdateVisualisationAxes(AbstractVisualisation.PropertyType propertyType)
{
switch (propertyType)
{
case AbstractVisualisation.PropertyType.X:
if (visualisationReference.xDimension.Attribute == "Undefined" && X_AXIS != null)// GameObject_Axes_Holders[0] != null)
{
DestroyImmediate(X_AXIS);
}
else if (X_AXIS != null)
{
Axis a = X_AXIS.GetComponent<Axis>();
a.Init(visualisationReference.dataSource, visualisationReference.xDimension, visualisationReference);
BindMinMaxAxisValues(a, visualisationReference.xDimension);
}
else if (visualisationReference.xDimension.Attribute != "Undefined")
{
Vector3 pos = Vector3.zero;
pos.y = -0.02f;
X_AXIS = CreateAxis(propertyType, visualisationReference.xDimension, pos, new Vector3(0f, 0f, 0f), 0);
}
break;
case AbstractVisualisation.PropertyType.Y:
if (visualisationReference.yDimension.Attribute == "Undefined" && Y_AXIS != null)
{
DestroyImmediate(Y_AXIS);
}
else if (Y_AXIS != null)
{
Axis a = Y_AXIS.GetComponent<Axis>();
a.Init(visualisationReference.dataSource, visualisationReference.yDimension, visualisationReference);
BindMinMaxAxisValues(a, visualisationReference.yDimension);
}
else if (visualisationReference.yDimension.Attribute != "Undefined")
{
Vector3 pos = Vector3.zero;
pos.x = -0.02f;
Y_AXIS = CreateAxis(propertyType, visualisationReference.yDimension, pos, new Vector3(0f, 0f, 0f), 1);
}
break;
case AbstractVisualisation.PropertyType.Z:
if (visualisationReference.zDimension.Attribute == "Undefined" && Z_AXIS != null)
{
DestroyImmediate(Z_AXIS);
}
else if (Z_AXIS != null)
{
Axis a = Z_AXIS.GetComponent<Axis>();
a.Init(visualisationReference.dataSource, visualisationReference.zDimension, visualisationReference);
BindMinMaxAxisValues(Z_AXIS.GetComponent<Axis>(), visualisationReference.zDimension);
}
else if (visualisationReference.zDimension.Attribute != "Undefined")
{
Vector3 pos = Vector3.zero;
pos.y = -0.02f;
pos.x = -0.02f;
Z_AXIS = CreateAxis(propertyType, visualisationReference.zDimension, pos, new Vector3(90f, 0f, 0f), 2);
}
break;
case AbstractVisualisation.PropertyType.DimensionFiltering:
if (visualisationReference.xDimension.Attribute != "Undefined")
{
BindMinMaxAxisValues(X_AXIS.GetComponent<Axis>(), visualisationReference.xDimension);
}
if (visualisationReference.yDimension.Attribute != "Undefined")
{
BindMinMaxAxisValues(Y_AXIS.GetComponent<Axis>(), visualisationReference.yDimension);
}
if (visualisationReference.zDimension.Attribute != "Undefined")
{
BindMinMaxAxisValues(Z_AXIS.GetComponent<Axis>(), visualisationReference.zDimension);
}
break;
case AbstractVisualisation.PropertyType.Scaling:
if (visualisationReference.xDimension.Attribute != "Undefined")
{
BindMinMaxAxisValues(X_AXIS.GetComponent<Axis>(), visualisationReference.xDimension);
}
if (visualisationReference.yDimension.Attribute != "Undefined")
{
BindMinMaxAxisValues(Y_AXIS.GetComponent<Axis>(), visualisationReference.yDimension);
}
if (visualisationReference.zDimension.Attribute != "Undefined")
{
BindMinMaxAxisValues(Z_AXIS.GetComponent<Axis>(), visualisationReference.zDimension);
}
break;
default:
break;
}
UpdateAxes();
}
/// <summary>
/// Gets the axies.
/// </summary>
/// <returns>The axies.</returns>
/// <param name="axies">Axies.</param>
protected string getAxis(Dictionary<CreationConfiguration.Axis, string> axies, CreationConfiguration.Axis axis)
{
string axes = null;
string retVal = "";
if (axies.TryGetValue(axis, out axes))
retVal = axes;
return retVal;
}
public override void SaveConfiguration(){}
public override void LoadConfiguration(){}
/// <summary>
/// Maps the colours.
/// </summary>
/// <returns>The colours.</returns>
/// <param name="data">Data.</param>
public override Color[] mapColoursContinuous(float[] data)
{
Color[] colours = new Color[data.Length];
for (int i = 0; i < data.Length; ++i)
{
colours[i] = visualisationReference.dimensionColour.Evaluate(data[i]);
}
return colours;
}
public Color[] mapColoursPalette(float[] data, Color[] palette)
{
Color[] colours = new Color[data.Length];
float[] uniqueValues = data.Distinct().ToArray();
for (int i = 0; i < data.Length; i++)
{
int indexColor = Array.IndexOf(uniqueValues, data[i]);
colours[i] = palette[indexColor];
}
return colours;
}
// ******************************
// SPECIFIC VISUALISATION METHODS
// ******************************
private View CreateSimpleVisualisation(CreationConfiguration configuration)
{
if (visualisationReference.dataSource != null)
{
if (!visualisationReference.dataSource.IsLoaded) visualisationReference.dataSource.load();
ViewBuilder builder = new ViewBuilder(geometryToMeshTopology(configuration.Geometry), "Simple Visualisation");
if ((visualisationReference.dataSource[getAxis(configuration.Axies, CreationConfiguration.Axis.X)] != null) ||
(visualisationReference.dataSource[getAxis(configuration.Axies, CreationConfiguration.Axis.Y)] != null) ||
(visualisationReference.dataSource[getAxis(configuration.Axies, CreationConfiguration.Axis.Z)] != null))
{
builder.initialiseDataView(visualisationReference.dataSource.DataCount);
if (visualisationReference.dataSource[getAxis(configuration.Axies, CreationConfiguration.Axis.X)] != null)
builder.setDataDimension(visualisationReference.dataSource[getAxis(configuration.Axies, CreationConfiguration.Axis.X)].Data, ViewBuilder.VIEW_DIMENSION.X);
if (visualisationReference.dataSource[getAxis(configuration.Axies, CreationConfiguration.Axis.Y)] != null)
builder.setDataDimension(visualisationReference.dataSource[getAxis(configuration.Axies, CreationConfiguration.Axis.Y)].Data, ViewBuilder.VIEW_DIMENSION.Y);
if (visualisationReference.dataSource[getAxis(configuration.Axies, CreationConfiguration.Axis.Z)] != null)
builder.setDataDimension(visualisationReference.dataSource[getAxis(configuration.Axies, CreationConfiguration.Axis.Z)].Data, ViewBuilder.VIEW_DIMENSION.Z);
//destroy the view to clean the big mesh
destroyView();
//return the appropriate geometry view
return ApplyGeometryAndRendering(creationConfiguration, ref builder);
}
}
return null;
}
// *************************************************************
// ******************** UNITY METHODS ************************
// *************************************************************
// Use this for initialization
private void Update()
{
//UpdateAxes();
}
private void UpdateAxes()
{
// handle update to persistent properties
if (X_AXIS != null && X_AXIS.activeSelf)
{
X_AXIS.GetComponent<Axis>().Length = visualisationReference.width;
X_AXIS.GetComponent<Axis>().UpdateLength();
}
if (Y_AXIS != null && Y_AXIS.activeSelf)
{
Y_AXIS.GetComponent<Axis>().Length = visualisationReference.height;
Y_AXIS.GetComponent<Axis>().UpdateLength();
}
if (Z_AXIS != null && Z_AXIS.activeSelf)
{
Z_AXIS.GetComponent<Axis>().Length = visualisationReference.depth;
Z_AXIS.GetComponent<Axis>().UpdateLength();
}
foreach (View view in viewList)
{
view.transform.localScale = new Vector3(
visualisationReference.width,
visualisationReference.height,
visualisationReference.depth
);
}
}
}
}
| 50.136157 | 222 | 0.49834 | [
"MIT"
] | MaximeCordeil/FIESTA | Assets/IATK/Scripts/Controller/Visualisations/ScatterplotVisualisation.cs | 33,142 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using Azure.Core;
namespace Azure.Iot.Hub.Service.Authentication
{
/// <summary>
/// The IoT Hub credentials, to be used for authenticating against an IoT Hub instance via SAS tokens.
/// </summary>
public class IotHubSasCredential : ISasTokenProvider
{
// Time buffer before expiry when the token should be renewed, expressed as a percentage of the time to live.
// The token will be renewed when it has 15% or less of the sas token's lifespan left.
private const int RenewalTimeBufferPercentage = 15;
private readonly object _lock = new object();
private string _cachedSasToken;
private DateTimeOffset _tokenExpiryTime;
internal IotHubSasCredential(string connectionString)
{
Argument.AssertNotNullOrWhiteSpace(connectionString, nameof(connectionString));
var iotHubConnectionString = ConnectionString.Parse(connectionString);
var sharedAccessPolicy = iotHubConnectionString.GetRequired(SharedAccessSignatureConstants.SharedAccessPolicyIdentifier);
var sharedAccessKey = iotHubConnectionString.GetRequired(SharedAccessSignatureConstants.SharedAccessKeyIdentifier);
Endpoint = BuildEndpointUriFromHostName(iotHubConnectionString.GetRequired(SharedAccessSignatureConstants.HostNameIdentifier));
SetCredentials(sharedAccessPolicy, sharedAccessKey);
}
/// <summary>
/// Initializes a new instance of <see cref="IotHubSasCredential"/> class.
/// </summary>
/// <param name="sharedAccessPolicy">
/// The IoT Hub access permission, which can be either "iothubowner", "service", "registryRead" or "registryReadWrite" policy, as applicable.
/// For more information, see <see href="https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-security#access-control-and-permissions"/>.
/// </param>
/// <param name="sharedAccessKey">
/// The IoT Hub shared access key associated with the shared access policy permissions.
/// </param>
/// <param name="timeToLive">
/// (Optional) The validity duration of the generated shared access signature token used for authentication.
/// The token will be renewed when at 15% or less of it's lifespan. The default value is 30 minutes.
/// </param>
public IotHubSasCredential(string sharedAccessPolicy, string sharedAccessKey, TimeSpan timeToLive = default)
{
Argument.AssertNotNullOrWhiteSpace(sharedAccessPolicy, nameof(sharedAccessPolicy));
Argument.AssertNotNullOrWhiteSpace(sharedAccessKey, nameof(sharedAccessKey));
SetCredentials(sharedAccessPolicy, sharedAccessKey, timeToLive);
}
private void SetCredentials(string sharedAccessPolicy, string sharedAccessKey, TimeSpan timeToLive = default)
{
SharedAccessPolicy = sharedAccessPolicy;
SharedAccessKey = sharedAccessKey;
if (!timeToLive.Equals(TimeSpan.Zero))
{
if (timeToLive.CompareTo(TimeSpan.Zero) < 0)
{
throw new ArgumentException("The value for SasTokenTimeToLive cannot be a negative TimeSpan", nameof(timeToLive));
}
SasTokenTimeToLive = timeToLive;
}
_cachedSasToken = null;
}
/// <summary>
/// The IoT Hub service instance endpoint to connect to.
/// </summary>
public Uri Endpoint { get; internal set; }
/// <summary>
/// The IoT Hub access permission, which can be either "iothubowner", "service", "registryRead" or "registryReadWrite" policy, as applicable.
/// For more information, see <see href="https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-security#access-control-and-permissions"/>.
/// </summary>
public string SharedAccessPolicy { get; private set; }
/// <summary>
/// The IoT Hub shared access key associated with the shared access policy permissions.
/// </summary>
public string SharedAccessKey { get; private set; }
/// <summary>
/// The validity duration of the generated shared access signature token used for authentication.
/// The token will be renewed when at 15% or less of it's lifespan. The default value is 30 minutes.
/// </summary>
public TimeSpan SasTokenTimeToLive { get; private set; } = TimeSpan.FromMinutes(30);
private static Uri BuildEndpointUriFromHostName(string hostName)
{
return new UriBuilder
{
Scheme = Uri.UriSchemeHttps,
Host = hostName
}.Uri;
}
public string GetSasToken()
{
lock (_lock)
{
if (TokenShouldBeGenerated())
{
var builder = new SharedAccessSignatureBuilder
{
HostName = Endpoint.Host,
SharedAccessPolicy = SharedAccessPolicy,
SharedAccessKey = SharedAccessKey,
TimeToLive = SasTokenTimeToLive,
};
_tokenExpiryTime = DateTimeOffset.UtcNow.Add(SasTokenTimeToLive);
_cachedSasToken = builder.ToSignature();
}
return _cachedSasToken;
}
}
private bool TokenShouldBeGenerated()
{
// The token needs to be generated if this is the first time it is being accessed (not cached yet)
// or the current time is greater than or equal to the token expiry time, less 15% buffer.
if (_cachedSasToken == null)
{
return true;
}
var bufferTimeInMilliseconds = (double)RenewalTimeBufferPercentage / 100 * SasTokenTimeToLive.TotalMilliseconds;
DateTimeOffset tokenExpiryTimeWithBuffer = _tokenExpiryTime.AddMilliseconds(-bufferTimeInMilliseconds);
return DateTimeOffset.UtcNow.CompareTo(tokenExpiryTimeWithBuffer) >= 0;
}
}
}
| 43.951389 | 156 | 0.636751 | [
"MIT"
] | foreverstupid/azure-sdk-for-net | sdk/iot/Azure.Iot.Hub.Service/src/Authentication/IotHubSasCredential.cs | 6,331 | C# |
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using Hangfire.SqlServer.RabbitMQ;
using Xunit.Sdk;
namespace Hangfire.SqlServer.RabbitMq.Tests
{
public class CleanRabbitMqQueueAttribute : BeforeAfterTestAttribute
{
private static readonly object GlobalLock = new object();
private readonly IEnumerable<string> _queues;
private readonly RabbitMqJobQueue _rabbitMq;
public CleanRabbitMqQueueAttribute(params string[] queues)
{
_queues = queues;
_rabbitMq = new RabbitMqChannel(_queues).CreateQueue();
}
public override void Before(MethodInfo methodUnderTest)
{
Monitor.Enter(GlobalLock);
foreach (var queue in _queues)
{
_rabbitMq.Channel.QueueDeclare(queue, true, false, false, null);
_rabbitMq.Channel.QueuePurge(queue);
}
_rabbitMq.Dispose();
}
public override void After(MethodInfo methodUnderTest)
{
Monitor.Exit(GlobalLock);
}
public static RabbitMqJobQueue GetMessageQueue(params string[] queue)
{
return new RabbitMqChannel(queue).CreateQueue();
}
}
}
| 29.581395 | 80 | 0.636792 | [
"MIT"
] | psongit/Hangfire.SqlServer.RabbitMq | tests/Hangfire.SqlServer.RabbitMq.Tests/Utils/CleanRabbitMqQueueAttribute.cs | 1,274 | C# |
/* Copyright 2018 The TensorFlow Authors. 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 UnityEngine;
using UnityEngine.Video;
public class HandTracking : MonoBehaviour
{
[Tooltip("Configurable TFLite model.")]
public int InputW = 256;
public int InputH = 256;
public TextAsset PalmDetection;
public TextAsset HandLandmark3D;
public int PalmDetectionLerpFrameCount = 3;
public int HandLandmark3DLerpFrameCount = 4;
public bool UseGPU = true;
private RenderTexture videoTexture;
private Texture2D texture;
private Inferencer inferencer = new Inferencer();
private GameObject debugPlane;
private DebugRenderer debugRenderer;
void Awake() { QualitySettings.vSyncCount = 0; }
void Start()
{
InitTexture();
inferencer.Init(PalmDetection, HandLandmark3D, UseGPU,
PalmDetectionLerpFrameCount, HandLandmark3DLerpFrameCount);
debugPlane = GameObject.Find("TensorFlowLite");
debugRenderer = debugPlane.GetComponent<DebugRenderer>();
debugRenderer.Init(inferencer.InputWidth, inferencer.InputHeight, debugPlane);
}
private void InitTexture()
{
var rectTransform = GetComponent<RectTransform>();
var renderer = GetComponent<Renderer>();
var videoPlayer = GetComponent<VideoPlayer>();
int width = (int)rectTransform.rect.width;
int height = (int)rectTransform.rect.height;
videoTexture = new RenderTexture(width, height, 24);
videoPlayer.targetTexture = videoTexture;
renderer.material.mainTexture = videoTexture;
videoPlayer.Play();
texture = new Texture2D(videoTexture.width, videoTexture.height, TextureFormat.RGB24, false);
}
void Update()
{
Graphics.SetRenderTarget(videoTexture);
texture.ReadPixels(new Rect(0, 0, videoTexture.width, videoTexture.height), 0, 0);
texture.Apply();
Graphics.SetRenderTarget(null);
inferencer.Update(texture);
}
public void OnRenderObject()
{
if (!inferencer.Initialized){ return; }
bool debugHandLandmarks3D = true;
if (debugHandLandmarks3D)
{
var handLandmarks = inferencer.HandLandmarks;
debugRenderer.DrawHand3D(handLandmarks);
}
}
void OnDestroy(){ inferencer.Destroy(); }
}
| 35.44186 | 102 | 0.658793 | [
"Apache-2.0"
] | t-takasaka/tensorflow | tensorflow/lite/experimental/examples/unity/TensorFlowLitePlugin/Assets/TensorFlowLite/Examples/HandTracking/Scripts/HandTracking.cs | 3,050 | C# |
////////////////////////////////
//
// Copyright 2021 Battelle Energy Alliance, LLC
//
//
////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace CSET_Main.Questions.POCO
{
public class ParameterTextBuilder
{
private QuestionPoco _poco;
private string _textSub;
private string _textSubNoLinks;
private bool needsParameterization
{
get
{
return _poco.Parameters.Any()&&!String.IsNullOrEmpty(_poco.Text)&&_poco.IsRequirement;
}
}
public ParameterTextBuilder(QuestionPoco poco)
{
_poco = poco;
_textSub = createTextBlock();
_textSubNoLinks = createTextBlock();
}
public Tuple<string, string> ReplaceParameterText()
{
switch(needsParameterization)
{
case false:
processNoParameters();
break;
case true:
processWithParameters();
break;
}
return new Tuple<string, string>(_textSub, _textSubNoLinks);
}
private void processNoParameters()
{
processForNonParameter(_poco.Text);
}
private void processWithParameters()
{
var tokenized = tokenizeText();
foreach (var item in tokenized)
{
var param = getParameterForText(item);
switch (param.HasValue)
{
case true:
processForParameter(param.Value.Key, param.Value.Value);
break;
case false:
processForNonParameter(item);
break;
}
}
}
private void processForNonParameter(string item)
{
if(item != null && item.Length>0)
{
//_textSub.Inlines.Add(getRunForText(item));
//_textSubNoLinks.Inlines.Add(getRunForText(item));
}
}
private void processForParameter(int index, ParameterContainer param)
{
//var link = new Hyperlink();
//link.Click += QuestionListView.FlyOutDisplay;
//link.Inlines.Add(getRunForParameter(index));
//link.CommandParameter = new object[] { param, _poco };
//_textSub.Inlines.Add(link);
//_textSubNoLinks.Inlines.Add(getRunForParameter(index));
}
//private Run getRunForText(string text)
//{
// return new Run(text);
//}
//private Run getRunForParameter(int index)
//{
// var run = new Run();
// var binding = new Binding();
// binding.Path = new PropertyPath(String.Format("Parameters[{0}].Value", index));
// binding.Mode = BindingMode.OneWay;
// run.SetBinding(Run.TextProperty, binding);
// return run;
//}
private string[] tokenizeText()
{
var parameterStrings = String.Join("|", _poco.Parameters.Select(t => "(" + Regex.Escape(t.Name) + ")"));
return Regex.Split(_poco.Text, parameterStrings);
}
private KeyValuePair<int, ParameterContainer>? getParameterForText(string item)
{
var kvp= _poco.Parameters.Select((t, i) => new KeyValuePair<int, ParameterContainer>(i, t))
.FirstOrDefault(t => t.Value.Name == item);
if(kvp.Value==null)
{
return null;
}
return kvp;
}
private string createTextBlock()
{
throw new NotImplementedException("this needs to build the html with the links in it");
//return new string() { DataContext = _poco, TextWrapping=TextWrapping.Wrap, Name="QuestionText" };
}
}
}
| 33.360656 | 116 | 0.517199 | [
"MIT"
] | PinkDev1/cset | CSETWebApi/CSETWeb_Api/BusinessLogic/Questions/POCO/Requirement_ParametersBuilder.cs | 4,070 | C# |
// Reading DOOM WAD files
// https://www.cyotek.com/blog/reading-doom-wad-files
// Writing DOOM WAD files
// https://www.cyotek.com/blog/writing-doom-wad-files
// Copyright © 2020-2022 Cyotek Ltd. All Rights Reserved.
// This work is licensed under the MIT License.
// See LICENSE.TXT for the full text
// Found this example useful?
// https://www.cyotek.com/contribute
using System.IO;
namespace Cyotek.Data
{
public sealed class WadDirectoryReader : IDirectoryReader
{
#region Private Fields
private readonly WadFormat _format;
#endregion Private Fields
#region Public Constructors
public WadDirectoryReader(WadFormat format)
{
Guard.ThrowIfNull(format, nameof(format));
_format = format;
}
public WadDirectoryReader(WadType type)
: this(WadFormat.GetFormat(type))
{
}
#endregion Public Constructors
#region Public Methods
public WadLump ReadEntry(Stream stream)
{
WadLump result;
byte[] buffer;
Guard.ThrowIfNull(stream, nameof(stream));
Guard.ThrowIfUnreadableStream(stream, nameof(stream));
buffer = this.ReadBuffer(stream, _format.DirectoryEntryLength);
result = new WadLump
{
Offset = WordHelpers.GetInt32Le(buffer, _format.DirectoryEntryDataOffset),
Size = WordHelpers.GetInt32Le(buffer, _format.DirectoryEntrySizeOffset),
Name = CharHelpers.GetSafeName(buffer, _format.DirectoryEntryNameOffset, _format.DirectoryEntryNameLength),
};
if ((_format.Flags & WadFormatFlag.CompressionMode) != 0)
{
result.CompressionMode = buffer[_format.DirectoryEntryCompressionModeOffset];
result.UncompressedSize = WordHelpers.GetInt32Le(buffer, _format.DirectoryEntryUncompressedSizeOffset);
}
else
{
result.UncompressedSize = result.Size;
}
if ((_format.Flags & WadFormatFlag.FileType) != 0)
{
result.Type = buffer[_format.DirectoryEntryFileTypeOffset];
}
BufferHelpers.Release(buffer);
return result;
}
public DirectoryHeader ReadHeader(Stream stream)
{
DirectoryHeader result;
byte[] buffer;
Guard.ThrowIfNull(stream, nameof(stream));
Guard.ThrowIfUnreadableStream(stream, nameof(stream));
buffer = this.ReadBuffer(stream, _format.HeaderLength);
if (this.IsValidSignature(buffer))
{
WadType type;
int directoryStart;
int lumpCount;
type = _format.Type;
directoryStart = WordHelpers.GetInt32Le(buffer, _format.HeaderDirectoryOffset);
lumpCount = (_format.Flags & WadFormatFlag.DirectorySize) == 0
? WordHelpers.GetInt32Le(buffer, _format.HeaderCountOffset)
: WordHelpers.GetInt32Le(buffer, _format.HeaderCountOffset) / _format.DirectoryEntryLength;
result = new DirectoryHeader(type, directoryStart, lumpCount);
}
else
{
result = DirectoryHeader.Empty;
}
BufferHelpers.Release(buffer);
return result;
}
#endregion Public Methods
#region Private Methods
internal static bool IsValidSignature(byte[] buffer, byte[] signature)
{
bool result;
result = true;
for (int i = 0; i < signature.Length; i++)
{
if (buffer[i] != signature[i])
{
result = false;
break;
}
}
return result;
}
public int DirectoryEntrySize => _format.DirectoryEntryLength;
private bool IsValidSignature(byte[] buffer) => WadDirectoryReader.IsValidSignature(buffer, _format.SignatureBytes);
private byte[] ReadBuffer(Stream stream, byte length)
{
byte[] buffer;
buffer = BufferHelpers.GetBuffer(length);
if (stream.Read(buffer, 0, length) != length)
{
throw new InvalidDataException("Failed to fill data buffer.");
}
return buffer;
}
#endregion Private Methods
}
} | 25.082278 | 120 | 0.663386 | [
"MIT"
] | cyotek/WadDemo | lib/WadDirectoryReader.cs | 3,966 | C# |
#region License
// Copyright (c) 2012, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This software is licensed under the Open Software License v3.0.
// For the complete license, see http://www.clearcanvas.ca/OSLv3.0
#endregion
using System;
using ClearCanvas.Common;
using ClearCanvas.Enterprise.Core.Upgrade;
namespace ClearCanvas.ImageServer.Model.SqlServer.UpgradeScripts
{
[ExtensionOf(typeof(PersistentStoreUpgradeScriptExtensionPoint))]
class UpgradeFrom_6_1_7081_10268 : BaseUpgradeScript
{
public UpgradeFrom_6_1_7081_10268()
: base(new Version(6, 1, 7081, 10268), null, "UpgradeFrom_6_1_7081_10268.sql")
{
}
}
}
| 26.851852 | 82 | 0.710345 | [
"Apache-2.0"
] | SNBnani/Xian | ImageServer/Model/SqlServer/UpgradeScripts/UpgradeFrom_6_1_7081_10268.cs | 727 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
namespace Microsoft.Protocols.TestTools.StackSdk.Security.Nrpc
{
/// <summary>
/// NRPC compute session key algorithms.
/// </summary>
public enum NrpcComputeSessionKeyAlgorithm
{
/// <summary>
/// If AES support is negotiated between the client and the server,
/// the strong-key support flag is ignored and the session key is
/// computed with the HMAC-SHA256 algorithm.
/// </summary>
HMACSHA256,
/// <summary>
/// If AES is not negotiated and strong-key support is one of the flags
/// in the NegotiateFlags between the client and the server,
/// the session key is computed with the MD5 message-digest algorithm.
/// </summary>
MD5,
/// <summary>
/// If neither AES nor strong-key support is negotiated between the client
/// and the server, the session key is computed by using the DES
/// encryption algorithm in ECB mode.
/// </summary>
DES
}
/// <summary>
/// NRPC compute netlogon credential algorithms.
/// </summary>
public enum NrpcComputeNetlogonCredentialAlgorithm
{
/// <summary>
/// If AES support is negotiated between the client and the server,
/// the Netlogon credentials are computed using the AES-128 encryption
/// algorithm in 8-bit CFB mode with a zero initialization vector.
/// </summary>
AES128,
/// <summary>
/// If AES is not supported, the Netlogon credentials are computed using
/// DES encryption algorithm in ECB mode.
/// </summary>
DESECB
}
/// <summary>
/// NRPC signature algorithms.
/// </summary>
public enum NrpcSignatureAlgorithm
{
/// <summary>
/// If AES is negotiated, a client generates an NL_AUTH_SHA2_SIGNATURE token
/// that contains an HMAC-SHA256 checksum [RFC4634], a sequence number,
/// and a Confounder (if confidentiality has been requested),
/// to send data protected on the wire.
/// </summary>
HMACSHA256,
/// <summary>
/// If AES is not negotiated, a client generates an Netlogon Signature token
/// that contains an HMAC-MD5 checksum ([RFC2104]), a sequence number,
/// and a Confounder (if confidentiality has been requested),
/// to send data protected on the wire.
/// </summary>
HMACMD5,
}
/// <summary>
/// NRPC seal algorithms.
/// </summary>
public enum NrpcSealAlgorithm
{
/// <summary>
/// If AES is negotiated, the data is encrypted using the AES algorithm.
/// </summary>
AES128,
/// <summary>
/// If AES is not negotiated, the data is encrypted using the RC4 algorithm.
/// </summary>
RC4
}
}
| 31.628866 | 101 | 0.600717 | [
"MIT"
] | 0neb1n/WindowsProtocolTestSuites | ProtoSDK/MS-NRPC/NrpcCryptoAlgorithm.cs | 3,068 | C# |
using System;
namespace GoToWindow.Api
{
public class WindowEntry : IWindowEntry
{
public IntPtr HWnd { get; set; }
public uint ProcessId { get; set; }
public string Title { get; set; }
public IntPtr IconHandle { get; set; }
public bool IsVisible { get; set; }
public string ProcessName { get; set; }
public bool Focus()
{
return WindowToForeground.ForceWindowToForeground(HWnd);
}
public bool IsForeground()
{
return WindowToForeground.GetForegroundWindow() == HWnd;
}
public bool IsSameWindow(IWindowEntry other)
{
if (other == null)
return false;
return ProcessId == other.ProcessId && HWnd == other.HWnd;
}
public override string ToString()
{
return $"{ProcessName} ({ProcessId}): \"{Title}\"";
}
}
}
| 21.052632 | 63 | 0.645 | [
"MIT"
] | vhanla/GoToWindow | GoToWindow.Api/WindowEntry.cs | 802 | C# |
using System;
using Aop.Api.Domain;
using System.Collections.Generic;
using Aop.Api.Response;
namespace Aop.Api.Request
{
/// <summary>
/// AOP API: alipay.open.public.comptest.create
/// </summary>
public class AlipayOpenPublicComptestCreateRequest : IAopRequest<AlipayOpenPublicComptestCreateResponse>
{
/// <summary>
/// 文档发布验证
/// </summary>
public string BizContent { get; set; }
#region IAopRequest Members
private bool needEncrypt=false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AopObject bizModel;
public void SetNeedEncrypt(bool needEncrypt){
this.needEncrypt=needEncrypt;
}
public bool GetNeedEncrypt(){
return this.needEncrypt;
}
public void SetNotifyUrl(string notifyUrl){
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl(){
return this.notifyUrl;
}
public void SetReturnUrl(string returnUrl){
this.returnUrl = returnUrl;
}
public string GetReturnUrl(){
return this.returnUrl;
}
public void SetTerminalType(String terminalType){
this.terminalType=terminalType;
}
public string GetTerminalType(){
return this.terminalType;
}
public void SetTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
public string GetTerminalInfo(){
return this.terminalInfo;
}
public void SetProdCode(String prodCode){
this.prodCode=prodCode;
}
public string GetProdCode(){
return this.prodCode;
}
public string GetApiName()
{
return "alipay.open.public.comptest.create";
}
public void SetApiVersion(string apiVersion){
this.apiVersion=apiVersion;
}
public string GetApiVersion(){
return this.apiVersion;
}
public IDictionary<string, string> GetParameters()
{
AopDictionary parameters = new AopDictionary();
parameters.Add("biz_content", this.BizContent);
return parameters;
}
public AopObject GetBizModel()
{
return this.bizModel;
}
public void SetBizModel(AopObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.572727 | 108 | 0.605476 | [
"Apache-2.0"
] | Varorbc/alipay-sdk-net-all | AlipaySDKNet/Request/AlipayOpenPublicComptestCreateRequest.cs | 2,605 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using Qwack.Core.Basic;
using Qwack.Core.Instruments;
using Qwack.Core.Models;
using Qwack.Dates;
using Qwack.Math;
using Qwack.Math.Extensions;
using Qwack.Paths.Features;
using Qwack.Paths.Regressors;
using Qwack.Transport.BasicTypes;
namespace Qwack.Paths.Payoffs
{
public class MultiPeriodBackPricingOption : IPathProcess, IRequiresFinish, IAssetPathPayoff
{
private readonly object _locker = new();
private readonly List<DateTime[]> _avgDates;
private readonly DateTime _decisionDate;
private readonly OptionType _callPut;
private readonly string _discountCurve;
private readonly Currency _ccy;
private readonly DateTime _settleFixingDate;
private readonly DateTime _payDate;
private readonly string _assetName;
private int _assetIndex;
private readonly string _fxName;
private int _fxIndex;
private List<int[]> _dateIndexes;
private List<int[]> _dateIndexesPast;
private List<int[]> _dateIndexesFuture;
private int[] _nPast;
private int[] _nFuture;
private int[] _nTotal;
private int _decisionDateIx;
private Vector<double>[] _results;
private Vector<double> _notional;
private bool _isComplete;
private double _expiryToSettleCarry;
private readonly Vector<double> _one = new(1.0);
public string RegressionKey => _assetName + (_fxName != null ? $"*{_fxName}" : "");
public LinearAveragePriceRegressor SettlementRegressor { get; set; }
public LinearAveragePriceRegressor[] AverageRegressors { get; set; }
public IAssetFxModel VanillaModel { get; set; }
public MultiPeriodBackPricingOption(string assetName, List<DateTime[]> avgDates, DateTime decisionDate, DateTime settlementFixingDate, DateTime payDate, OptionType callPut, string discountCurve, Currency ccy, double notional)
{
_avgDates = avgDates;
_decisionDate = decisionDate;
_callPut = callPut;
_discountCurve = discountCurve;
_ccy = ccy;
_settleFixingDate = settlementFixingDate;
_payDate = payDate;
_assetName = assetName;
_notional = new Vector<double>(notional);
if (_ccy.Ccy != "USD")
_fxName = $"USD/{_ccy.Ccy}";
AverageRegressors = avgDates.Select(avg => avg.Last() > decisionDate ? new LinearAveragePriceRegressor(decisionDate, avg.Where(x => x > decisionDate).ToArray(), RegressionKey) : null).ToArray();
SettlementRegressor = new LinearAveragePriceRegressor(decisionDate, new[] { _settleFixingDate }, RegressionKey);
}
public bool IsComplete => _isComplete;
public IAssetInstrument AssetInstrument { get; private set; }
public void Finish(IFeatureCollection collection)
{
var dims = collection.GetFeature<IPathMappingFeature>();
_assetIndex = dims.GetDimension(_assetName);
if (!string.IsNullOrEmpty(_fxName))
_fxIndex = dims.GetDimension(_fxName);
var dates = collection.GetFeature<ITimeStepsFeature>();
_dateIndexes = _avgDates
.Select(x => x.Select(y => dates.GetDateIndex(y)).ToArray())
.ToList();
_dateIndexesPast = _avgDates
.Select(y=>y
.Where(x => x <= _decisionDate)
.Select(x => dates.GetDateIndex(x))
.ToArray())
.ToList();
_dateIndexesFuture = _avgDates
.Select(y => y
.Where(x => x > _decisionDate)
.Select(x => dates.GetDateIndex(x))
.ToArray())
.ToList();
_decisionDateIx = dates.GetDateIndex(_decisionDate);
_nPast = _dateIndexesPast.Select(x=>x.Length).ToArray();
_nFuture = _dateIndexesFuture.Select(x => x.Length).ToArray();
_nTotal = _nPast.Select((x,ix)=>x + _nFuture[ix]).ToArray();
var engine = collection.GetFeature<IEngineFeature>();
_results = new Vector<double>[engine.NumberOfPaths / Vector<double>.Count];
if (VanillaModel != null)
{
var curve = VanillaModel.GetPriceCurve(_assetName);
var decisionSpotDate = _decisionDate.AddPeriod(RollType.F, curve.SpotCalendar, curve.SpotLag);
_expiryToSettleCarry = curve.GetPriceForDate(_payDate) / curve.GetPriceForDate(decisionSpotDate);
}
_isComplete = true;
}
public void Process(IPathBlock block)
{
var blockBaseIx = block.GlobalPathIndex;
var nTotalVec = new Vector<double>[_nTotal.Length];
for (var i = 0; i < nTotalVec.Length; i++)
nTotalVec[i] = new Vector<double>(_nTotal[i]);
for (var path = 0; path < block.NumberOfPaths; path += Vector<double>.Count)
{
var steps = block.GetStepsForFactor(path, _assetIndex);
Span<Vector<double>> stepsFx = null;
if (_fxName != null)
stepsFx = block.GetStepsForFactor(path, _fxIndex);
var avgs = new Vector<double>[_dateIndexes.Count];
var avgVec = new Vector<double>((_callPut == OptionType.C) ? double.MaxValue : double.MinValue);
var setReg = new double[Vector<double>.Count];
for (var a = 0; a < _dateIndexes.Count; a++)
{
var pastSum = new Vector<double>(0.0);
for (var p = 0; p < _dateIndexesPast[a].Length; p++)
{
pastSum += steps[_dateIndexesPast[a][p]] * (_fxName != null ? stepsFx[_dateIndexesPast[a][p]] : _one);
}
var spotAtExpiry = steps[_decisionDateIx] * (_fxName != null ? stepsFx[_decisionDateIx] : _one);
if (VanillaModel != null && AverageRegressors[a] == null)
{
avgs[a] = pastSum / nTotalVec[a];
for (var i = 0; i < Vector<double>.Count; i++)
setReg[i] = spotAtExpiry[i] * _expiryToSettleCarry;
}
else
{
var futSum = new double[Vector<double>.Count];
for (var i = 0; i < Vector<double>.Count; i++)
{
futSum[i] = AverageRegressors[a] == null ? 0.0 : AverageRegressors[a].Predict(spotAtExpiry[i]) * _nFuture[a];
setReg[i] = SettlementRegressor.Predict(spotAtExpiry[i]);
}
var futVec = new Vector<double>(futSum);
avgs[a] = (futVec + pastSum) / nTotalVec[a];
}
avgVec = (_callPut == OptionType.C) ?
Vector.Min(avgs[a], avgVec) :
Vector.Max(avgs[a], avgVec);
}
var setVec = new Vector<double>(setReg);
var payoff = (_callPut == OptionType.C) ?
Vector.Max(new Vector<double>(0), setVec - avgVec) :
Vector.Max(new Vector<double>(0), avgVec - setVec);
var resultIx = (blockBaseIx + path) / Vector<double>.Count;
_results[resultIx] = payoff * _notional;
}
}
public void SetupFeatures(IFeatureCollection pathProcessFeaturesCollection)
{
var dates = pathProcessFeaturesCollection.GetFeature<ITimeStepsFeature>();
dates.AddDates(_avgDates.SelectMany(x=>x));
dates.AddDate(_payDate);
dates.AddDate(_decisionDate);
}
public double AverageResult => _results.Select(x =>
{
var vec = new double[Vector<double>.Count];
x.CopyTo(vec);
return vec.Average();
}).Average();
public double[] ResultsByPath
{
get
{
var vecLen = Vector<double>.Count;
var results = new double[_results.Length * vecLen];
for (var i = 0; i < _results.Length; i++)
{
for (var j = 0; j < vecLen; j++)
{
results[i * vecLen + j] = _results[i][j];
}
}
return results;
}
}
public double ResultStdError => _results.SelectMany(x =>
{
var vec = new double[Vector<double>.Count];
x.CopyTo(vec);
return vec;
}).StdDev();
public CashFlowSchedule ExpectedFlows(IAssetFxModel model)
{
var ar = AverageResult;
return new CashFlowSchedule
{
Flows = new List<CashFlow>
{
new CashFlow
{
Fv = ar,
Pv = ar * model.FundingModel.Curves[_discountCurve].GetDf(model.BuildDate,_payDate),
Currency = _ccy,
FlowType = FlowType.FixedAmount,
SettleDate = _payDate,
YearFraction = 1.0
}
}
};
}
public CashFlowSchedule[] ExpectedFlowsByPath(IAssetFxModel model)
{
var df = model.FundingModel.Curves[_discountCurve].GetDf(model.BuildDate, _payDate);
return ResultsByPath.Select(x => new CashFlowSchedule
{
Flows = new List<CashFlow>
{
new CashFlow
{
Fv = x,
Pv = x * df,
Currency = _ccy,
FlowType = FlowType.FixedAmount,
SettleDate = _payDate,
YearFraction = 1.0
}
}
}).ToArray();
}
}
}
| 40.181132 | 234 | 0.518971 | [
"MIT"
] | cetusfinance/qwack | src/Qwack.Paths/Payoffs/MultiPeriodBackPricingOption.cs | 10,648 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace InterfacesApp.Entities
{
public abstract class Employee : Human
{
public int Id { get; set; }
public string FullName { get; set; }
public void Print()
{
Console.WriteLine($"{Id} - {FullName}");
}
public abstract string GetInfo();
}
}
| 20.315789 | 52 | 0.590674 | [
"MIT"
] | sedc-codecademy/skwd8-06-csharpadv | g3/Class-04/Class3Recap/InterfacesApp/Entities/Employee.cs | 388 | C# |
/*
* Copyright (c) 2016 Google 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.
*/
// [START complete]
using System;
using Google.Cloud.BigQuery.V2;
namespace GoogleCloudSamples
{
public class BigquerySample
{
const string usage = @"Usage:
BigquerySample <project_id>";
private static void Main(string[] args)
{
string projectId = null;
if (args.Length == 0)
{
Console.WriteLine(usage);
}
else
{
projectId = args[0];
// [START setup]
// By default, the Google.Cloud.BigQuery.V2 library client will authenticate
// using the service account file (created in the Google Developers
// Console) specified by the GOOGLE_APPLICATION_CREDENTIALS
// environment variable. If you are running on
// a Google Compute Engine VM, authentication is completely
// automatic.
var client = BigQueryClient.Create(projectId);
// [END setup]
// [START query]
var table = client.GetTable("bigquery-public-data", "samples", "shakespeare");
string query = $@"SELECT corpus AS title, COUNT(*) AS unique_words FROM `{table.FullyQualifiedId}`
GROUP BY title ORDER BY unique_words DESC LIMIT 42";
var result = client.ExecuteQuery(query);
// [END query]
// [START print_results]
Console.Write("\nQuery Results:\n------------\n");
foreach (var row in result.GetRows())
{
Console.WriteLine($"{row["title"]}: {row["unique_words"]}");
}
// [END print_results]
}
Console.WriteLine("\nPress any key...");
Console.ReadKey();
}
}
}
// [END complete]
| 37.455882 | 116 | 0.5532 | [
"ECL-2.0",
"Apache-2.0"
] | vecalciskay/dotnet-docs-samples | bigquery/api/GettingStarted/Program.cs | 2,549 | C# |
using Microsoft.AspNetCore.Authentication;
using System.Collections.Generic;
namespace Diagnostics.CompilerHost.Security.CertificateAuth
{
public class CertificateAuthOptions: AuthenticationSchemeOptions
{
public new CertificateAuthEvents Events
{
get
{
return (CertificateAuthEvents)base.Events;
}
set
{
base.Events = value;
}
}
/// <summary>
/// List of Allowed Cert Subject Names.
/// </summary>
public IEnumerable<string> AllowedSubjectNames { get; set; }
/// <summary>
/// List of Allowed Cert Issuers.
/// </summary>
public IEnumerable<string> AllowedIssuers { get; set; }
}
}
| 26.4 | 70 | 0.565657 | [
"MIT"
] | Azure/Azure-AppServices-Diagnostics | src/Diagnostics.CompilerHost/Security/CertificateAuth/CertificateAuthOptions.cs | 794 | C# |
using Microsoft.Win32;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
namespace Literay
{
public partial class MainWindow : Window
{
private bool FreshWorkspace
{
get
{
if (tabMain.Items.Count == 1)
{
LuaTabPage tabPage = (tabMain.SelectedItem as TabItem).Tag as LuaTabPage;
return tabPage.FilePath == null && tabPage.Text == "";
}
else
{
return false;
}
}
}
private bool AnyFilesUnsaved
{
get
{
return tabMain.Items.Cast<TabItem>().Any(tabItem => !(tabItem.Tag as LuaTabPage).IsSaved);
}
}
private LuaScript Script;
public MainWindow()
{
InitializeComponent();
propMain.SelectedObject = RenderProperties.Default;
mnuFileNew_Click(null, RoutedEventArgs.Empty as RoutedEventArgs);
DispatcherTimer enableTimer = new DispatcherTimer();
enableTimer.Tick += new EventHandler(EnableTimer_Tick);
enableTimer.Interval = TimeSpan.FromMilliseconds(100);
enableTimer.Start();
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Idle;
}
private void Window_Closing(object sender, CancelEventArgs e)
{
if (mnuScriptRun.IsEnabled)
{
if (!FreshWorkspace && AnyFilesUnsaved)
{
switch (MessageBox.Show("Do you want to save changes to unsaved files?", "Confirmation", MessageBoxButton.YesNoCancel, MessageBoxImage.Question))
{
case MessageBoxResult.Yes:
if (!FileSaveAll()) e.Cancel = true;
break;
case MessageBoxResult.Cancel:
e.Cancel = true;
break;
}
}
}
else
{
Environment.Exit(0);
}
}
private void mnuFileNew_Click(object sender, RoutedEventArgs e)
{
FileNew();
}
private void mnuFileOpen_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.DefaultExt = "lua";
dialog.Filter = "Lua script files (*.lua)|*.lua";
dialog.Multiselect = true;
if (dialog.ShowDialog().Value)
{
if (FreshWorkspace) tabMain.Items.Clear();
foreach (string fileName in dialog.FileNames)
{
LuaTabPage tabPage = new LuaTabPage();
tabPage.FilePath = fileName;
tabPage.Text = File.ReadAllText(fileName);
tabPage.IsSaved = true;
tabMain.Items.Add(tabPage.TabItem);
tabPage.TabItem.IsSelected = true;
tabPage.TabItem.MouseUp += tabMain_MouseUp;
}
}
}
private void mnuFileClose_Click(object sender, RoutedEventArgs e)
{
FileClose((tabMain.SelectedItem as TabItem).Tag as LuaTabPage);
}
private void mnuFileSave_Click(object sender, RoutedEventArgs e)
{
FileSave((tabMain.SelectedItem as TabItem).Tag as LuaTabPage);
}
private void mnuFileSaveAs_Click(object sender, RoutedEventArgs e)
{
FileSaveAs((tabMain.SelectedItem as TabItem).Tag as LuaTabPage);
}
private void mnuFileSaveAll_Click(object sender, RoutedEventArgs e)
{
FileSaveAll();
}
private void mnuFileExit_Click(object sender, RoutedEventArgs e)
{
Close();
}
private void mnuEditUndo_Click(object sender, RoutedEventArgs e)
{
LuaTabPage tabPage = (tabMain.SelectedItem as TabItem).Tag as LuaTabPage;
tabPage.TextBox.Undo();
}
private void mnuEditRedo_Click(object sender, RoutedEventArgs e)
{
LuaTabPage tabPage = (tabMain.SelectedItem as TabItem).Tag as LuaTabPage;
tabPage.TextBox.Redo();
}
private void mnuEditCut_Click(object sender, RoutedEventArgs e)
{
LuaTabPage tabPage = (tabMain.SelectedItem as TabItem).Tag as LuaTabPage;
tabPage.TextBox.Cut();
}
private void mnuEditCopy_Click(object sender, RoutedEventArgs e)
{
LuaTabPage tabPage = (tabMain.SelectedItem as TabItem).Tag as LuaTabPage;
tabPage.TextBox.Copy();
}
private void mnuEditPaste_Click(object sender, RoutedEventArgs e)
{
LuaTabPage tabPage = (tabMain.SelectedItem as TabItem).Tag as LuaTabPage;
tabPage.TextBox.Paste();
}
private void mnuEditSelectAll_Click(object sender, RoutedEventArgs e)
{
LuaTabPage tabPage = (tabMain.SelectedItem as TabItem).Tag as LuaTabPage;
tabPage.TextBox.SelectAll();
}
private void mnuViewCloseAllRenderWindows_Click(object sender, RoutedEventArgs e)
{
WindowRenderer.AllWindows.ToList().ForEach(renderWindow => renderWindow.Close());
}
private void mnuScriptRun_Click(object sender, RoutedEventArgs e)
{
mnuScriptRun.IsEnabled = btnScriptRun.IsEnabled = false;
mnuScriptStop.IsEnabled = btnScriptStop.IsEnabled = true;
LuaTabPage tabPage = (tabMain.SelectedItem as TabItem).Tag as LuaTabPage;
if (tabPage.FilePath != null) FileSave(tabPage);
Script = new LuaScript(propMain.SelectedObject as RenderProperties, tabPage.FileName, tabPage.FilePath);
Script.Run(tabPage.Text);
mnuScriptRun.IsEnabled = btnScriptRun.IsEnabled = true;
mnuScriptStop.IsEnabled = btnScriptStop.IsEnabled = false;
}
private void mnuScriptStop_Click(object sender, RoutedEventArgs e)
{
Script.Stop();
mnuScriptRun.IsEnabled = btnScriptRun.IsEnabled = true;
mnuScriptStop.IsEnabled = btnScriptStop.IsEnabled = false;
}
private void mnuRenderPropertiesLoadDefault_Click(object sender, RoutedEventArgs e)
{
propMain.SelectedObject = RenderProperties.Default;
}
private void mnuHelpAbout_Click(object sender, RoutedEventArgs e)
{
new WindowAbout().ShowDialog();
}
private void tabMain_MouseUp(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Middle)
{
FileClose((sender as TabItem).Tag as LuaTabPage);
}
}
private void EnableTimer_Tick(object sender, EventArgs e)
{
LuaTabPage tabPage = (tabMain.SelectedItem as TabItem).Tag as LuaTabPage;
mnuEditUndo.IsEnabled = cmnuEditUndo.IsEnabled = btnEditUndo.IsEnabled = tabPage.TextBox.CanUndo;
mnuEditRedo.IsEnabled = cmnuEditRedo.IsEnabled = btnEditRedo.IsEnabled = tabPage.TextBox.CanRedo;
mnuEditCut.IsEnabled = cmnuEditCut.IsEnabled = btnEditCut.IsEnabled = tabPage.TextBox.SelectionLength > 0;
mnuEditCopy.IsEnabled = cmnuEditCopy.IsEnabled = btnEditCopy.IsEnabled = tabPage.TextBox.SelectionLength > 0;
mnuViewCloseAllRenderWindows.IsEnabled = WindowRenderer.AllWindows.Count > 0;
}
private void FileNew()
{
int index = 1;
while (tabMain.Items.Cast<TabItem>().Any(tabItem => (tabItem.Tag as LuaTabPage).FileName == LuaTabPage.GenerateNewFilename(index)))
{
index++;
}
LuaTabPage tabPage = new LuaTabPage();
tabPage.FileName = LuaTabPage.GenerateNewFilename(index);
tabMain.Items.Add(tabPage.TabItem);
tabPage.TabItem.IsSelected = true;
tabPage.TabItem.MouseUp += tabMain_MouseUp;
}
private void FileClose(LuaTabPage tabPage)
{
bool close;
if (tabPage.IsSaved || tabPage.FilePath == null && tabPage.Text == "")
{
close = true;
}
else
{
switch (MessageBox.Show("Do you want to save changes to " + tabPage.FileName + "?", "Confirmation", MessageBoxButton.YesNoCancel, MessageBoxImage.Question))
{
case MessageBoxResult.Yes:
close = FileSave(tabPage);
break;
case MessageBoxResult.No:
close = true;
break;
default:
close = false;
break;
}
}
if (close)
{
tabMain.Items.Remove(tabPage.TabItem);
if (tabMain.Items.Count == 0) FileNew();
}
}
private bool FileSave(LuaTabPage tabPage)
{
if (tabPage.FilePath == null)
{
return FileSaveAs(tabPage);
}
else
{
tabPage.IsSaved = true;
File.WriteAllText(tabPage.FilePath, tabPage.Text);
return true;
}
}
private bool FileSaveAs(LuaTabPage tabPage)
{
SaveFileDialog dialog = new SaveFileDialog();
dialog.DefaultExt = "lua";
dialog.Filter = "Lua script files (*.lua)|*.lua";
dialog.FileName = tabPage.FileName;
if (dialog.ShowDialog().Value)
{
tabPage.FilePath = dialog.FileName;
tabPage.IsSaved = true;
File.WriteAllText(tabPage.FilePath, tabPage.Text);
return true;
}
else
{
return false;
}
}
private bool FileSaveAll()
{
foreach (TabItem tabItem in tabMain.Items)
{
if (!FileSave(tabItem.Tag as LuaTabPage)) return false;
}
return true;
}
}
} | 30.208481 | 161 | 0.686747 | [
"BSD-2-Clause"
] | bytecode77/literay | Literay/Windows/MainWindow.xaml.cs | 8,551 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace SimpleOverlayForm.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
}
}
| 34.625 | 98 | 0.679603 | [
"MIT"
] | OnTheFenceDevelopment/xamarinforms | SimpleOverlayForm/SimpleOverlayForm/SimpleOverlayForm.iOS/AppDelegate.cs | 1,110 | C# |
/*******************************************************************************
* Copyright 2012-2019 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.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.Backup;
using Amazon.Backup.Model;
namespace Amazon.PowerShell.Cmdlets.BAK
{
/// <summary>
/// Returns the current service opt-in settings for the Region. If service opt-in is enabled
/// for a service, Backup tries to protect that service's resources in this Region, when
/// the resource is included in an on-demand backup or scheduled backup plan. Otherwise,
/// Backup does not try to protect that service's resources in this Region.
/// </summary>
[Cmdlet("Get", "BAKRegionSetting")]
[OutputType("System.String")]
[AWSCmdlet("Calls the AWS Backup DescribeRegionSettings API operation.", Operation = new[] {"DescribeRegionSettings"}, SelectReturnType = typeof(Amazon.Backup.Model.DescribeRegionSettingsResponse))]
[AWSCmdletOutput("System.String or Amazon.Backup.Model.DescribeRegionSettingsResponse",
"This cmdlet returns a collection of System.String objects.",
"The service call response (type Amazon.Backup.Model.DescribeRegionSettingsResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class GetBAKRegionSettingCmdlet : AmazonBackupClientCmdlet, IExecutor
{
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The default value is 'ResourceTypeOptInPreference'.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.Backup.Model.DescribeRegionSettingsResponse).
/// Specifying the name of a property of type Amazon.Backup.Model.DescribeRegionSettingsResponse will result in that property being returned.
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "ResourceTypeOptInPreference";
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate<Amazon.Backup.Model.DescribeRegionSettingsResponse, GetBAKRegionSettingCmdlet>(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
}
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
// create request
var request = new Amazon.Backup.Model.DescribeRegionSettingsRequest();
CmdletOutput output;
// issue call
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
pipelineOutput = cmdletContext.Select(response, this);
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
return output;
}
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.Backup.Model.DescribeRegionSettingsResponse CallAWSServiceOperation(IAmazonBackup client, Amazon.Backup.Model.DescribeRegionSettingsRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Backup", "DescribeRegionSettings");
try
{
#if DESKTOP
return client.DescribeRegionSettings(request);
#elif CORECLR
return client.DescribeRegionSettingsAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public System.Func<Amazon.Backup.Model.DescribeRegionSettingsResponse, GetBAKRegionSettingCmdlet, object> Select { get; set; } =
(response, cmdlet) => response.ResourceTypeOptInPreference;
}
}
}
| 42.922078 | 202 | 0.614221 | [
"Apache-2.0"
] | aws/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/Backup/Basic/Get-BAKRegionSetting-Cmdlet.cs | 6,610 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.