content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using System.Collections.Generic;
namespace EntityFrameworkCore.LocalStorage.Serializer
{
interface ISerializer
{
Dictionary<TKey, object[]> Deserialize<TKey>(string list, Dictionary<TKey, object[]> newList);
string Serialize<TKey>(Dictionary<TKey, object[]> list);
}
}
| 25.083333 | 102 | 0.710963 | [
"MIT"
] | TheRealDuckboy/EntityFrameworkCore.LocalStorage | src/EntityFrameworkCore.LocalStorage/Serializer/ISerializer.cs | 303 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.Core;
namespace Azure.ResourceManager.Sql
{
internal partial class ServerAutomaticTuningRestOperations
{
private readonly string _userAgent;
private readonly HttpPipeline _pipeline;
private readonly Uri _endpoint;
private readonly string _apiVersion;
/// <summary> Initializes a new instance of ServerAutomaticTuningRestOperations. </summary>
/// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
/// <param name="applicationId"> The application id to use for user agent. </param>
/// <param name="endpoint"> server parameter. </param>
/// <param name="apiVersion"> Api Version. </param>
/// <exception cref="ArgumentNullException"> <paramref name="pipeline"/> or <paramref name="apiVersion"/> is null. </exception>
public ServerAutomaticTuningRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default)
{
_pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline));
_endpoint = endpoint ?? new Uri("https://management.azure.com");
_apiVersion = apiVersion ?? "2020-11-01-preview";
_userAgent = Core.HttpMessageUtilities.GetUserAgentName(this, applicationId);
}
internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string serverName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Sql/servers/", false);
uri.AppendPath(serverName, true);
uri.AppendPath("/automaticTuning/current", false);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Retrieves server automatic tuning options. </summary>
/// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="serverName"> The name of the server. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="serverName"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="serverName"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response<ServerAutomaticTuningData>> GetAsync(string subscriptionId, string resourceGroupName, string serverName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(serverName, nameof(serverName));
using var message = CreateGetRequest(subscriptionId, resourceGroupName, serverName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
ServerAutomaticTuningData value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = ServerAutomaticTuningData.DeserializeServerAutomaticTuningData(document.RootElement);
return Response.FromValue(value, message.Response);
}
case 404:
return Response.FromValue((ServerAutomaticTuningData)null, message.Response);
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> Retrieves server automatic tuning options. </summary>
/// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="serverName"> The name of the server. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="serverName"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="serverName"/> is an empty string, and was expected to be non-empty. </exception>
public Response<ServerAutomaticTuningData> Get(string subscriptionId, string resourceGroupName, string serverName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(serverName, nameof(serverName));
using var message = CreateGetRequest(subscriptionId, resourceGroupName, serverName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
ServerAutomaticTuningData value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = ServerAutomaticTuningData.DeserializeServerAutomaticTuningData(document.RootElement);
return Response.FromValue(value, message.Response);
}
case 404:
return Response.FromValue((ServerAutomaticTuningData)null, message.Response);
default:
throw new RequestFailedException(message.Response);
}
}
internal HttpMessage CreateUpdateRequest(string subscriptionId, string resourceGroupName, string serverName, ServerAutomaticTuningData parameters)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Patch;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Sql/servers/", false);
uri.AppendPath(serverName, true);
uri.AppendPath("/automaticTuning/current", false);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Content-Type", "application/json");
var content = new Utf8JsonRequestContent();
content.JsonWriter.WriteObjectValue(parameters);
request.Content = content;
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Update automatic tuning options on server. </summary>
/// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="serverName"> The name of the server. </param>
/// <param name="parameters"> The requested automatic tuning resource state. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="parameters"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="serverName"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response<ServerAutomaticTuningData>> UpdateAsync(string subscriptionId, string resourceGroupName, string serverName, ServerAutomaticTuningData parameters, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(serverName, nameof(serverName));
Argument.AssertNotNull(parameters, nameof(parameters));
using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, serverName, parameters);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
ServerAutomaticTuningData value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = ServerAutomaticTuningData.DeserializeServerAutomaticTuningData(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> Update automatic tuning options on server. </summary>
/// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="serverName"> The name of the server. </param>
/// <param name="parameters"> The requested automatic tuning resource state. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="parameters"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="serverName"/> is an empty string, and was expected to be non-empty. </exception>
public Response<ServerAutomaticTuningData> Update(string subscriptionId, string resourceGroupName, string serverName, ServerAutomaticTuningData parameters, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(serverName, nameof(serverName));
Argument.AssertNotNull(parameters, nameof(parameters));
using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, serverName, parameters);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
ServerAutomaticTuningData value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = ServerAutomaticTuningData.DeserializeServerAutomaticTuningData(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
}
}
| 63.507109 | 227 | 0.663134 | [
"MIT"
] | KurnakovMaksim/azure-sdk-for-net | sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/RestOperations/ServerAutomaticTuningRestOperations.cs | 13,400 | C# |
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using ShareBook.Data;
using ShareBook.Data.Repositories;
using ShareBook.Domain.Interfaces;
using ShareBook.Domain.Services;
using ShareBook.GoogleBooks;
namespace ShareBook.WebApi
{
public class Startup
{
private readonly IWebHostEnvironment _env;
private readonly IConfiguration _configuration;
public Startup(IWebHostEnvironment _env, IConfiguration _configuration)
{
this._env = _env;
this._configuration = _configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ShareBookDbContext>(options =>
options.UseNpgsql(
_configuration.GetConnectionString("DefaultConnection"),
x => x.MigrationsAssembly("ShareBook.Data")));
services.AddIdentityCore<AppUser>()
.AddEntityFrameworkStores<ShareBookDbContext>()
.AddDefaultTokenProviders();
services.AddHttpClient();
services.AddScoped<IUserService, UserService>();
services.AddScoped<IBookService, BookService>();
services.AddScoped<IBookRepository, BookRepository>();
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<ILanguageRepository, LanguageRepository>();
services.AddScoped<IInternetBookService, GoogleBookService>();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "ShareBook.WebApi", Version = "v1" });
var securityScheme = new OpenApiSecurityScheme
{
Name = "JWT Authentication",
Description = "Enter JWT Bearer token **_only_**",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "bearer", // must be lower case
BearerFormat = "JWT",
Reference = new OpenApiReference
{
Id = JwtBearerDefaults.AuthenticationScheme,
Type = ReferenceType.SecurityScheme
}
};
c.AddSecurityDefinition(securityScheme.Reference.Id, securityScheme);
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{securityScheme, new string[] { }}
});
});
services.AddCors();
services.AddControllers();
// Adding Authentication
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
// Adding Jwt Bearer
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = false,
ValidateAudience = false,
//ValidAudience = _configuration["JWT:ValidAudience"],
//ValidIssuer = _configuration["JWT:ValidIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"]))
};
});
// configure DI for application service
}
// 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();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ShareBook.WebApi v1"));
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
| 38.578125 | 117 | 0.596193 | [
"MIT"
] | paloni/sharebook | backend/src/ShareBook.WebApi/Startup.cs | 4,938 | C# |
namespace Octokit.GraphQL.Model
{
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using Octokit.GraphQL.Core;
using Octokit.GraphQL.Core.Builders;
/// <summary>
/// An Issue is a place to discuss ideas, enhancements, tasks, and bugs for a project.
/// </summary>
public class Issue : QueryableValue<Issue>
{
internal Issue(Expression expression) : base(expression)
{
}
/// <summary>
/// Reason that the conversation was locked.
/// </summary>
public LockReason? ActiveLockReason { get; }
/// <summary>
/// A list of Users assigned to this object.
/// </summary>
/// <param name="first">Returns the first _n_ elements from the list.</param>
/// <param name="after">Returns the elements in the list that come after the specified cursor.</param>
/// <param name="last">Returns the last _n_ elements from the list.</param>
/// <param name="before">Returns the elements in the list that come before the specified cursor.</param>
public UserConnection Assignees(Arg<int>? first = null, Arg<string>? after = null, Arg<int>? last = null, Arg<string>? before = null) => this.CreateMethodCall(x => x.Assignees(first, after, last, before), Octokit.GraphQL.Model.UserConnection.Create);
/// <summary>
/// The actor who authored the comment.
/// </summary>
public IActor Author => this.CreateProperty(x => x.Author, Octokit.GraphQL.Model.Internal.StubIActor.Create);
/// <summary>
/// Author's association with the subject of the comment.
/// </summary>
public CommentAuthorAssociation AuthorAssociation { get; }
/// <summary>
/// Identifies the body of the issue.
/// </summary>
public string Body { get; }
/// <summary>
/// Identifies the body of the issue rendered to HTML.
/// </summary>
public string BodyHTML { get; }
/// <summary>
/// Identifies the body of the issue rendered to text.
/// </summary>
public string BodyText { get; }
/// <summary>
/// `true` if the object is closed (definition of closed may depend on type)
/// </summary>
public bool Closed { get; }
/// <summary>
/// Identifies the date and time when the object was closed.
/// </summary>
public DateTimeOffset? ClosedAt { get; }
/// <summary>
/// A list of comments associated with the Issue.
/// </summary>
/// <param name="first">Returns the first _n_ elements from the list.</param>
/// <param name="after">Returns the elements in the list that come after the specified cursor.</param>
/// <param name="last">Returns the last _n_ elements from the list.</param>
/// <param name="before">Returns the elements in the list that come before the specified cursor.</param>
public IssueCommentConnection Comments(Arg<int>? first = null, Arg<string>? after = null, Arg<int>? last = null, Arg<string>? before = null) => this.CreateMethodCall(x => x.Comments(first, after, last, before), Octokit.GraphQL.Model.IssueCommentConnection.Create);
/// <summary>
/// Identifies the date and time when the object was created.
/// </summary>
public DateTimeOffset CreatedAt { get; }
/// <summary>
/// Check if this comment was created via an email reply.
/// </summary>
public bool CreatedViaEmail { get; }
/// <summary>
/// Identifies the primary key from the database.
/// </summary>
public int? DatabaseId { get; }
/// <summary>
/// The actor who edited the comment.
/// </summary>
public IActor Editor => this.CreateProperty(x => x.Editor, Octokit.GraphQL.Model.Internal.StubIActor.Create);
public ID Id { get; }
/// <summary>
/// Check if this comment was edited and includes an edit with the creation data
/// </summary>
public bool IncludesCreatedEdit { get; }
/// <summary>
/// A list of labels associated with the object.
/// </summary>
/// <param name="first">Returns the first _n_ elements from the list.</param>
/// <param name="after">Returns the elements in the list that come after the specified cursor.</param>
/// <param name="last">Returns the last _n_ elements from the list.</param>
/// <param name="before">Returns the elements in the list that come before the specified cursor.</param>
public LabelConnection Labels(Arg<int>? first = null, Arg<string>? after = null, Arg<int>? last = null, Arg<string>? before = null) => this.CreateMethodCall(x => x.Labels(first, after, last, before), Octokit.GraphQL.Model.LabelConnection.Create);
/// <summary>
/// The moment the editor made the last edit
/// </summary>
public DateTimeOffset? LastEditedAt { get; }
/// <summary>
/// `true` if the object is locked
/// </summary>
public bool Locked { get; }
/// <summary>
/// Identifies the milestone associated with the issue.
/// </summary>
public Milestone Milestone => this.CreateProperty(x => x.Milestone, Octokit.GraphQL.Model.Milestone.Create);
/// <summary>
/// Identifies the issue number.
/// </summary>
public int Number { get; }
/// <summary>
/// A list of Users that are participating in the Issue conversation.
/// </summary>
/// <param name="first">Returns the first _n_ elements from the list.</param>
/// <param name="after">Returns the elements in the list that come after the specified cursor.</param>
/// <param name="last">Returns the last _n_ elements from the list.</param>
/// <param name="before">Returns the elements in the list that come before the specified cursor.</param>
public UserConnection Participants(Arg<int>? first = null, Arg<string>? after = null, Arg<int>? last = null, Arg<string>? before = null) => this.CreateMethodCall(x => x.Participants(first, after, last, before), Octokit.GraphQL.Model.UserConnection.Create);
/// <summary>
/// List of project cards associated with this issue.
/// </summary>
/// <param name="first">Returns the first _n_ elements from the list.</param>
/// <param name="after">Returns the elements in the list that come after the specified cursor.</param>
/// <param name="last">Returns the last _n_ elements from the list.</param>
/// <param name="before">Returns the elements in the list that come before the specified cursor.</param>
/// <param name="archivedStates">A list of archived states to filter the cards by</param>
public ProjectCardConnection ProjectCards(Arg<int>? first = null, Arg<string>? after = null, Arg<int>? last = null, Arg<string>? before = null, Arg<IEnumerable<ProjectCardArchivedState?>>? archivedStates = null) => this.CreateMethodCall(x => x.ProjectCards(first, after, last, before, archivedStates), Octokit.GraphQL.Model.ProjectCardConnection.Create);
/// <summary>
/// Identifies when the comment was published at.
/// </summary>
public DateTimeOffset? PublishedAt { get; }
/// <summary>
/// A list of reactions grouped by content left on the subject.
/// </summary>
public IQueryableList<ReactionGroup> ReactionGroups => this.CreateProperty(x => x.ReactionGroups);
/// <summary>
/// A list of Reactions left on the Issue.
/// </summary>
/// <param name="first">Returns the first _n_ elements from the list.</param>
/// <param name="after">Returns the elements in the list that come after the specified cursor.</param>
/// <param name="last">Returns the last _n_ elements from the list.</param>
/// <param name="before">Returns the elements in the list that come before the specified cursor.</param>
/// <param name="content">Allows filtering Reactions by emoji.</param>
/// <param name="orderBy">Allows specifying the order in which reactions are returned.</param>
public ReactionConnection Reactions(Arg<int>? first = null, Arg<string>? after = null, Arg<int>? last = null, Arg<string>? before = null, Arg<ReactionContent>? content = null, Arg<ReactionOrder>? orderBy = null) => this.CreateMethodCall(x => x.Reactions(first, after, last, before, content, orderBy), Octokit.GraphQL.Model.ReactionConnection.Create);
/// <summary>
/// The repository associated with this node.
/// </summary>
public Repository Repository => this.CreateProperty(x => x.Repository, Octokit.GraphQL.Model.Repository.Create);
/// <summary>
/// The HTTP path for this issue
/// </summary>
public string ResourcePath { get; }
/// <summary>
/// Identifies the state of the issue.
/// </summary>
public IssueState State { get; }
/// <summary>
/// A list of events, comments, commits, etc. associated with the issue.
/// </summary>
/// <param name="first">Returns the first _n_ elements from the list.</param>
/// <param name="after">Returns the elements in the list that come after the specified cursor.</param>
/// <param name="last">Returns the last _n_ elements from the list.</param>
/// <param name="before">Returns the elements in the list that come before the specified cursor.</param>
/// <param name="since">Allows filtering timeline events by a `since` timestamp.</param>
public IssueTimelineConnection Timeline(Arg<int>? first = null, Arg<string>? after = null, Arg<int>? last = null, Arg<string>? before = null, Arg<DateTimeOffset>? since = null) => this.CreateMethodCall(x => x.Timeline(first, after, last, before, since), Octokit.GraphQL.Model.IssueTimelineConnection.Create);
/// <summary>
/// Identifies the issue title.
/// </summary>
public string Title { get; }
/// <summary>
/// Identifies the date and time when the object was last updated.
/// </summary>
public DateTimeOffset UpdatedAt { get; }
/// <summary>
/// The HTTP URL for this issue
/// </summary>
public string Url { get; }
/// <summary>
/// A list of edits to this content.
/// </summary>
/// <param name="first">Returns the first _n_ elements from the list.</param>
/// <param name="after">Returns the elements in the list that come after the specified cursor.</param>
/// <param name="last">Returns the last _n_ elements from the list.</param>
/// <param name="before">Returns the elements in the list that come before the specified cursor.</param>
public UserContentEditConnection UserContentEdits(Arg<int>? first = null, Arg<string>? after = null, Arg<int>? last = null, Arg<string>? before = null) => this.CreateMethodCall(x => x.UserContentEdits(first, after, last, before), Octokit.GraphQL.Model.UserContentEditConnection.Create);
/// <summary>
/// Can user react to this subject
/// </summary>
public bool ViewerCanReact { get; }
/// <summary>
/// Check if the viewer is able to change their subscription status for the repository.
/// </summary>
public bool ViewerCanSubscribe { get; }
/// <summary>
/// Check if the current viewer can update this object.
/// </summary>
public bool ViewerCanUpdate { get; }
/// <summary>
/// Reasons why the current viewer can not update this comment.
/// </summary>
public IEnumerable<CommentCannotUpdateReason> ViewerCannotUpdateReasons { get; }
/// <summary>
/// Did the viewer author this comment.
/// </summary>
public bool ViewerDidAuthor { get; }
/// <summary>
/// Identifies if the viewer is watching, not watching, or ignoring the subscribable entity.
/// </summary>
public SubscriptionState? ViewerSubscription { get; }
internal static Issue Create(Expression expression)
{
return new Issue(expression);
}
}
} | 48.804688 | 362 | 0.623659 | [
"MIT"
] | ChilliCream/octokit.graphql.net | Octokit.GraphQL/Model/Issue.cs | 12,494 | C# |
#if !NETSTANDARD13
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the athena-2017-05-18.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Threading;
using System.Threading.Tasks;
using Amazon.Runtime;
namespace Amazon.Athena.Model
{
/// <summary>
/// Base class for ListDataCatalogs paginators.
/// </summary>
internal sealed partial class ListDataCatalogsPaginator : IPaginator<ListDataCatalogsResponse>, IListDataCatalogsPaginator
{
private readonly IAmazonAthena _client;
private readonly ListDataCatalogsRequest _request;
private int _isPaginatorInUse = 0;
/// <summary>
/// Enumerable containing all full responses for the operation
/// </summary>
public IPaginatedEnumerable<ListDataCatalogsResponse> Responses => new PaginatedResponse<ListDataCatalogsResponse>(this);
/// <summary>
/// Enumerable containing all of the DataCatalogsSummary
/// </summary>
public IPaginatedEnumerable<DataCatalogSummary> DataCatalogsSummary =>
new PaginatedResultKeyResponse<ListDataCatalogsResponse, DataCatalogSummary>(this, (i) => i.DataCatalogsSummary);
internal ListDataCatalogsPaginator(IAmazonAthena client, ListDataCatalogsRequest request)
{
this._client = client;
this._request = request;
}
#if BCL
IEnumerable<ListDataCatalogsResponse> IPaginator<ListDataCatalogsResponse>.Paginate()
{
if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0)
{
throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance.");
}
var nextToken = _request.NextToken;
ListDataCatalogsResponse response;
do
{
_request.NextToken = nextToken;
response = _client.ListDataCatalogs(_request);
nextToken = response.NextToken;
yield return response;
}
while (nextToken != null);
}
#endif
#if AWS_ASYNC_ENUMERABLES_API
async IAsyncEnumerable<ListDataCatalogsResponse> IPaginator<ListDataCatalogsResponse>.PaginateAsync(CancellationToken cancellationToken = default)
{
if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0)
{
throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance.");
}
var nextToken = _request.NextToken;
ListDataCatalogsResponse response;
do
{
_request.NextToken = nextToken;
response = await _client.ListDataCatalogsAsync(_request, cancellationToken).ConfigureAwait(false);
nextToken = response.NextToken;
cancellationToken.ThrowIfCancellationRequested();
yield return response;
}
while (nextToken != null);
}
#endif
}
}
#endif | 38.845361 | 154 | 0.664278 | [
"Apache-2.0"
] | orinem/aws-sdk-net | sdk/src/Services/Athena/Generated/Model/_bcl45+netstandard/ListDataCatalogsPaginator.cs | 3,768 | C# |
//
// StaticEventSubscriptionIssue.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using ICSharpCode.NRefactory.PatternMatching;
using System.Collections.Generic;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.Refactoring;
using Mono.CSharp;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.CSharp.Resolver;
using System.Linq;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[IssueDescription("Static event removal check",
Description = "Checks if static events are removed",
Category = IssueCategories.CodeQualityIssues,
Severity = Severity.Warning)]
public class StaticEventSubscriptionIssue : GatherVisitorCodeIssueProvider
{
protected override IGatherVisitor CreateVisitor(BaseRefactoringContext context)
{
return new GatherVisitor(context);
}
class GatherVisitor : GatherVisitorBase<StaticEventSubscriptionIssue>
{
public GatherVisitor (BaseRefactoringContext ctx) : base (ctx)
{
}
public override void VisitSyntaxTree(SyntaxTree syntaxTree)
{
base.VisitSyntaxTree(syntaxTree);
foreach (var assignedEvent in assignedEvents) {
addedEvents.Remove(assignedEvent);
}
foreach (var hs in removedEvents) {
HashSet<Tuple<IMember, AssignmentExpression>> h;
if (!addedEvents.TryGetValue(hs.Key, out h))
continue;
foreach (var evt in hs.Value) {
restart:
foreach (var m in h) {
if (m.Item1 == evt) {
h.Remove(m);
goto restart;
}
}
}
}
foreach (var added in addedEvents) {
foreach (var usage in added.Value) {
AddIssue(new CodeIssue(usage.Item2.OperatorToken,
ctx.TranslateString("Subscription to static events without unsubscription may cause memory leaks.")));
}
}
}
public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
{
if (methodDeclaration.HasModifier(Modifiers.Static))
return;
base.VisitMethodDeclaration(methodDeclaration);
}
public override void VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration)
{
if (constructorDeclaration.HasModifier(Modifiers.Static))
return;
base.VisitConstructorDeclaration(constructorDeclaration);
}
readonly Dictionary<IMember, HashSet<Tuple<IMember, AssignmentExpression>>> addedEvents = new Dictionary<IMember, HashSet<Tuple<IMember, AssignmentExpression>>>();
readonly Dictionary<IMember, HashSet<IMember>> removedEvents = new Dictionary<IMember, HashSet<IMember>>();
readonly HashSet<IMember> assignedEvents = new HashSet<IMember> ();
public override void VisitAssignmentExpression(AssignmentExpression assignmentExpression)
{
base.VisitAssignmentExpression(assignmentExpression);
if (assignmentExpression.Operator == AssignmentOperatorType.Add) {
var left = ctx.Resolve(assignmentExpression.Left) as MemberResolveResult;
if (left == null || left.Member.SymbolKind != SymbolKind.Event || !left.Member.IsStatic)
return;
if (assignmentExpression.Right is AnonymousMethodExpression || assignmentExpression.Right is LambdaExpression) {
AddIssue(new CodeIssue(assignmentExpression.OperatorToken,
ctx.TranslateString("Subscription to static events with an anonymous method may cause memory leaks.")));
}
var right = ctx.Resolve(assignmentExpression.Right) as MethodGroupResolveResult;
if (right == null || right.Methods.Count() != 1)
return;
HashSet<Tuple<IMember, AssignmentExpression>> hs;
if (!addedEvents.TryGetValue(left.Member, out hs))
addedEvents[left.Member] = hs = new HashSet<Tuple<IMember, AssignmentExpression>>();
hs.Add(Tuple.Create((IMember)right.Methods.First(), assignmentExpression));
} else if (assignmentExpression.Operator == AssignmentOperatorType.Subtract) {
var left = ctx.Resolve(assignmentExpression.Left) as MemberResolveResult;
if (left == null || left.Member.SymbolKind != SymbolKind.Event || !left.Member.IsStatic)
return;
var right = ctx.Resolve(assignmentExpression.Right) as MethodGroupResolveResult;
if (right == null || right.Methods.Count() != 1)
return;
HashSet<IMember> hs;
if (!removedEvents.TryGetValue(left.Member, out hs))
removedEvents[left.Member] = hs = new HashSet<IMember>();
hs.Add(right.Methods.First());
} else if (assignmentExpression.Operator == AssignmentOperatorType.Assign) {
var left = ctx.Resolve(assignmentExpression.Left) as MemberResolveResult;
if (left == null || left.Member.SymbolKind != SymbolKind.Event || !left.Member.IsStatic)
return;
assignedEvents.Add(left.Member);
}
}
}
}
}
| 39.594595 | 166 | 0.736519 | [
"MIT"
] | Jenkin0603/myvim | bundle/omnisharp-vim/server/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Custom/StaticEventSubscriptionIssue.cs | 5,863 | C# |
using Seed.Environment.Plugins.Features;
namespace Seed.Environment.Engine
{
public interface IFeatureEventHandler
{
void Installing(IFeatureInfo feature);
void Installed(IFeatureInfo feature);
void Enabling(IFeatureInfo feature);
void Enabled(IFeatureInfo feature);
void Disabling(IFeatureInfo feature);
void Disabled(IFeatureInfo feature);
void Uninstalling(IFeatureInfo feature);
void Uninstalled(IFeatureInfo feature);
}
}
| 21.291667 | 48 | 0.700587 | [
"MIT"
] | fyl080801/dotnet-seed | src/Seed.Environment.Abstractions/Engine/IFeatureEventHandler.cs | 511 | C# |
using System;
namespace Octopus.Client.Model
{
public class DashboardItemResource : Resource
{
public string ProjectId { get; set; }
public string EnvironmentId { get; set; }
public string ReleaseId { get; set; }
public string DeploymentId { get; set; }
public string TaskId { get; set; }
public string TenantId { get; set; }
public string ChannelId { get; set; }
public string ReleaseVersion { get; set; }
public DateTimeOffset Created { get; set; }
public DateTimeOffset QueueTime { get; set; }
public DateTimeOffset? StartTime { get; set; }
public DateTimeOffset? CompletedTime { get; set; }
public TaskState State { get; set; }
public bool HasPendingInterruptions { get; set; }
public bool HasWarningsOrErrors { get; set; }
public string ErrorMessage { get; set; }
public string Duration { get; set; }
public bool IsCurrent { get; set; }
public bool IsPrevious { get; set; }
public bool IsCompleted { get; set; }
}
} | 39.035714 | 58 | 0.620311 | [
"Apache-2.0"
] | terotgut/OctopusClients | source/Octopus.Client/Model/DashboardItemResource.cs | 1,093 | 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("M2engage")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("M2engage")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[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("fbb82c3e-ad73-4911-8546-0ff357a64365")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.405405 | 84 | 0.746387 | [
"BSD-3-Clause"
] | Project-Lunar/Project-Lunar-M2Engage-Library | M2engage/Properties/AssemblyInfo.cs | 1,387 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using System.Reflection;
public class GenericDataHandler : MonoBehaviour
{
object dataSource;
Dictionary<string, object> fields;
//for real time sources
public DataSource source = null;
string index = "";
void Start()
{
//fields = new Dictionary<string, object>();
}
public void setData(Dictionary<string,object> data)
{
fields = data;
}
public string getData(string field)
{
object retData =null;
retData = getDataObj(field);
if(retData != null)
{
return retData.ToString();
}
else
{
return "";
}
}
public int getDataAsInt(string field)
{
object retData = null;
retData = getDataObj(field);
if (retData != null)
{
return (int)retData;
}
else
{
return 0;
}
}
public object getDataObj(string field)
{
object outp = new object();
Dictionary<string, object> subFieldVars;
//Make more efficient
if (fields == null)
{
return null;
}
string[] splitFields = field.Split('.');
string fieldToSearch = splitFields[0];
if (splitFields.Length > 1)
{
string subField = splitFields[1];
field.Split('.');
object result = new object();
fields.TryGetValue(fieldToSearch, out result);
if (result != null)
{
subFieldVars = result.GetType().GetFields().ToDictionary(prop => prop.Name, prop => prop.GetValue(fields[fieldToSearch]));
return subFieldVars[subField];
}
else
{
return "None";
}
}
fields.TryGetValue(fieldToSearch, out outp);
return outp ?? "";
}
}
| 21.634409 | 138 | 0.522863 | [
"MIT"
] | ChrisAshtear/EUIDatasources | Runtime/Menu/GenericDataHandler.cs | 2,014 | C# |
namespace Xamarin.Forms.Platform.Android
{
public static class PlatformConfigurationExtensions
{
public static IPlatformElementConfiguration<PlatformConfiguration.Android, T> OnThisPlatform<T>(this T element)
where T : Element, IElementConfiguration<T>
{
return (element).On<PlatformConfiguration.Android>();
}
}
} | 30 | 114 | 0.784848 | [
"MIT"
] | 07101994/Xamarin.Forms | Xamarin.Forms.Platform.Android/PlatformConfigurationExtensions.cs | 330 | 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 DbContextModels.AdventureWorks
{
using System;
using System.Collections.Generic;
public partial class ShipMethod
{
public ShipMethod()
{
this.PurchaseOrderHeaders = new HashSet<PurchaseOrder>();
this.SalesOrderHeaders = new HashSet<SalesOrderHeader>();
}
public int ShipMethodID { get; set; }
public string Name { get; set; }
public decimal ShipBase { get; set; }
public decimal ShipRate { get; set; }
public System.Guid rowguid { get; set; }
public System.DateTime ModifiedDate { get; set; }
public virtual ICollection<PurchaseOrder> PurchaseOrderHeaders { get; set; }
public virtual ICollection<SalesOrderHeader> SalesOrderHeaders { get; set; }
}
}
| 36.147059 | 84 | 0.568755 | [
"Apache-2.0"
] | Daniel-Svensson/OpenRiaServices | src/OpenRiaServices.EntityFramework/Test/DbContextModel/AdventureWorks/ShipMethod.cs | 1,229 | C# |
namespace Frederikskaj2.Reservations.Shared
{
public enum UpdateUserResult
{
Success,
GeneralError,
UserWasDeleted
}
} | 17.222222 | 44 | 0.63871 | [
"MIT"
] | Frederikskaj2/Reservations | Shared/Models/UpdateUserResult.cs | 157 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Moq;
using NUnit.Framework;
using PHPAnalysis.Analysis;
using PHPAnalysis.Analysis.AST;
using PHPAnalysis.Analysis.CFG;
using PHPAnalysis.Analysis.CFG.Taint;
using PHPAnalysis.Analysis.CFG.Traversal;
using PHPAnalysis.Data;
using PHPAnalysis.Parsing;
using PHPAnalysis.Tests.TestUtils;
using PHPAnalysis.Utils.XmlHelpers;
namespace PHPAnalysis.Tests.Analysis.AST
{
[TestFixture]
public class IncludeResolvertTests : ConfigDependentTests
{
[TestCase(@"<?php include('./j.php');", new[] {@"j.php"}, true),
TestCase(@"<?php include('./j.php');", new[] { @"f.php" }, false),
TestCase(@"<?php require('./j.php');", new[] { @"j.php" }, true),
TestCase(@"<?php include_once('./j.php');", new[] { @"j.php" }, true),
TestCase(@"<?php require_once('./j.php');", new[] { @"j.php" }, true),
TestCase(@"<?php include(__FILE__ . '/j.php');", new[] { @"j.php" }, true),
TestCase(@"<?php include(__FILE__ . '/' . 'j.php');", new[] { @"j.php" }, true),
TestCase(@"<?php include(__FILE__ . $_GET['a']);", new[] { @"j.php" }, false),]
public void ResolveInclude(string phpCode, string[] existingFiles, bool shouldResolve)
{
var includeResolver = new IncludeResolver(existingFiles.Select(f => new File() {FullPath = f}).ToList());
var ast = PHPParseUtils.ParsePHPCode(phpCode, Config.PHPSettings.PHPParserPath);
ast.IterateAllNodes(node =>
{
if (node.Name == AstConstants.Node + ":" + AstConstants.Nodes.Expr_Include)
{
File file;
if (includeResolver.TryResolveInclude(node, out file))
{
Assert.IsTrue(shouldResolve);
}
else
{
Assert.IsFalse(shouldResolve);
}
}
return true;
});
}
}
}
| 37.280702 | 117 | 0.564706 | [
"MIT"
] | jtvn/Eir-CTLLTL | PHPAnalysis/PHPAnalysis.Tests/Analysis/AST/IncludeResolvertTests.cs | 2,127 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Core;
namespace Azure.ResourceManager.Sql
{
/// <summary> A Class representing a ServerJobAgentJobExecution along with the instance operations that can be performed on it. </summary>
public partial class ServerJobAgentJobExecution : ArmResource
{
/// <summary> Generate the resource identifier of a <see cref="ServerJobAgentJobExecution"/> instance. </summary>
public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string serverName, string jobAgentName, string jobName, string jobExecutionId)
{
var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/executions/{jobExecutionId}";
return new ResourceIdentifier(resourceId);
}
private readonly ClientDiagnostics _clientDiagnostics;
private readonly JobExecutionsRestOperations _jobExecutionsRestClient;
private readonly JobExecutionData _data;
/// <summary> Initializes a new instance of the <see cref="ServerJobAgentJobExecution"/> class for mocking. </summary>
protected ServerJobAgentJobExecution()
{
}
/// <summary> Initializes a new instance of the <see cref = "ServerJobAgentJobExecution"/> class. </summary>
/// <param name="options"> The client parameters to use in these operations. </param>
/// <param name="resource"> The resource that is the target of operations. </param>
internal ServerJobAgentJobExecution(ArmResource options, JobExecutionData resource) : base(options, resource.Id)
{
HasData = true;
_data = resource;
_clientDiagnostics = new ClientDiagnostics(ClientOptions);
_jobExecutionsRestClient = new JobExecutionsRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Initializes a new instance of the <see cref="ServerJobAgentJobExecution"/> class. </summary>
/// <param name="options"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal ServerJobAgentJobExecution(ArmResource options, ResourceIdentifier id) : base(options, id)
{
_clientDiagnostics = new ClientDiagnostics(ClientOptions);
_jobExecutionsRestClient = new JobExecutionsRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Initializes a new instance of the <see cref="ServerJobAgentJobExecution"/> class. </summary>
/// <param name="clientOptions"> The client options to build client context. </param>
/// <param name="credential"> The credential to build client context. </param>
/// <param name="uri"> The uri to build client context. </param>
/// <param name="pipeline"> The pipeline to build client context. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal ServerJobAgentJobExecution(ArmClientOptions clientOptions, TokenCredential credential, Uri uri, HttpPipeline pipeline, ResourceIdentifier id) : base(clientOptions, credential, uri, pipeline, id)
{
_clientDiagnostics = new ClientDiagnostics(ClientOptions);
_jobExecutionsRestClient = new JobExecutionsRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Gets the resource type for the operations. </summary>
public static readonly ResourceType ResourceType = "Microsoft.Sql/servers/jobAgents/jobs/executions";
/// <summary> Gets whether or not the current instance has data. </summary>
public virtual bool HasData { get; }
/// <summary> Gets the data representing this Feature. </summary>
/// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
public virtual JobExecutionData Data
{
get
{
if (!HasData)
throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
return _data;
}
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id));
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/executions/{jobExecutionId}
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/executions/{jobExecutionId}
/// OperationId: JobExecutions_Get
/// <summary> Gets a job execution. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async virtual Task<Response<ServerJobAgentJobExecution>> GetAsync(CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("ServerJobAgentJobExecution.Get");
scope.Start();
try
{
var response = await _jobExecutionsRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Parent.Name, Id.Parent.Parent.Name, Id.Parent.Name, Guid.Parse(Id.Name), cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false);
return Response.FromValue(new ServerJobAgentJobExecution(this, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/executions/{jobExecutionId}
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/executions/{jobExecutionId}
/// OperationId: JobExecutions_Get
/// <summary> Gets a job execution. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<ServerJobAgentJobExecution> Get(CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("ServerJobAgentJobExecution.Get");
scope.Start();
try
{
var response = _jobExecutionsRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Parent.Name, Id.Parent.Parent.Name, Id.Parent.Name, Guid.Parse(Id.Name), cancellationToken);
if (response.Value == null)
throw _clientDiagnostics.CreateRequestFailedException(response.GetRawResponse());
return Response.FromValue(new ServerJobAgentJobExecution(this, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Lists all available geo-locations. </summary>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> A collection of locations that may take multiple service requests to iterate over. </returns>
public async virtual Task<IEnumerable<AzureLocation>> GetAvailableLocationsAsync(CancellationToken cancellationToken = default)
{
return await ListAvailableLocationsAsync(ResourceType, cancellationToken).ConfigureAwait(false);
}
/// <summary> Lists all available geo-locations. </summary>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> A collection of locations that may take multiple service requests to iterate over. </returns>
public virtual IEnumerable<AzureLocation> GetAvailableLocations(CancellationToken cancellationToken = default)
{
return ListAvailableLocations(ResourceType, cancellationToken);
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/executions/{jobExecutionId}/cancel
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/executions/{jobExecutionId}
/// OperationId: JobExecutions_Cancel
/// <summary> Requests cancellation of a job execution. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async virtual Task<Response> CancelAsync(CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("ServerJobAgentJobExecution.Cancel");
scope.Start();
try
{
var response = await _jobExecutionsRestClient.CancelAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Parent.Name, Id.Parent.Parent.Name, Id.Parent.Name, Guid.Parse(Id.Name), cancellationToken).ConfigureAwait(false);
return response;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/executions/{jobExecutionId}/cancel
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/executions/{jobExecutionId}
/// OperationId: JobExecutions_Cancel
/// <summary> Requests cancellation of a job execution. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response Cancel(CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("ServerJobAgentJobExecution.Cancel");
scope.Start();
try
{
var response = _jobExecutionsRestClient.Cancel(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Parent.Name, Id.Parent.Parent.Name, Id.Parent.Name, Guid.Parse(Id.Name), cancellationToken);
return response;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
#region ServerJobAgentJobExecutionStep
/// <summary> Gets a collection of ServerJobAgentJobExecutionSteps in the ServerJobAgentJobExecution. </summary>
/// <returns> An object representing collection of ServerJobAgentJobExecutionSteps and their operations over a ServerJobAgentJobExecution. </returns>
public virtual ServerJobAgentJobExecutionStepCollection GetServerJobAgentJobExecutionSteps()
{
return new ServerJobAgentJobExecutionStepCollection(this);
}
#endregion
}
}
| 57.625571 | 246 | 0.688114 | [
"MIT"
] | LGDoor/azure-sdk-for-net | sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/ServerJobAgentJobExecution.cs | 12,620 | C# |
using System;
using System.Collections.Concurrent;
using StackExchange.Redis;
namespace Masuit.Tools.Core.NoSQL
{
/// <summary>
/// ConnectionMultiplexer对象管理帮助类
/// </summary>
public static class RedisConnectionManager
{
/// <summary>
/// Redis服务器连接字符串,默认为:127.0.0.1:6379,allowadmin=true<br/>
/// </summary>
public static string RedisConnectionString
{
get => "127.0.0.1:6379,allowadmin=true";
set { }
}
private static readonly ConcurrentDictionary<string, ConnectionMultiplexer> ConnectionCache = new ConcurrentDictionary<string, ConnectionMultiplexer>();
/// <summary>
/// 对象池获取线程内唯一对象
/// </summary>
public static ConnectionMultiplexer Instance
{
get
{
var multiplexer = ConnectionCache.GetOrAdd(RedisConnectionString, GetManager(RedisConnectionString));
return multiplexer;
}
}
/// <summary>
/// 缓存获取
/// </summary>
/// <param name="connectionString">连接字符串</param>
/// <returns>连接对象</returns>
public static ConnectionMultiplexer GetConnectionMultiplexer(string connectionString)
{
var multiplexer = ConnectionCache.GetOrAdd(connectionString, GetManager(RedisConnectionString));
return multiplexer;
}
private static ConnectionMultiplexer GetManager(string connectionString = null)
{
connectionString = connectionString ?? RedisConnectionString;
var connect = ConnectionMultiplexer.Connect(ConfigurationOptions.Parse(connectionString, true));
//注册如下事件
connect.ConnectionFailed += MuxerConnectionFailed;
connect.ConnectionRestored += MuxerConnectionRestored;
connect.ErrorMessage += MuxerErrorMessage;
connect.ConfigurationChanged += MuxerConfigurationChanged;
connect.HashSlotMoved += MuxerHashSlotMoved;
connect.InternalError += MuxerInternalError;
return connect;
}
#region 事件
/// <summary>
/// 配置更改时
/// </summary>
/// <param name="sender">触发者</param>
/// <param name="e">事件参数</param>
private static void MuxerConfigurationChanged(object sender, EndPointEventArgs e)
{
Console.WriteLine("Configuration changed: " + e.EndPoint);
}
/// <summary>
/// 发生错误时
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e)
{
Console.WriteLine("ErrorMessage: " + e.Message);
}
/// <summary>
/// 重新建立连接之前的错误
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e)
{
Console.WriteLine("ConnectionRestored: " + e.EndPoint);
}
/// <summary>
/// 连接失败 , 如果重新连接成功你将不会收到这个通知
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e)
{
Console.WriteLine("重新连接:Endpoint failed: " + e.EndPoint + ", " + e.FailureType + (e.Exception == null ? "" : (", " + e.Exception.Message)));
}
/// <summary>
/// 更改集群
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e)
{
Console.WriteLine("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint);
}
/// <summary>
/// redis类库错误
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerInternalError(object sender, InternalErrorEventArgs e)
{
Console.WriteLine("InternalError:Message" + e.Exception.Message);
}
#endregion 事件
}
} | 34.427419 | 160 | 0.582806 | [
"MIT"
] | U3DC/Masuit.Tools | Masuit.Tools.Core/NoSQL/RedisConnectionManager.cs | 4,509 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
using System.Text.Encodings.Web;
using System.Linq;
using System.Threading.Tasks;
using IVMSBack.Areas.Identity.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
namespace IVMSBack.Areas.Identity.Pages.Account.Manage
{
public partial class EmailModel : PageModel
{
private readonly UserManager<IVMSBackUser> _userManager;
private readonly SignInManager<IVMSBackUser> _signInManager;
private readonly IEmailSender _emailSender;
public EmailModel(
UserManager<IVMSBackUser> userManager,
SignInManager<IVMSBackUser> signInManager,
IEmailSender emailSender)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
}
public string Username { get; set; }
public string Email { get; set; }
public bool IsEmailConfirmed { get; set; }
[TempData]
public string StatusMessage { get; set; }
[BindProperty]
public InputModel Input { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
[Display(Name = "New email")]
public string NewEmail { get; set; }
}
private async Task LoadAsync(IVMSBackUser user)
{
var email = await _userManager.GetEmailAsync(user);
Email = email;
Input = new InputModel
{
NewEmail = email,
};
IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user);
}
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
await LoadAsync(user);
return Page();
}
public async Task<IActionResult> OnPostChangeEmailAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (!ModelState.IsValid)
{
await LoadAsync(user);
return Page();
}
var email = await _userManager.GetEmailAsync(user);
if (Input.NewEmail != email)
{
var userId = await _userManager.GetUserIdAsync(user);
var code = await _userManager.GenerateChangeEmailTokenAsync(user, Input.NewEmail);
var callbackUrl = Url.Page(
"/Account/ConfirmEmailChange",
pageHandler: null,
values: new { userId = userId, email = Input.NewEmail, code = code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(
Input.NewEmail,
"Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
StatusMessage = "Confirmation link to change email sent. Please check your email.";
return RedirectToPage();
}
StatusMessage = "Your email is unchanged.";
return RedirectToPage();
}
public async Task<IActionResult> OnPostSendVerificationEmailAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (!ModelState.IsValid)
{
await LoadAsync(user);
return Page();
}
var userId = await _userManager.GetUserIdAsync(user);
var email = await _userManager.GetEmailAsync(user);
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = userId, code = code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(
email,
"Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
StatusMessage = "Verification email sent. Please check your email.";
return RedirectToPage();
}
}
}
| 34.310811 | 126 | 0.574242 | [
"Unlicense"
] | saibothack/IVMSBack | IVMSBack/Areas/Identity/Pages/Account/Manage/Email.cshtml.cs | 5,080 | C# |
using System.Collections.Generic;
using Abp.AutoMapper;
using EIRA.MultiTenancy;
namespace EIRA.Web.Models.Account
{
public class TenantSelectionViewModel
{
public string Action { get; set; }
public List<TenantInfo> Tenants { get; set; }
[AutoMapFrom(typeof(Tenant))]
public class TenantInfo
{
public int Id { get; set; }
public string TenancyName { get; set; }
public string Name { get; set; }
}
}
} | 21.826087 | 53 | 0.599602 | [
"MIT"
] | gladiatormaximusty/Questionnaire-Backend | src/EIRA.Web/Models/Account/TenantSelectionViewModel.cs | 504 | C# |
// Copyright Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using HoloToolkit.Unity;
namespace GalaxyExplorer
{
public class SolarSystemResizer : SingleInstance<SolarSystemResizer>
{
void Awake()
{
transform.localScale = transform.localScale * MyAppPlatformManager.SolarSystemScaleFactor;
}
}
} | 28.933333 | 102 | 0.721198 | [
"MIT"
] | ActiveNick/GalaxyExplorer | Assets/SolarSystem/SolarSystemResizer.cs | 436 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
using Microsoft.EntityFrameworkCore.Query.Internal;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
namespace Microsoft.EntityFrameworkCore.Query;
/// <inheritdoc />
public class RelationalQueryTranslationPostprocessor : QueryTranslationPostprocessor
{
private readonly bool _useRelationalNulls;
/// <summary>
/// Creates a new instance of the <see cref="RelationalQueryTranslationPostprocessor" /> class.
/// </summary>
/// <param name="dependencies">Parameter object containing dependencies for this class.</param>
/// <param name="relationalDependencies">Parameter object containing relational dependencies for this class.</param>
/// <param name="queryCompilationContext">The query compilation context object to use.</param>
public RelationalQueryTranslationPostprocessor(
QueryTranslationPostprocessorDependencies dependencies,
RelationalQueryTranslationPostprocessorDependencies relationalDependencies,
QueryCompilationContext queryCompilationContext)
: base(dependencies, queryCompilationContext)
{
RelationalDependencies = relationalDependencies;
_useRelationalNulls = RelationalOptionsExtension.Extract(queryCompilationContext.ContextOptions).UseRelationalNulls;
}
/// <summary>
/// Relational provider-specific dependencies for this service.
/// </summary>
protected virtual RelationalQueryTranslationPostprocessorDependencies RelationalDependencies { get; }
/// <inheritdoc />
public override Expression Process(Expression query)
{
query = base.Process(query);
query = new SelectExpressionProjectionApplyingExpressionVisitor(
((RelationalQueryCompilationContext)QueryCompilationContext).QuerySplittingBehavior).Visit(query);
query = new SelectExpressionPruningExpressionVisitor().Visit(query);
#if DEBUG
// Verifies that all SelectExpression are marked as immutable after this point.
new SelectExpressionMutableVerifyingExpressionVisitor().Visit(query);
// Verifies that all table aliases are uniquely assigned without skipping over
// Which points to possible mutation of a SelectExpression being used in multiple places.
new TableAliasVerifyingExpressionVisitor().Visit(query);
#endif
query = new SqlExpressionSimplifyingExpressionVisitor(RelationalDependencies.SqlExpressionFactory, _useRelationalNulls)
.Visit(query);
query = new RelationalValueConverterCompensatingExpressionVisitor(RelationalDependencies.SqlExpressionFactory).Visit(query);
return query;
}
#if DEBUG
private sealed class SelectExpressionMutableVerifyingExpressionVisitor : ExpressionVisitor
{
[return: NotNullIfNotNull("expression")]
public override Expression? Visit(Expression? expression)
{
if (expression is SelectExpression selectExpression)
{
if (selectExpression.IsMutable())
{
throw new InvalidDataException(selectExpression.Print());
}
}
if (expression is ShapedQueryExpression shapedQueryExpression)
{
Visit(shapedQueryExpression.QueryExpression);
return shapedQueryExpression;
}
return base.Visit(expression);
}
}
private sealed class TableAliasVerifyingExpressionVisitor : ExpressionVisitor
{
private readonly ScopedVisitor _scopedVisitor = new();
// Validates that all aliases are unique inside SelectExpression
// And all aliases are used in without any generated alias being missing
[return: NotNullIfNotNull("expression")]
public override Expression? Visit(Expression? expression)
{
switch (expression)
{
case ShapedQueryExpression shapedQueryExpression:
UniquifyAliasInSelectExpression(shapedQueryExpression.QueryExpression);
Visit(shapedQueryExpression.QueryExpression);
return shapedQueryExpression;
case RelationalSplitCollectionShaperExpression relationalSplitCollectionShaperExpression:
UniquifyAliasInSelectExpression(relationalSplitCollectionShaperExpression.SelectExpression);
Visit(relationalSplitCollectionShaperExpression.InnerShaper);
return relationalSplitCollectionShaperExpression;
default:
return base.Visit(expression);
}
}
private void UniquifyAliasInSelectExpression(Expression selectExpression)
=> _scopedVisitor.EntryPoint(selectExpression);
private sealed class ScopedVisitor : ExpressionVisitor
{
private readonly HashSet<string> _usedAliases = new(StringComparer.OrdinalIgnoreCase);
private readonly HashSet<TableExpressionBase> _visitedTableExpressionBases = new(ReferenceEqualityComparer.Instance);
public Expression EntryPoint(Expression expression)
{
_usedAliases.Clear();
_visitedTableExpressionBases.Clear();
if (expression is SelectExpression selectExpression)
{
foreach (var alias in selectExpression.RemovedAliases())
{
_usedAliases.Add(alias);
}
}
var result = Visit(expression);
foreach (var group in _usedAliases.GroupBy(e => e[..1]))
{
if (group.Count() == 1)
{
continue;
}
var numbers = group.OrderBy(e => e).Skip(1).Select(e => int.Parse(e[1..])).OrderBy(e => e).ToList();
if (numbers.Count - 1 != numbers[^1])
{
throw new InvalidOperationException($"Missing alias in the list: {string.Join(",", group.Select(e => e))}");
}
}
return result;
}
[return: NotNullIfNotNull("expression")]
public override Expression? Visit(Expression? expression)
{
var visitedExpression = base.Visit(expression);
if (visitedExpression is TableExpressionBase tableExpressionBase
&& !_visitedTableExpressionBases.Contains(tableExpressionBase)
&& tableExpressionBase.Alias != null)
{
if (_usedAliases.Contains(tableExpressionBase.Alias))
{
throw new InvalidOperationException($"Duplicate alias: {tableExpressionBase.Alias}");
}
_usedAliases.Add(tableExpressionBase.Alias);
_visitedTableExpressionBases.Add(tableExpressionBase);
}
return visitedExpression;
}
}
}
#endif
}
| 41.896552 | 132 | 0.646365 | [
"MIT"
] | AraHaan/efcore | src/EFCore.Relational/Query/RelationalQueryTranslationPostprocessor.cs | 7,290 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Titration_Analyzer
{
public class unkownacid
{
private Dictionary<string, string> monoproticacid = new Dictionary<string, string>();
private Dictionary<string, string> diproticacidone = new Dictionary<string, string>();
private Dictionary<string, string> triproticacidone = new Dictionary<string, string>();
private bool AcidorBase;
public double percentmatch { get; set; }
public string acidorbasevalues;
public List<string> acidname = new List<string>();
public unkownacid(int H, bool acidorbase)
{
AcidorBase = acidorbase;
switch (H)
{
case 1:
if(acidorbase == false)
{
monoproticacid.Add("Iodic", "0.8");
monoproticacid.Add("Sulfuric (2)", "1.92");
monoproticacid.Add("Chlorous", "1.96");
monoproticacid.Add("2-Nitrobenzoic", "1.96");
monoproticacid.Add("Chloroacetic", "2.85");
monoproticacid.Add("Hydrofluoric", "3.14");
monoproticacid.Add("Nitrous", "3.39");
monoproticacid.Add("Ethanoic", "3.65");
monoproticacid.Add("Formic", "3.75");
monoproticacid.Add("Lactic", "3.86");
monoproticacid.Add("Barbituric", "4.01");
monoproticacid.Add("Benzoic", "4.19");
monoproticacid.Add("Hydrazoic", "4.72");
monoproticacid.Add("Acetic", "4.75");
monoproticacid.Add("Butanoic", "4.83");
monoproticacid.Add("Propionic", "4.87");
monoproticacid.Add("Pyridinium ion", "5.25");
monoproticacid.Add("Hydrosulfuric", "7");
monoproticacid.Add("Hypochlorous", "7.53");
monoproticacid.Add("Hypobromous", "8.7");
monoproticacid.Add("Hydrocyanic", "9.21");
monoproticacid.Add("Boric (1)", "9.23");
monoproticacid.Add("Phenol", "9.8");
monoproticacid.Add("Hypoiodous", "10.7");
monoproticacid.Add("Hydrogen peroxide", "11.62");
}
else if(acidorbase == true)
{
monoproticacid.Add("Oxazole", "0.8");
monoproticacid.Add("Aniline", "4.6");
monoproticacid.Add("Acetate", "4.75");
monoproticacid.Add("Pyridine", "5.23");
monoproticacid.Add("Imidazole", "6.8");
monoproticacid.Add("Morphonline", "8.36");
monoproticacid.Add("Ammonium ion", "9.25");
monoproticacid.Add("Uracil", "9.45");
monoproticacid.Add("Succinimide", "9.62");
monoproticacid.Add("Isopropylamine", "10.63");
monoproticacid.Add("Triethylamine", "10.8");
monoproticacid.Add("Piperidine", "11");
monoproticacid.Add("Azetidine", "11.29");
monoproticacid.Add("Pyrrolidine", "11.31");
}
break;
case 2:
if(acidorbase == false)
{
diproticacidone.Add("Oxalic", "1.23,4.19");
diproticacidone.Add("Sulfurous", "1.81,6.91");
diproticacidone.Add("Maleic", "1.89,6.23");
diproticacidone.Add("Proline", "1.95,10.46");
diproticacidone.Add("Threonine", "2.09,9.10");
diproticacidone.Add("Methionine", "2.13,9.28");
diproticacidone.Add("Asparagine", "2.14,8.72");
diproticacidone.Add("Glutamine", "2.17,9.13");
diproticacidone.Add("Serine", "2.19,9.21");
diproticacidone.Add("Phenylalanine", "2.20,9.31");
diproticacidone.Add("Valine", "2.29,9.74");
diproticacidone.Add("Isoluecine", "2.32,9.76");
diproticacidone.Add("Leucine", "2.33,9.74");
diproticacidone.Add("Glycine", "2.35,9.78");
diproticacidone.Add("Alanine", "2.35,9.87");
diproticacidone.Add("Tryptophan", "2.46,9.41");
diproticacidone.Add("Malonic", "2.85,5.7");
diproticacidone.Add("o-Phthalic", "2.95,5.41");
diproticacidone.Add("Tartric", "3.04,4.37");
diproticacidone.Add("Fumaric", "3.05,4.49");
diproticacidone.Add("Methylmalonic", "3.07, 5.76");
diproticacidone.Add("Isopthalic", "3.07, 4.60");
diproticacidone.Add("Lysergic", "3.44, 7.68");
diproticacidone.Add("Malic", "3.46,5.1");
diproticacidone.Add("Teraphthalic", "3.46,5.1");
diproticacidone.Add("Ascorbic", "4.1,11.8");
diproticacidone.Add("Succinic", "4.21,5.64");
diproticacidone.Add("Carbonic", "6.37,10.32");
diproticacidone.Add("P-Hydroquinone", "9.85,11.4");
}
else if(acidorbase == true)
{
diproticacidone.Add("Creatine", "9.2,4.8");
diproticacidone.Add("1,2,3-Triaminopropane", "9.59,7.95");
diproticacidone.Add("1,3-Diamino-2-propanol", "9.69,7.93");
diproticacidone.Add("Piperazine", "9.73,5.53");
diproticacidone.Add("1,2-Ethanediamine", "9.92,6.68");
diproticacidone.Add("1,3-Propanediamine", "10.55,8.88");
diproticacidone.Add("1,4-Butanediamine", "10.80,9.63");
}
break;
case 3:
if(acidorbase == false)
{
triproticacidone.Add("Histidine", "1.80,6.04,9.33");
triproticacidone.Add("Argenine", "1.82,8.99,12.48");
triproticacidone.Add("Cysteine", "1.92,8.37,10.70");
triproticacidone.Add("Aspartic", "1.99,3.90,9.90");
triproticacidone.Add("Glutamic", "2.1,4.07,9.47");
triproticacidone.Add("Phosphoric", "2.12,7.21,12.32/12.66");
triproticacidone.Add("Lysine", "2.16,9.06,10.54");
triproticacidone.Add("Tyrosine", "2.20,9.21,10.46");
triproticacidone.Add("Arsenic", "2.3,7.1,9.22/11.53");
triproticacidone.Add("Oxaloacetic", "2.55,4.37,13.03");
triproticacidone.Add("Citric", "3.08,4.74,5.4");
triproticacidone.Add("Nitrilotriacetic", "3.08,4.74,5.4");
triproticacidone.Add("Cyanuric", "6.88,11.4,13.5");
}
else if (acidorbase == true)
{
triproticacidone.Add("Phosphate Ion", "12.32,7.21,2.12");
triproticacidone.Add("Citrate Ion", "5.4,4.74,3.08");
}
break;
default:
break;
}
}
public List<string> acidlist(int protinationstate)
{
switch (protinationstate)
{
case 1:
foreach (var acid in monoproticacid)
{
acidname.Add(acid.Key);
}
break;
case 2:
foreach (var acid in diproticacidone)
{
acidname.Add(acid.Key);
}
break;
case 3:
foreach (var acid in triproticacidone)
{
acidname.Add(acid.Key);
}
break;
default:
break;
}
return acidname;
}
public string knowngetpKa(int hplus, string acid)
{
var pkareturnvalues = "";
switch (hplus)
{
case 1:
pkareturnvalues = monoproticacid[acid];
break;
case 2:
pkareturnvalues = diproticacidone[acid];
break;
case 3:
pkareturnvalues = triproticacidone[acid];
if(pkareturnvalues.Contains("/") == true)
{
var acidseperated = pkareturnvalues.Split(',');
var seperatedslash = acidseperated[2].Split('/');
pkareturnvalues = acidseperated[0] + ',' + acidseperated[1] + ',' + seperatedslash[0];
}
break;
default:
break;
}
return pkareturnvalues;
}
public double GetpKa(double pkb)
{
return 14 - pkb;
}
public string DetermineUnkown(string acidPKa, int acidtype)
{
double closestmatchdifference = 14;
string closestmatch = "";
double firstdifference = 0;
double seconddifference = 0;
double firstequiv = 0;
double secondequiv = 0;
double thirddifference = 0;
double thirdequiv = 0;
var splitunkownstring = acidPKa.Split(',').ToList();
splitunkownstring.Remove("");
splitunkownstring.Sort();
switch (acidtype)
{
case 1:
foreach (KeyValuePair<string, string> acidentry in monoproticacid)
{
double acidvalue = 0;
acidvalue = Convert.ToDouble(acidentry.Value);
if (Math.Abs(acidvalue - Convert.ToDouble(splitunkownstring[0])) < closestmatchdifference)
{
closestmatchdifference = Math.Abs(acidvalue - Convert.ToDouble(splitunkownstring[0]));
closestmatch = acidentry.Key;
acidorbasevalues = acidentry.Value;
}
}
percentmatch = Math.Round(((closestmatchdifference) / Convert.ToDouble(splitunkownstring[0])) * 100, 1);
break;
case 2:
foreach (KeyValuePair<string, string> acidentry in diproticacidone)
{
var acidentries = acidentry.Value.Split(',');
Array.Sort(acidentries);
double firstacidpka = 0;
double secondacidpka = 0;
firstacidpka = Convert.ToDouble(acidentries[0]);
secondacidpka = Convert.ToDouble(acidentries[1]);
var firstunkownpka = Convert.ToDouble(splitunkownstring[0]);
var secondunkownpka = Convert.ToDouble(splitunkownstring[1]);
if (Math.Abs(firstacidpka - firstunkownpka) + Math.Abs(secondacidpka - secondunkownpka)< closestmatchdifference)
{
closestmatchdifference = Math.Abs(firstacidpka - firstunkownpka) + Math.Abs(secondacidpka - secondunkownpka);
closestmatch = acidentry.Key;
acidorbasevalues = acidentry.Value;
firstdifference = Math.Abs(firstacidpka - firstunkownpka);
seconddifference = Math.Abs(secondacidpka - secondunkownpka);
firstequiv = firstacidpka;
secondequiv = secondacidpka;
}
}
percentmatch = Math.Round((((firstdifference/firstequiv) + ((seconddifference / secondequiv)))/2)*100, 1);
break;
case 3:
foreach (KeyValuePair<string, string> acidentry in triproticacidone)
{
var acidentries = acidentry.Value.Split(',');
double firstacidpka = 0;
double secondacidpka = 0;
firstacidpka = Convert.ToDouble(acidentries[0]);
secondacidpka = Convert.ToDouble(acidentries[1]);
var thirdacidpka = new List<string>();
if (acidentries[2].Contains('/'))
{
thirdacidpka = acidentries[2].Split('/').ToList();
}
else
{
thirdacidpka.Add(acidentries[2]);
}
var firstunkownpka = Convert.ToDouble(splitunkownstring[0]);
var secondunkownpka = Convert.ToDouble(splitunkownstring[1]);
var thirdunkownpka = Convert.ToDouble(splitunkownstring[2]);
foreach (string acid in thirdacidpka)
{
double acidorbaseentry = 0;
acidorbaseentry = Convert.ToDouble(acid);
if (Math.Abs(firstacidpka - firstunkownpka) + Math.Abs(secondacidpka - secondunkownpka) + Math.Abs(acidorbaseentry - thirdunkownpka) < closestmatchdifference)
{
closestmatchdifference = Math.Abs(firstacidpka - firstunkownpka) + Math.Abs(secondacidpka - secondunkownpka);
closestmatch = acidentry.Key;
acidorbasevalues = acidentry.Value;
firstdifference = Math.Abs(firstacidpka - firstunkownpka);
seconddifference = Math.Abs(secondacidpka - secondunkownpka);
thirddifference = Math.Abs(acidorbaseentry - thirdunkownpka);
firstequiv = firstacidpka;
secondequiv = secondacidpka;
thirdequiv = acidorbaseentry;
}
}
}
percentmatch = Math.Round((((firstdifference / firstequiv) + (seconddifference / secondequiv) + (thirddifference / thirdequiv)) / 3) * 100, 1);
break;
default:
break;
}
return closestmatch;
}
}
}
| 45.793605 | 186 | 0.442075 | [
"CC0-1.0"
] | dalevens/OpenTitration | src/TitrationAnalyzer/unkownacid.cs | 15,755 | C# |
namespace VegaLite.Schema
{
/// <summary>
/// The layout direction for legend orient group layout.
/// </summary>
public struct Direction
{
public Orientation? Enum;
public SignalRef SignalRef;
public static implicit operator Direction(Orientation @enum)
{
return new Direction
{
Enum = @enum
};
}
public static implicit operator Direction(SignalRef signalRef)
{
return new Direction
{
SignalRef = signalRef
};
}
}
}
| 21.964286 | 70 | 0.513821 | [
"MIT"
] | trmcnealy/VegaLite.NET | VegaLite.NET/Schema/Direction.cs | 617 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Core;
namespace Azure.ResourceManager.Sql
{
/// <summary> A Class representing a ServerDatabaseAdvisor along with the instance operations that can be performed on it. </summary>
public partial class ServerDatabaseAdvisor : ArmResource
{
/// <summary> Generate the resource identifier of a <see cref="ServerDatabaseAdvisor"/> instance. </summary>
public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string serverName, string databaseName, string advisorName)
{
var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/advisors/{advisorName}";
return new ResourceIdentifier(resourceId);
}
private readonly ClientDiagnostics _serverDatabaseAdvisorDatabaseAdvisorsClientDiagnostics;
private readonly DatabaseAdvisorsRestOperations _serverDatabaseAdvisorDatabaseAdvisorsRestClient;
private readonly AdvisorData _data;
/// <summary> Initializes a new instance of the <see cref="ServerDatabaseAdvisor"/> class for mocking. </summary>
protected ServerDatabaseAdvisor()
{
}
/// <summary> Initializes a new instance of the <see cref = "ServerDatabaseAdvisor"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="data"> The resource that is the target of operations. </param>
internal ServerDatabaseAdvisor(ArmClient client, AdvisorData data) : this(client, data.Id)
{
HasData = true;
_data = data;
}
/// <summary> Initializes a new instance of the <see cref="ServerDatabaseAdvisor"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal ServerDatabaseAdvisor(ArmClient client, ResourceIdentifier id) : base(client, id)
{
_serverDatabaseAdvisorDatabaseAdvisorsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Sql", ResourceType.Namespace, DiagnosticOptions);
Client.TryGetApiVersion(ResourceType, out string serverDatabaseAdvisorDatabaseAdvisorsApiVersion);
_serverDatabaseAdvisorDatabaseAdvisorsRestClient = new DatabaseAdvisorsRestOperations(_serverDatabaseAdvisorDatabaseAdvisorsClientDiagnostics, Pipeline, DiagnosticOptions.ApplicationId, BaseUri, serverDatabaseAdvisorDatabaseAdvisorsApiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Gets the resource type for the operations. </summary>
public static readonly ResourceType ResourceType = "Microsoft.Sql/servers/databases/advisors";
/// <summary> Gets whether or not the current instance has data. </summary>
public virtual bool HasData { get; }
/// <summary> Gets the data representing this Feature. </summary>
/// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
public virtual AdvisorData Data
{
get
{
if (!HasData)
throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
return _data;
}
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id));
}
/// <summary> Gets a collection of RecommendedActions in the RecommendedAction. </summary>
/// <returns> An object representing collection of RecommendedActions and their operations over a RecommendedAction. </returns>
public virtual RecommendedActionCollection GetRecommendedActions()
{
return new RecommendedActionCollection(Client, Id);
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/advisors/{advisorName}
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/advisors/{advisorName}
/// OperationId: DatabaseAdvisors_Get
/// <summary> Gets a database advisor. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async virtual Task<Response<ServerDatabaseAdvisor>> GetAsync(CancellationToken cancellationToken = default)
{
using var scope = _serverDatabaseAdvisorDatabaseAdvisorsClientDiagnostics.CreateScope("ServerDatabaseAdvisor.Get");
scope.Start();
try
{
var response = await _serverDatabaseAdvisorDatabaseAdvisorsRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw await _serverDatabaseAdvisorDatabaseAdvisorsClientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false);
return Response.FromValue(new ServerDatabaseAdvisor(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/advisors/{advisorName}
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/advisors/{advisorName}
/// OperationId: DatabaseAdvisors_Get
/// <summary> Gets a database advisor. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<ServerDatabaseAdvisor> Get(CancellationToken cancellationToken = default)
{
using var scope = _serverDatabaseAdvisorDatabaseAdvisorsClientDiagnostics.CreateScope("ServerDatabaseAdvisor.Get");
scope.Start();
try
{
var response = _serverDatabaseAdvisorDatabaseAdvisorsRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, cancellationToken);
if (response.Value == null)
throw _serverDatabaseAdvisorDatabaseAdvisorsClientDiagnostics.CreateRequestFailedException(response.GetRawResponse());
return Response.FromValue(new ServerDatabaseAdvisor(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/advisors/{advisorName}
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/advisors/{advisorName}
/// OperationId: DatabaseAdvisors_Update
/// <summary> Updates a database advisor. </summary>
/// <param name="parameters"> The requested advisor resource state. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="parameters"/> is null. </exception>
public async virtual Task<Response<ServerDatabaseAdvisor>> UpdateAsync(AdvisorData parameters, CancellationToken cancellationToken = default)
{
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var scope = _serverDatabaseAdvisorDatabaseAdvisorsClientDiagnostics.CreateScope("ServerDatabaseAdvisor.Update");
scope.Start();
try
{
var response = await _serverDatabaseAdvisorDatabaseAdvisorsRestClient.UpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, parameters, cancellationToken).ConfigureAwait(false);
return Response.FromValue(new ServerDatabaseAdvisor(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// RequestPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/advisors/{advisorName}
/// ContextualPath: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/advisors/{advisorName}
/// OperationId: DatabaseAdvisors_Update
/// <summary> Updates a database advisor. </summary>
/// <param name="parameters"> The requested advisor resource state. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="parameters"/> is null. </exception>
public virtual Response<ServerDatabaseAdvisor> Update(AdvisorData parameters, CancellationToken cancellationToken = default)
{
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var scope = _serverDatabaseAdvisorDatabaseAdvisorsClientDiagnostics.CreateScope("ServerDatabaseAdvisor.Update");
scope.Start();
try
{
var response = _serverDatabaseAdvisorDatabaseAdvisorsRestClient.Update(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, parameters, cancellationToken);
return Response.FromValue(new ServerDatabaseAdvisor(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
| 56.964103 | 256 | 0.688153 | [
"MIT"
] | danielortega-msft/azure-sdk-for-net | sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/ServerDatabaseAdvisor.cs | 11,108 | 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 DrawShip.Preview.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 39.666667 | 151 | 0.582633 | [
"Apache-2.0"
] | laingsimon/draw-ship | DrawShip.Preview/Properties/Settings.Designer.cs | 1,073 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Reflection;
using System;
using AnyThinkAds.Common;
using AnyThinkAds.ThirdParty.LitJson;
namespace AnyThinkAds.Api
{
public class ATBannerAdLoadingExtra
{
public static readonly string kATBannerAdLoadingExtraBannerAdSize = "banner_ad_size";
public static readonly string kATBannerAdLoadingExtraBannerAdSizeStruct = "banner_ad_size_struct";
public static readonly string kATBannerAdSizeUsesPixelFlagKey = "uses_pixel";
public static readonly string kATBannerAdShowingPisitionTop = "top";
public static readonly string kATBannerAdShowingPisitionBottom = "bottom";
//Deprecated in v5.7.3
public static readonly string kATBannerAdLoadingExtraInlineAdaptiveWidth = "inline_adaptive_width";
public static readonly string kATBannerAdLoadingExtraInlineAdaptiveOrientation = "inline_adaptive_orientation";
public static readonly int kATBannerAdLoadingExtraInlineAdaptiveOrientationCurrent = 0;
public static readonly int kATBannerAdLoadingExtraInlineAdaptiveOrientationPortrait = 1;
public static readonly int kATBannerAdLoadingExtraInlineAdaptiveOrientationLandscape = 2;
//Deprecated in v5.7.3
public static readonly string kATBannerAdLoadingExtraAdaptiveWidth = "adaptive_width";
public static readonly string kATBannerAdLoadingExtraAdaptiveOrientation = "adaptive_orientation";
public static readonly int kATBannerAdLoadingExtraAdaptiveOrientationCurrent = 0;
public static readonly int kATBannerAdLoadingExtraAdaptiveOrientationPortrait = 1;
public static readonly int kATBannerAdLoadingExtraAdaptiveOrientationLandscape = 2;
}
public class ATBannerAd
{
private static readonly ATBannerAd instance = new ATBannerAd();
private IATBannerAdClient client;
private ATBannerAd()
{
client = GetATBannerAdClient();
}
public static ATBannerAd Instance
{
get
{
return instance;
}
}
/**
API
*/
public void loadBannerAd(string placementId, Dictionary<string,object> pairs)
{
if (pairs != null && pairs.ContainsKey(ATBannerAdLoadingExtra.kATBannerAdLoadingExtraBannerAdSize))
{
client.loadBannerAd(placementId, JsonMapper.ToJson(pairs));
}
else if (pairs != null && pairs.ContainsKey(ATBannerAdLoadingExtra.kATBannerAdLoadingExtraBannerAdSizeStruct))
{
ATSize size = (ATSize)(pairs[ATBannerAdLoadingExtra.kATBannerAdLoadingExtraBannerAdSizeStruct]);
pairs.Add(ATBannerAdLoadingExtra.kATBannerAdLoadingExtraBannerAdSize, size.width + "x" + size.height);
pairs.Add(ATBannerAdLoadingExtra.kATBannerAdSizeUsesPixelFlagKey, size.usesPixel);
//Dictionary<string, object> newPaires = new Dictionary<string, object> { { ATBannerAdLoadingExtra.kATBannerAdLoadingExtraBannerAdSize, size.width + "x" + size.height }, { ATBannerAdLoadingExtra.kATBannerAdSizeUsesPixelFlagKey, size.usesPixel } };
client.loadBannerAd(placementId, JsonMapper.ToJson(pairs));
}
else
{
client.loadBannerAd(placementId, JsonMapper.ToJson(pairs));
}
}
public string checkAdStatus(string placementId)
{
return client.checkAdStatus(placementId);
}
public string getValidAdCaches(string placementId)
{
return client.getValidAdCaches(placementId);
}
public void setListener(ATBannerAdListener listener)
{
client.setListener(listener);
}
public void showBannerAd(string placementId, ATRect rect)
{
client.showBannerAd(placementId, rect, "");
}
public void showBannerAd(string placementId, ATRect rect, Dictionary<string,string> pairs)
{
client.showBannerAd(placementId, rect, JsonMapper.ToJson(pairs));
}
public void showBannerAd(string placementId, string position)
{
client.showBannerAd(placementId, position, "");
}
public void showBannerAd(string placementId, string position, Dictionary<string,string> pairs)
{
client.showBannerAd(placementId, position, JsonMapper.ToJson(pairs));
}
public void showBannerAd(string placementId)
{
client.showBannerAd(placementId);
}
public void hideBannerAd(string placementId)
{
client.hideBannerAd(placementId);
}
public void cleanBannerAd(string placementId)
{
client.cleanBannerAd(placementId);
}
public IATBannerAdClient GetATBannerAdClient()
{
return AnyThinkAds.ATAdsClientFactory.BuildBannerAdClient();
}
}
}
| 36.644444 | 263 | 0.69153 | [
"Apache-2.0"
] | anythinkteam/demo_unity | AnyThinkUnitySDK/Assets/AnyThinkAds/Api/ATBannerAd.cs | 4,949 | C# |
// *
// * Copyright (C) 2008 Roger Alsing : http://www.RogerAlsing.com
// *
// * This library is free software; you can redistribute it and/or modify it
// * under the terms of the GNU Lesser General Public License 2.1 or later, as
// * published by the Free Software Foundation. See the included license.txt
// * or http://www.gnu.org/copyleft/lesser.html for details.
// *
// *
namespace Alsing.SourceCode
{
/// <summary>
/// PatternScanResult struct is redurned by the Pattern class when an .IndexIn call has been performed.
/// </summary>
public struct PatternScanResult
{
/// <summary>
/// The index on which the pattern was found in the source string
/// </summary>
public int Index;
/// <summary>
/// The string that was found , this is always the same as the pattern StringPattern property if the pattern is a simple pattern.
/// if the pattern is complex this field will contain the string that was found by the scan.
/// </summary>
public string Token;
}
} | 36.724138 | 137 | 0.65446 | [
"MIT"
] | TrevorDArcyEvans/EllieWare | code/SyntaxBox/Alsing.SyntaxBox/Document/SyntaxDefinition/Pattern/PatternScanResult.cs | 1,067 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using ImageRichWebSite.Models;
namespace ImageRichWebSite.Controllers
{
[Authorize]
public class ManageController : Controller
{
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
public ManageController()
{
}
public ManageController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
{
UserManager = userManager;
SignInManager = signInManager;
}
public ApplicationSignInManager SignInManager
{
get
{
return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set
{
_signInManager = value;
}
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
//
// GET: /Manage/Index
public async Task<ActionResult> Index(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error ? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: "";
var userId = User.Identity.GetUserId();
var model = new IndexViewModel
{
HasPassword = HasPassword(),
PhoneNumber = await UserManager.GetPhoneNumberAsync(userId),
TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId),
Logins = await UserManager.GetLoginsAsync(userId),
BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId)
};
return View(model);
}
//
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> RemoveLogin(string loginProvider, string providerKey)
{
ManageMessageId? message;
var result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey));
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
message = ManageMessageId.RemoveLoginSuccess;
}
else
{
message = ManageMessageId.Error;
}
return RedirectToAction("ManageLogins", new { Message = message });
}
//
// GET: /Manage/AddPhoneNumber
public ActionResult AddPhoneNumber()
{
return View();
}
//
// POST: /Manage/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), model.Number);
if (UserManager.SmsService != null)
{
var message = new IdentityMessage
{
Destination = model.Number,
Body = "Your security code is: " + code
};
await UserManager.SmsService.SendAsync(message);
}
return RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.Number });
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> EnableTwoFactorAuthentication()
{
await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), true);
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", "Manage");
}
//
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DisableTwoFactorAuthentication()
{
await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), false);
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", "Manage");
}
//
// GET: /Manage/VerifyPhoneNumber
public async Task<ActionResult> VerifyPhoneNumber(string phoneNumber)
{
var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), phoneNumber);
// Send an SMS through the SMS provider to verify the phone number
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
//
// POST: /Manage/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var result = await UserManager.ChangePhoneNumberAsync(User.Identity.GetUserId(), model.PhoneNumber, model.Code);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.AddPhoneSuccess });
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "Failed to verify phone");
return View(model);
}
//
// GET: /Manage/RemovePhoneNumber
public async Task<ActionResult> RemovePhoneNumber()
{
var result = await UserManager.SetPhoneNumberAsync(User.Identity.GetUserId(), null);
if (!result.Succeeded)
{
return RedirectToAction("Index", new { Message = ManageMessageId.Error });
}
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.RemovePhoneSuccess });
}
//
// GET: /Manage/ChangePassword
public ActionResult ChangePassword()
{
return View();
}
//
// POST: /Manage/ChangePassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}
//
// GET: /Manage/SetPassword
public ActionResult SetPassword()
{
return View();
}
//
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SetPassword(SetPasswordViewModel model)
{
if (ModelState.IsValid)
{
var result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Manage/ManageLogins
public async Task<ActionResult> ManageLogins(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user == null)
{
return View("Error");
}
var userLogins = await UserManager.GetLoginsAsync(User.Identity.GetUserId());
var otherLogins = AuthenticationManager.GetExternalAuthenticationTypes().Where(auth => userLogins.All(ul => auth.AuthenticationType != ul.LoginProvider)).ToList();
ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
return new AccountController.ChallengeResult(provider, Url.Action("LinkLoginCallback", "Manage"), User.Identity.GetUserId());
}
//
// GET: /Manage/LinkLoginCallback
public async Task<ActionResult> LinkLoginCallback()
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId());
if (loginInfo == null)
{
return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
}
var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login);
return result.Succeeded ? RedirectToAction("ManageLogins") : RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
}
protected override void Dispose(bool disposing)
{
if (disposing && _userManager != null)
{
_userManager.Dispose();
_userManager = null;
}
base.Dispose(disposing);
}
#region Helpers
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
private bool HasPassword()
{
var user = UserManager.FindById(User.Identity.GetUserId());
if (user != null)
{
return user.PasswordHash != null;
}
return false;
}
private bool HasPhoneNumber()
{
var user = UserManager.FindById(User.Identity.GetUserId());
if (user != null)
{
return user.PhoneNumber != null;
}
return false;
}
public enum ManageMessageId
{
AddPhoneSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
#endregion
}
} | 36.374677 | 175 | 0.567024 | [
"Apache-2.0"
] | kappy/ImageRichWebApplication | ImageRichWebApplication/Controllers/ManageController.cs | 14,079 | C# |
using System;
using System.Security.Cryptography;
namespace SSH.Encryption
{
class TripleDES_CTR : CipherCTR
{
public override int BlockSize { get { return 8; } }
public override int KeySize { get { return 24; } }
internal override Type CryptoType { get { return typeof(TripleDESCryptoServiceProvider); } }
}
}
| 27.769231 | 101 | 0.65651 | [
"MIT"
] | neoscrib/secureshell | SSH/Encryption/TripleDES_CTR.cs | 363 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.GoogleNative.Compute.V1.Outputs
{
/// <summary>
/// An instance-attached disk resource.
/// </summary>
[OutputType]
public sealed class AttachedDiskResponse
{
/// <summary>
/// Specifies whether the disk will be auto-deleted when the instance is deleted (but not when the disk is detached from the instance).
/// </summary>
public readonly bool AutoDelete;
/// <summary>
/// Indicates that this is a boot disk. The virtual machine will use the first partition of the disk for its root filesystem.
/// </summary>
public readonly bool Boot;
/// <summary>
/// Specifies a unique device name of your choice that is reflected into the /dev/disk/by-id/google-* tree of a Linux operating system running within the instance. This name can be used to reference the device for mounting, resizing, and so on, from within the instance. If not specified, the server chooses a default device name to apply to this disk, in the form persistent-disk-x, where x is a number assigned by Google Compute Engine. This field is only applicable for persistent disks.
/// </summary>
public readonly string DeviceName;
/// <summary>
/// Encrypts or decrypts a disk using a customer-supplied encryption key. If you are creating a new disk, this field encrypts the new disk using an encryption key that you provide. If you are attaching an existing disk that is already encrypted, this field decrypts the disk using the customer-supplied encryption key. If you encrypt a disk using a customer-supplied key, you must provide the same key again when you attempt to use this resource at a later time. For example, you must provide the key when you create a snapshot or an image from the disk or when you attach the disk to a virtual machine instance. If you do not provide an encryption key, then the disk will be encrypted using an automatically generated key and you do not need to provide a key to use the disk later. Instance templates do not store customer-supplied encryption keys, so you cannot use your own keys to encrypt disks in a managed instance group.
/// </summary>
public readonly Outputs.CustomerEncryptionKeyResponse DiskEncryptionKey;
/// <summary>
/// The size of the disk in GB.
/// </summary>
public readonly string DiskSizeGb;
/// <summary>
/// A list of features to enable on the guest operating system. Applicable only for bootable images. Read Enabling guest operating system features to see a list of available options.
/// </summary>
public readonly ImmutableArray<Outputs.GuestOsFeatureResponse> GuestOsFeatures;
/// <summary>
/// A zero-based index to this disk, where 0 is reserved for the boot disk. If you have many disks attached to an instance, each disk would have a unique index number.
/// </summary>
public readonly int Index;
/// <summary>
/// [Input Only] Specifies the parameters for a new disk that will be created alongside the new instance. Use initialization parameters to create boot disks or local SSDs attached to the new instance. This property is mutually exclusive with the source property; you can only define one or the other, but not both.
/// </summary>
public readonly Outputs.AttachedDiskInitializeParamsResponse InitializeParams;
/// <summary>
/// Specifies the disk interface to use for attaching this disk, which is either SCSI or NVME. The default is SCSI. Persistent disks must always use SCSI and the request will fail if you attempt to attach a persistent disk in any other format than SCSI. Local SSDs can use either NVME or SCSI. For performance characteristics of SCSI over NVMe, see Local SSD performance.
/// </summary>
public readonly string Interface;
/// <summary>
/// Type of the resource. Always compute#attachedDisk for attached disks.
/// </summary>
public readonly string Kind;
/// <summary>
/// Any valid publicly visible licenses.
/// </summary>
public readonly ImmutableArray<string> Licenses;
/// <summary>
/// The mode in which to attach this disk, either READ_WRITE or READ_ONLY. If not specified, the default is to attach the disk in READ_WRITE mode.
/// </summary>
public readonly string Mode;
/// <summary>
/// shielded vm initial state stored on disk
/// </summary>
public readonly Outputs.InitialStateConfigResponse ShieldedInstanceInitialState;
/// <summary>
/// Specifies a valid partial or full URL to an existing Persistent Disk resource. When creating a new instance, one of initializeParams.sourceImage or initializeParams.sourceSnapshot or disks.source is required except for local SSD. If desired, you can also attach existing non-root persistent disks using this property. This field is only applicable for persistent disks. Note that for InstanceTemplate, specify the disk name for zonal disk, and the URL for regional disk.
/// </summary>
public readonly string Source;
/// <summary>
/// Specifies the type of the disk, either SCRATCH or PERSISTENT. If not specified, the default is PERSISTENT.
/// </summary>
public readonly string Type;
[OutputConstructor]
private AttachedDiskResponse(
bool autoDelete,
bool boot,
string deviceName,
Outputs.CustomerEncryptionKeyResponse diskEncryptionKey,
string diskSizeGb,
ImmutableArray<Outputs.GuestOsFeatureResponse> guestOsFeatures,
int index,
Outputs.AttachedDiskInitializeParamsResponse initializeParams,
string @interface,
string kind,
ImmutableArray<string> licenses,
string mode,
Outputs.InitialStateConfigResponse shieldedInstanceInitialState,
string source,
string type)
{
AutoDelete = autoDelete;
Boot = boot;
DeviceName = deviceName;
DiskEncryptionKey = diskEncryptionKey;
DiskSizeGb = diskSizeGb;
GuestOsFeatures = guestOsFeatures;
Index = index;
InitializeParams = initializeParams;
Interface = @interface;
Kind = kind;
Licenses = licenses;
Mode = mode;
ShieldedInstanceInitialState = shieldedInstanceInitialState;
Source = source;
Type = type;
}
}
}
| 53.9 | 935 | 0.680891 | [
"Apache-2.0"
] | AaronFriel/pulumi-google-native | sdk/dotnet/Compute/V1/Outputs/AttachedDiskResponse.cs | 7,007 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Realtor.Core.SharedKernel;
using Realtor.Data.Extensions;
namespace Realtor.Data
{
public abstract class EntityConfig<TEntity> : IEntityTypeConfiguration<TEntity> where TEntity : Entity
{
public virtual void Configure(EntityTypeBuilder<TEntity> builder)
{
builder.EnsureKey();
}
}
}
| 26.9375 | 106 | 0.733179 | [
"MIT"
] | rdtriggs/RealtorSite | Realtor.WebApi/Realtor.Data/EntityConfig.cs | 433 | C# |
using System;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
namespace Aspnetcore.Camps.Model.Entities
{
public class CampUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
} | 23.818182 | 56 | 0.698473 | [
"MIT"
] | wghglory/Aspnetcore.Camps | Aspnetcore.Camps.Model/Entities/CampUser.cs | 264 | C# |
using System;
using cOOnsole.Handlers;
using cOOnsole.Handlers.Base;
using FluentAssertions;
using Xunit;
using static cOOnsole.Shortcuts;
namespace cOOnsole.Tests
{
public class ShortcutsTests
{
private readonly Unconditional _dummy = new(HandleResult.Handled);
[Fact]
public void TokenTest() => Token("token", _dummy).Should().BeOfType<Token>();
[Fact]
public void DescriptionTest() => Description("description", _dummy).Should().BeOfType<Description>();
[Fact]
public void ForkTest() => Fork().Should().BeOfType<Fork>();
[Fact]
public void PrintUsageIfUnmatchedTest() => PrintUsageIfNotMatched(new Unconditional(HandleResult.NotMatched))
.Should().BeOfType<PrintUsageIfNotMatched>();
[Fact]
public void UnconditionalTest() => Unconditional(HandleResult.NotMatched).Should().BeOfType<Unconditional>();
[Fact]
public void ActionTest()
=> Action((Action<string[], IHandlerContext>) null!).Should().BeOfType<UntypedAction>();
[Fact]
public void ActionOfTTest()
=> Action((Action<object, IHandlerContext>) null!).Should().BeOfType<TypedAction<object>>();
}
} | 32.421053 | 117 | 0.660714 | [
"MIT"
] | kalexii/cOOnsole | cOOnsole.Tests/ShortcutsTests.cs | 1,234 | C# |
using System;
using HotChocolate.Configuration;
using HotChocolate.Types.Descriptors;
using HotChocolate.Types.Descriptors.Definitions;
namespace HotChocolate.Types
{
public class InterfaceType<T>
: InterfaceType
{
private Action<IInterfaceTypeDescriptor<T>> _configure;
public InterfaceType()
{
_configure = Configure;
}
public InterfaceType(Action<IInterfaceTypeDescriptor<T>> configure)
{
_configure = configure
?? throw new ArgumentNullException(nameof(configure));
}
protected override InterfaceTypeDefinition CreateDefinition(
ITypeDiscoveryContext context)
{
var descriptor = InterfaceTypeDescriptor.New<T>(
context.DescriptorContext);
_configure(descriptor);
return descriptor.CreateDefinition();
}
protected virtual void Configure(IInterfaceTypeDescriptor<T> descriptor)
{
}
protected sealed override void Configure(
IInterfaceTypeDescriptor descriptor)
{
throw new NotSupportedException();
}
}
}
| 26.422222 | 80 | 0.633305 | [
"MIT"
] | GraemeF/hotchocolate | src/HotChocolate/Core/src/Types/Types/InterfaceType~1.cs | 1,189 | C# |
namespace Gripper.ChromeDevTools.Emulation
{
using Newtonsoft.Json;
/// <summary>
/// Used to specify User Agent Cient Hints to emulate. See https://wicg.github.io/ua-client-hints
/// </summary>
public sealed class UserAgentBrandVersion
{
/// <summary>
/// brand
///</summary>
[JsonProperty("brand")]
public string Brand
{
get;
set;
}
/// <summary>
/// version
///</summary>
[JsonProperty("version")]
public string Version
{
get;
set;
}
}
} | 21.689655 | 101 | 0.489666 | [
"MIT"
] | tomaskrupka/Gripper | src/Gripper.ChromeDevTools/Emulation/UserAgentBrandVersion.cs | 629 | C# |
using System.Collections.Generic;
using System.Linq;
using NiuNiu.Library.Domain;
namespace NiuNiu.Library.Solver
{
/// <summary>
/// Finds the best value from a hand for NiuNiu.
/// </summary>
public class HandSolver
{
private List<HandValue> cardValues;
private Hand currentHand;
/// <summary>
/// Gets the best hand value from a hand.
/// </summary>
/// <param name="hand">The <see cref="Hand" /> to solve.</param>
/// <returns></returns>
public HandValue Solve(Hand hand)
{
currentHand = hand;
cardValues = new List<HandValue> { new HandValue(currentHand) };
RecursiveSolve(0, new List<Card>(), currentHand.Cards, 0);
return cardValues.Max();
}
private void RecursiveSolve(int currentSum, IReadOnlyCollection<Card> included, IReadOnlyList<Card> notIncluded, int startIndex)
{
for (int index = startIndex; index < notIncluded.Count; index++)
{
Card nextCard = notIncluded[index];
if ((currentSum + nextCard.FaceValue) % 10 == 0 && included.Count == 2)
{
var leftHand = new Hand(included);
leftHand.AddCard(nextCard);
cardValues.Add(new HandValue(currentHand, leftHand));
}
else if (included.Count < 3)
{
var nextIncluded = new List<Card>(included) { nextCard };
var nextNotIncluded = new List<Card>(notIncluded);
nextNotIncluded.Remove(nextCard);
RecursiveSolve(currentSum + nextCard.FaceValue, nextIncluded, nextNotIncluded, startIndex++);
}
}
}
}
} | 36.42 | 136 | 0.549698 | [
"MIT"
] | EdAllonby/NiuNiu | NiuNiu/NiuNiu.Library/Solver/HandSolver.cs | 1,821 | C# |
using System;
namespace ParadoxNotion.Serialization.FullSerializer {
/// <summary>
/// This attribute controls some serialization behavior for a type. See the comments
/// on each of the fields for more information.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public sealed class fsObjectAttribute : Attribute {
/// <summary>
/// The previous model that should be used if an old version of this
/// object is encountered. Using this attribute also requires that the
/// type have a public constructor that takes only one parameter, an object
/// instance of the given type. Use of this parameter *requires* that
/// the VersionString parameter is also set.
/// </summary>
public Type[] PreviousModels;
/// <summary>
/// The version string to use for this model. This should be unique among all
/// prior versions of this model that is supported for importation. If PreviousModel
/// is set, then this attribute must also be set. A good valid example for this
/// is "v1", "v2", "v3", ...
/// </summary>
public string VersionString;
/// <summary>
/// This controls the behavior for member serialization.
/// The default behavior is fsMemberSerialization.Default.
/// </summary>
public fsMemberSerialization MemberSerialization = fsMemberSerialization.Default;
/// <summary>
/// Specify a custom converter to use for serialization. The converter type needs
/// to derive from fsBaseConverter. This defaults to null.
/// </summary>
public Type Converter;
/// <summary>
/// Specify a custom processor to use during serialization. The processor type needs
/// to derive from fsObjectProcessor and the call to CanProcess is not invoked. This
/// defaults to null.
/// </summary>
public Type Processor;
public fsObjectAttribute() { }
public fsObjectAttribute(string versionString, params Type[] previousModels) {
VersionString = versionString;
PreviousModels = previousModels;
}
}
} | 43.153846 | 92 | 0.646168 | [
"MIT"
] | CITMUniversityExercises/AIExercises | AIVisualScripting/AIVisualScripting/Assets/ParadoxNotion/NodeCanvas/Framework/_Commons/Runtime/Serialization/Full Serializer/fsObjectAttribute.cs | 2,246 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Data;
using System.Collections;
using System.Collections.Specialized;
namespace Nixxis.Client.Controls
{
public abstract class NixxisBasePanel : Panel
{
static NixxisBasePanel()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(NixxisBasePanel), new FrameworkPropertyMetadata(typeof(NixxisBasePanel)));
}
public static readonly RoutedEvent HeightToShowContentChangedEvent = EventManager.RegisterRoutedEvent("HeightToShowContentChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(NixxisBasePanel));
public static readonly DependencyProperty PriorityProperty = DependencyProperty.RegisterAttached("Priority", typeof(int), typeof(NixxisBasePanel), new PropertyMetadata(0));
public static readonly DependencyProperty HeightToShowContentProperty = DependencyProperty.Register("HeightToShowContent", typeof(double), typeof(NixxisBasePanel), new PropertyMetadata(new PropertyChangedCallback(HeightToShowContentChanging)));
public static readonly DependencyProperty TopToShowContentProperty = DependencyProperty.Register("TopToShowContent", typeof(double), typeof(NixxisBasePanel));
public static readonly DependencyProperty HiddenContentProperty = DependencyProperty.Register("HiddenContent", typeof(bool), typeof(NixxisBasePanel));
public static readonly DependencyProperty ItemsWidthProperty = DependencyProperty.Register("ItemsWidth", typeof(double), typeof(NixxisBasePanel));
public static readonly DependencyProperty ItemsHeightProperty = DependencyProperty.Register("ItemsHeight", typeof(double), typeof(NixxisBasePanel));
public static readonly DependencyProperty MinimizedProperty = DependencyProperty.Register("Minimized", typeof(bool), typeof(NixxisBasePanel));
public bool Minimized
{
get
{
return (bool)GetValue(MinimizedProperty);
}
set
{
SetValue(MinimizedProperty, value);
}
}
public double ItemsWidth
{
get
{
return (double)GetValue(ItemsWidthProperty);
}
set
{
SetValue(ItemsWidthProperty, value);
}
}
public double ItemsHeight
{
get
{
return (double)GetValue(ItemsHeightProperty);
}
set
{
SetValue(ItemsHeightProperty, value);
}
}
public bool HiddenContent
{
get
{
return (bool)GetValue(HiddenContentProperty);
}
set
{
SetValue(HiddenContentProperty, value);
}
}
public double HeightToShowContent
{
get
{
return (double)GetValue(HeightToShowContentProperty);
}
set
{
SetValue(HeightToShowContentProperty, value);
}
}
public double TopToShowContent
{
get
{
return (double)GetValue(TopToShowContentProperty);
}
set
{
SetValue(TopToShowContentProperty, value);
}
}
public static void HeightToShowContentChanging(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
NixxisBasePanel nbp = obj as NixxisBasePanel;
nbp.RaiseEvent(new RoutedEventArgs(NixxisBasePanel.HeightToShowContentChangedEvent));
}
public event RoutedEventHandler HeightToShowContentChanged
{
add { AddHandler(HeightToShowContentChangedEvent, value); }
remove { RemoveHandler(HeightToShowContentChangedEvent, value); }
}
public static void SetPriority(UIElement element, Int32 value)
{
element.SetValue(PriorityProperty, value);
}
public static int GetPriority(UIElement element)
{
return (int)(element.GetValue(PriorityProperty));
}
}
public class NixxisPriorityPanel : NixxisBasePanel
{
static NixxisPriorityPanel()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(NixxisPriorityPanel), new FrameworkPropertyMetadata(typeof(NixxisPriorityPanel)));
}
protected override Size ArrangeOverride(Size finalSize)
{
int numbuttonVertical = (int)(finalSize.Height / ItemsHeight);
int numbuttonHorizontal = (int)(finalSize.Width / ItemsWidth);
int numVisible = numbuttonVertical * numbuttonHorizontal;
int currentColumn = 0;
int currentRow = 0;
int collapsedChild = 0;
foreach (UIElement uie in Children)
{
if (uie.Visibility == System.Windows.Visibility.Collapsed)
collapsedChild++;
else if (uie is StackPanel && ((StackPanel)uie).Children.Count == 1 && ((StackPanel)uie).Children[0].Visibility==Visibility.Collapsed)
collapsedChild++;
}
if (numbuttonHorizontal > 0)
{
HeightToShowContent = Math.Ceiling((double)(Children.Count -collapsedChild ) / numbuttonHorizontal) * ItemsHeight;
TopToShowContent = -HeightToShowContent;
}
bool SomethingHidden = false;
Dictionary<UIElement, bool> visibilities = new Dictionary<UIElement, bool>();
foreach (UIElement ctrl in (Children.Cast<UIElement>()).OrderByDescending(elm => (int)(elm.GetValue(PriorityProperty))))
{
if (ctrl.Visibility != Visibility.Collapsed
&& !(ctrl is StackPanel && ((StackPanel)ctrl).Children.Count == 1 && ((StackPanel)ctrl).Children[0].Visibility == Visibility.Collapsed)
)
{
if (numVisible > 0)
{
numVisible--;
visibilities.Add(ctrl, true);
}
else
{
visibilities.Add(ctrl, false);
SomethingHidden = true;
}
}
}
currentColumn = 0;
foreach (UIElement ctrl in Children)
{
if (ctrl.Visibility != Visibility.Collapsed
&& !(ctrl is StackPanel && ((StackPanel)ctrl).Children.Count == 1 && ((StackPanel)ctrl).Children[0].Visibility == Visibility.Collapsed)
&& visibilities[ctrl])
{
if (currentColumn >= numbuttonHorizontal)
{
currentRow++;
currentColumn = 0;
}
ctrl.Arrange(new Rect(new Point(currentColumn * ItemsWidth, currentRow * ItemsHeight), new Size(ItemsWidth, ItemsHeight)));
currentColumn++;
}
else
{
ctrl.Arrange(new Rect(0, 0, 0, 0));
}
}
HiddenContent = SomethingHidden;
return finalSize;
}
protected override Size MeasureOverride(Size availableSize)
{
return availableSize;
}
}
public class NixxisCoverFlowPanelDefaultTemplateSelector : DataTemplateSelector
{
public DataTemplate NotCovered { get; set; }
public DataTemplate CoveredOnTop { get; set; }
public DataTemplate CoveredOnBottom { get; set; }
public DataTemplate FullView { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
try
{
NixxisCoverFlowPanel.CoverFlowState cfs = NixxisCoverFlowPanel.GetCovered(container as UIElement);
switch (cfs)
{
case NixxisCoverFlowPanel.CoverFlowState.FullView:
return FullView;
case NixxisCoverFlowPanel.CoverFlowState.NotCovered:
return NotCovered;
case NixxisCoverFlowPanel.CoverFlowState.CoveredOnBottom:
return CoveredOnBottom;
case NixxisCoverFlowPanel.CoverFlowState.CoveredOnTop:
return CoveredOnTop;
}
}
catch
{
}
return base.SelectTemplate(item, container);
}
}
public class NixxisCoverFlowPanel : NixxisBasePanel
{
static NixxisCoverFlowPanel()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(NixxisCoverFlowPanel), new FrameworkPropertyMetadata(typeof(NixxisCoverFlowPanel)));
}
private int m_SelectedMargin = 5;
public enum CoverFlowState
{
FullView,
NotCovered,
CoveredOnTop,
CoveredOnBottom
}
public static readonly DependencyProperty CoveredProperty = DependencyProperty.RegisterAttached("Covered", typeof(CoverFlowState), typeof(NixxisCoverFlowPanel), new PropertyMetadata(CoverFlowState.NotCovered, new PropertyChangedCallback(CoveredChanged)));
public static readonly DependencyProperty IsSelectedProperty = DependencyProperty.RegisterAttached("IsSelected", typeof(bool), typeof(NixxisCoverFlowPanel), new PropertyMetadata(false, new PropertyChangedCallback(IsSelectedChanged)));
public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register("SelectedItem", typeof(object), typeof(NixxisCoverFlowPanel), new PropertyMetadata(null, new PropertyChangedCallback(SelectedItemChanged)));
public static readonly RoutedEvent SelectionChangedEvent = EventManager.RegisterRoutedEvent("SelectionChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(NixxisCoverFlowPanel));
public event RoutedEventHandler SelectionChanged
{
add { AddHandler(SelectionChangedEvent, value); }
remove { RemoveHandler(SelectionChangedEvent, value); }
}
public static void CoveredChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
DependencyObject dep = obj;
DependencyObject nixxisCoverFlowPanelChild = null;
while ((dep != null) && !(dep is NixxisCoverFlowPanel))
{
nixxisCoverFlowPanelChild = dep;
dep = VisualTreeHelper.GetParent(dep);
}
NixxisCoverFlowPanel thisExpandPanel = (NixxisCoverFlowPanel)dep;
if (nixxisCoverFlowPanelChild is ContentPresenter)
{
ContentPresenter cp = (ContentPresenter)nixxisCoverFlowPanelChild;
DataTemplateSelector backup = cp.ContentTemplateSelector;
cp.ContentTemplateSelector = null;
cp.ContentTemplateSelector = backup;
}
}
public static void SelectedItemChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
NixxisCoverFlowPanel thisExpandPanel = (NixxisCoverFlowPanel)obj;
if (args.NewValue == null)
{
Helpers.ApplyToChildren<FrameworkElement>(thisExpandPanel, NixxisCoverFlowPanel.IsSelectedProperty, false, (fe) => (NixxisCoverFlowPanel.GetIsSelected(fe)));
}
else
{
Helpers.ApplyToChildren<FrameworkElement>(thisExpandPanel, NixxisCoverFlowPanel.IsSelectedProperty, true, (fe) => ((fe as ContentPresenter).Content == args.NewValue && !NixxisCoverFlowPanel.GetIsSelected(fe)));
}
}
public static void IsSelectedChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
DependencyObject dep = obj;
DependencyObject nixxisCoverFlowPanelChild = null;
while ((dep != null) && !(dep is NixxisCoverFlowPanel))
{
nixxisCoverFlowPanelChild = dep;
dep = VisualTreeHelper.GetParent(dep);
}
NixxisCoverFlowPanel thisExpandPanel = (NixxisCoverFlowPanel)dep;
bool selected = (bool)args.NewValue;
if (selected)
{
foreach (UIElement ctrl in thisExpandPanel.Children)
{
if (ctrl != nixxisCoverFlowPanelChild && GetIsSelected(ctrl))
{
SetIsSelected(ctrl, false);
}
}
ContentPresenter cp = nixxisCoverFlowPanelChild as ContentPresenter;
if (cp!=null)
{
thisExpandPanel.SelectedItem = cp.Content;
}
}
else
{
if (thisExpandPanel.SelectedItem == ((ContentPresenter)nixxisCoverFlowPanelChild).Content && !GetIsSelected(nixxisCoverFlowPanelChild as UIElement))
{
SetIsSelected(nixxisCoverFlowPanelChild as UIElement, true);
return;
}
}
thisExpandPanel.RaiseEvent(new RoutedEventArgs(NixxisCoverFlowPanel.SelectionChangedEvent));
thisExpandPanel.InvalidateVisual();
}
public static void SetCovered(UIElement element, CoverFlowState value)
{
element.SetValue(CoveredProperty, value);
}
public static CoverFlowState GetCovered(UIElement element)
{
return (CoverFlowState)(element.GetValue(CoveredProperty));
}
public static void SetIsSelected(UIElement element, bool value)
{
element.SetValue(IsSelectedProperty, value);
}
public static bool GetIsSelected(UIElement element)
{
return (bool)(element.GetValue(IsSelectedProperty));
}
public object SelectedItem
{
get
{
return GetValue(SelectedItemProperty);
}
set
{
SetValue(SelectedItemProperty, value);
}
}
protected override Size ArrangeOverride(Size finalSize)
{
int indexSelected = -1;
for (int i = 0; i < Children.Count; i++)
{
UIElement ctrl = Children[i];
if (GetIsSelected(ctrl))
{
indexSelected = i;
break;
}
}
if (finalSize.Height < ItemsHeight)
return finalSize;
if (Children.Count == 1)
{
// will be done later...
}
else
{
HeightToShowContent = Math.Ceiling((double)Children.Count) * ItemsHeight;
TopToShowContent = -HeightToShowContent;
}
double smallWidth = /*ActualWidth*/finalSize.Width - 2 * m_SelectedMargin;
if (finalSize.Height >= HeightToShowContent)
{
if (Children.Count == 1)
{
SetCovered(Children[0], CoverFlowState.FullView);
Children[0].Measure(new Size(finalSize.Width, double.MaxValue));
Size desire = Children[0].DesiredSize;
HeightToShowContent = desire.Height;
TopToShowContent = -HeightToShowContent;
Children[0].Arrange(new Rect(new Point(0, 0), finalSize));
HiddenContent = (desire.Height > finalSize.Height);
}
else
{
HiddenContent = true;
int currentRow = 0;
foreach (UIElement ctrl in Children)
{
if (ctrl.Visibility != System.Windows.Visibility.Collapsed)
{
SetCovered(ctrl, CoverFlowState.NotCovered);
if (GetIsSelected(ctrl))
{
ctrl.Measure(new Size(/*ActualWidth*/finalSize.Width, ItemsHeight));
ctrl.Arrange(new Rect(new Point(0, currentRow * ItemsHeight), new Size(/*ActualWidth*/finalSize.Width, ItemsHeight)));
}
else
{
ctrl.Measure(new Size(smallWidth, ItemsHeight));
ctrl.Arrange(new Rect(new Point(m_SelectedMargin, currentRow * ItemsHeight), new Size(smallWidth, ItemsHeight)));
}
ctrl.RenderTransform = null;
currentRow++;
}
}
}
}
else
{
if (Children.Count == 1)
{
SetCovered(Children[0], CoverFlowState.FullView);
Children[0].Measure(new Size(finalSize.Width, double.MaxValue));
Size desire = Children[0].DesiredSize;
HeightToShowContent = desire.Height;
TopToShowContent = -HeightToShowContent;
Children[0].Arrange(new Rect(new Point(0, 0), finalSize));
HiddenContent = (desire.Height > finalSize.Height);
}
else
{
HiddenContent = true;
int count = Children.Count;
int stepcount = 0;
double step = (finalSize.Height - ItemsHeight) / (Children.Count - 1);
int zIndex = Children.Count - indexSelected;
double min = 0.9;
for (int i = 0; i < indexSelected; i++)
{
UIElement ctrl = Children[i];
if (ctrl.Visibility != System.Windows.Visibility.Collapsed)
{
SetCovered(ctrl, CoverFlowState.CoveredOnBottom);
if (/*ActualWidth*/finalSize.Width == 0)
continue;
Panel.SetZIndex(ctrl, zIndex);
zIndex++;
ctrl.Measure(new Size(smallWidth, ItemsHeight));
double scale = (1 - min) / indexSelected * (i) + min;
ctrl.Arrange(new Rect(new Point(m_SelectedMargin, stepcount * step), new Size(smallWidth, ItemsHeight)));
if (indexSelected != -1)
ctrl.RenderTransform = new ScaleTransform(scale, scale, smallWidth / 2, ItemsHeight / 2);
count--;
stepcount++;
}
}
if (indexSelected != -1)
{
UIElement ctrl = Children[indexSelected];
if (ctrl.Visibility != System.Windows.Visibility.Collapsed)
{
SetCovered(ctrl, CoverFlowState.NotCovered);
Panel.SetZIndex(ctrl, zIndex);
zIndex--;
ctrl.Measure(new Size(/*ActualWidth*/finalSize.Width, ItemsHeight));
ctrl.Arrange(new Rect(new Point(0, stepcount * step), new Size(/*ActualWidth*/finalSize.Width, ItemsHeight)));
ctrl.RenderTransform = null;
count--;
stepcount++;
}
}
for (int i = indexSelected + 1; i < Children.Count; i++)
{
UIElement ctrl = Children[i];
if (ctrl.Visibility != System.Windows.Visibility.Collapsed)
{
if (/*ActualWidth*/finalSize.Width == 0)
continue;
SetCovered(ctrl, CoverFlowState.CoveredOnTop);
Panel.SetZIndex(ctrl, zIndex);
zIndex--;
ctrl.Measure(new Size(smallWidth, ItemsHeight));
double scale = (min - 1) / (Children.Count - 1 - indexSelected) * (i) + (1 - (min - 1) / (Children.Count - 1 - indexSelected) * indexSelected);
ctrl.Arrange(new Rect(new Point(m_SelectedMargin, stepcount * step), new Size(smallWidth, ItemsHeight)));
if (indexSelected != -1)
ctrl.RenderTransform = new ScaleTransform(scale, scale, smallWidth / 2, ItemsHeight / 2);
count--;
stepcount++;
}
}
}
}
return finalSize;
}
protected override Size MeasureOverride(Size availableSize)
{
Size returnVal = new Size(availableSize.Width, availableSize.Height);
if (returnVal.Height == double.PositiveInfinity)
returnVal.Height = double.MaxValue;
if (returnVal.Width == double.PositiveInfinity)
returnVal.Width = double.MaxValue;
return returnVal;
}
}
public abstract class NixxisBaseExpandPanel : Grid
{
public class NixxisUIElementCollection : UIElementCollection
{
public delegate int ElementAddedEventHandler(object sender, ElementAddedEventsArgs args);
public class ElementAddedEventsArgs : EventArgs
{
public UIElement element { get; set; }
}
public NixxisUIElementCollection(UIElement visualParent, FrameworkElement logicalParent)
: base(visualParent, logicalParent)
{
}
public override int Add(UIElement e)
{
if (Added != null)
return Added(this, new ElementAddedEventsArgs() { element = e });
return base.Add(e);
}
public event ElementAddedEventHandler Added;
}
public static readonly RoutedEvent MinimumPanelHeightChangedEvent = EventManager.RegisterRoutedEvent("MinimumPanelHeightChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(NixxisBaseExpandPanel));
public static readonly RoutedEvent HeightToShowContentChangedEvent = EventManager.RegisterRoutedEvent("HeightToShowContentChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(NixxisBaseExpandPanel));
public static readonly DependencyProperty ItemTemplateSelectorProperty = DependencyProperty.Register("ItemTemplateSelector", typeof(DataTemplateSelector), typeof(NixxisBaseExpandPanel), new PropertyMetadata(null, new PropertyChangedCallback(ItemTemplateSelectorChanged)));
public static readonly DependencyProperty ItemTemplateProperty = DependencyProperty.Register("ItemTemplate", typeof(DataTemplate), typeof(NixxisBaseExpandPanel), new PropertyMetadata(null, new PropertyChangedCallback(ItemTemplateChanged)));
public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(object), typeof(NixxisBaseExpandPanel), new PropertyMetadata(null, new PropertyChangedCallback(ItemsSourceChanged)));
public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register("SelectedItem", typeof(object), typeof(NixxisBaseExpandPanel), new PropertyMetadata(null, new PropertyChangedCallback(SelectedItemChanged)));
public static readonly DependencyProperty ChildrenProperty = DependencyProperty.Register("Children", typeof(UIElementCollection), typeof(NixxisBaseExpandPanel));
public static readonly DependencyProperty ExpandButtonTemplateProperty = DependencyProperty.Register("ExpandButtonTemplate", typeof(ControlTemplate), typeof(NixxisBaseExpandPanel), new PropertyMetadata(null, new PropertyChangedCallback(ExpandButtonTemplateChanged)));
public static readonly DependencyProperty HeightToShowContentProperty = DependencyProperty.Register("HeightToShowContent", typeof(double), typeof(NixxisBaseExpandPanel));
public static readonly DependencyProperty ItemsWidthProperty = DependencyProperty.Register("ItemsWidth", typeof(double), typeof(NixxisBaseExpandPanel), new PropertyMetadata( new PropertyChangedCallback(ItemsWidthChanged)));
public static readonly DependencyProperty ItemsHeightProperty = DependencyProperty.Register("ItemsHeight", typeof(double), typeof(NixxisBaseExpandPanel), new PropertyMetadata( new PropertyChangedCallback(ItemsHeightChanged)));
public static readonly DependencyProperty MinimumNumberOfHorizontalItemsProperty = DependencyProperty.Register("MinimumNumberOfHorizontalItems", typeof(int), typeof(NixxisBaseExpandPanel), new PropertyMetadata(1));
public static readonly DependencyProperty MinimumNumberOfVerticalItemsProperty = DependencyProperty.Register("MinimumNumberOfVerticalItems", typeof(int), typeof(NixxisBaseExpandPanel), new PropertyMetadata(1));
public static readonly DependencyProperty MinimumPanelWidthProperty = DependencyProperty.Register("MinimumPanelWidth", typeof(double), typeof(NixxisBaseExpandPanel));
public static readonly DependencyProperty MinimumPanelHeightProperty = DependencyProperty.Register("MinimumPanelHeight", typeof(double), typeof(NixxisBaseExpandPanel), new PropertyMetadata(new PropertyChangedCallback(MinimumPanelHeightChanging)));
public static readonly DependencyProperty CollapsedPanelHeightProperty = DependencyProperty.Register("CollapsedPanelHeight", typeof(double), typeof(NixxisBaseExpandPanel));
public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(NixxisBaseExpandPanel));
public static readonly DependencyProperty MinimizedProperty = DependencyProperty.Register("Minimized", typeof(bool), typeof(NixxisBaseExpandPanel), new PropertyMetadata(false, new PropertyChangedCallback(MinimizedChanged)));
public static readonly DependencyProperty MinimizedToolTipContentProperty = DependencyProperty.Register("MinimizedToolTipContent", typeof(ToolTip), typeof(NixxisBaseExpandPanel));
public static readonly DependencyProperty ToolTipContentProperty = DependencyProperty.Register("ToolTipContent", typeof(ToolTip), typeof(NixxisBaseExpandPanel));
public static readonly DependencyProperty ToolTipPreviewImageProperty = DependencyProperty.Register("ToolTipPreviewImage", typeof(ImageSource), typeof(NixxisBaseExpandPanel));
public static readonly RoutedEvent SelectionChangedEvent = EventManager.RegisterRoutedEvent("SelectionChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(NixxisBaseExpandPanel));
public event RoutedEventHandler SelectionChanged
{
add { AddHandler(SelectionChangedEvent, value); }
remove { RemoveHandler(SelectionChangedEvent, value); }
}
public static readonly RoutedEvent ExpandStartingEvent = EventManager.RegisterRoutedEvent("ExpandStarting", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(NixxisBaseExpandPanel));
public event RoutedEventHandler ExpandStarting
{
add { AddHandler(ExpandStartingEvent, value); }
remove { RemoveHandler(ExpandStartingEvent, value); }
}
public static readonly RoutedEvent ExpandCompletedEvent = EventManager.RegisterRoutedEvent("ExpandCompleted", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(NixxisBaseExpandPanel));
public event RoutedEventHandler ExpandCompleted
{
add { AddHandler(ExpandCompletedEvent, value); }
remove { RemoveHandler(ExpandCompletedEvent, value); }
}
public static readonly RoutedEvent CollapseCompletedEvent = EventManager.RegisterRoutedEvent("CollapseCompleted", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(NixxisBaseExpandPanel));
public event RoutedEventHandler CollapseCompleted
{
add { AddHandler(CollapseCompletedEvent, value); }
remove { RemoveHandler(CollapseCompletedEvent, value); }
}
public static readonly RoutedEvent CollapseStartedEvent = EventManager.RegisterRoutedEvent("CollapseStarted", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(NixxisBaseExpandPanel));
public event RoutedEventHandler CollapseStarted
{
add { AddHandler(CollapseStartedEvent, value); }
remove { RemoveHandler(CollapseStartedEvent, value); }
}
public static void ItemTemplateSelectorChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
NixxisBaseExpandPanel thisExpandPanel = (NixxisBaseExpandPanel)obj;
DataTemplateSelector templateSelector = args.NewValue as DataTemplateSelector;
foreach (ContentPresenter cp in thisExpandPanel.m_Panel.Children)
{
if (cp != null)
{
cp.SetBinding(ContentPresenter.ContentTemplateSelectorProperty, new Binding() { Source = templateSelector });
}
}
}
public static void ItemTemplateChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
NixxisBaseExpandPanel thisExpandPanel = (NixxisBaseExpandPanel)obj;
DataTemplate template = args.NewValue as DataTemplate;
foreach (ContentPresenter cp in thisExpandPanel.m_Panel.Children)
{
if (cp != null)
{
cp.SetBinding(ContentPresenter.ContentTemplateProperty, new Binding() { Source = template });
}
}
}
public static void ItemsSourceChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
NixxisBaseExpandPanel thisExpandPanel = (NixxisBaseExpandPanel)obj;
IEnumerable collection = args.NewValue as IEnumerable;
if (collection is INotifyCollectionChanged)
{
INotifyCollectionChanged notcol = (INotifyCollectionChanged)collection;
thisExpandPanel.ItemsSourceCollection_CollectionChanged(collection, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
notcol.CollectionChanged += new NotifyCollectionChangedEventHandler(thisExpandPanel.ItemsSourceCollection_CollectionChanged);
}
else
{
object[] objs = new object[]{args.NewValue};
thisExpandPanel.ItemsSourceCollection_CollectionChanged(objs, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
public static void SelectedItemChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
NixxisBaseExpandPanel thisExpandPanel = (NixxisBaseExpandPanel)obj;
if (thisExpandPanel != null)
{
if (thisExpandPanel.m_Panel is NixxisCoverFlowPanel)
{
((NixxisCoverFlowPanel)(thisExpandPanel.m_Panel)).SelectedItem = args.NewValue;
}
}
}
public static void MinimizedChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
((NixxisBaseExpandPanel)obj).CheckMinimumSizeForPreview();
((NixxisBaseExpandPanel)obj).m_Panel.Minimized = ((NixxisBaseExpandPanel)obj).Minimized;
}
public static void ItemsWidthChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
((NixxisBaseExpandPanel)obj).m_Panel.ItemsWidth = (double)args.NewValue;
double dbl = (double)((NixxisBaseExpandPanel)obj).GetValue(NixxisBaseExpandPanel.MinimumPanelWidthProperty);
int num = (int)((NixxisBaseExpandPanel)obj).GetValue(NixxisBaseExpandPanel.MinimumNumberOfHorizontalItemsProperty);
if ((double)args.NewValue * num > dbl)
((NixxisBaseExpandPanel)obj).SetValue(NixxisBaseExpandPanel.MinimumPanelWidthProperty, num * (double)args.NewValue);
}
public static void ItemsHeightChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
((NixxisBaseExpandPanel)obj).m_Panel.ItemsHeight = (double)args.NewValue;
double dbl = (double)((NixxisBaseExpandPanel)obj).GetValue(NixxisBaseExpandPanel.MinimumPanelHeightProperty);
int num = (int)((NixxisBaseExpandPanel)obj).GetValue(NixxisBaseExpandPanel.MinimumNumberOfVerticalItemsProperty);
if ((double)args.NewValue * num + ((NixxisBaseExpandPanel)obj).m_ToggleButton.ActualHeight > dbl)
{
((NixxisBaseExpandPanel)obj).SetValue(NixxisBaseExpandPanel.MinimumPanelHeightProperty, ((NixxisBaseExpandPanel)obj).m_ToggleButton.ActualHeight + num * (double)args.NewValue);
}
}
public static void ExpandButtonTemplateChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
NixxisBaseExpandPanel nbep = ((NixxisBaseExpandPanel)obj);
ControlTemplate template = args.NewValue as ControlTemplate;
if (template != null && nbep != null)
nbep.m_ToggleButton.Template = template;
}
public static void MinimumPanelHeightChanging(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
NixxisBaseExpandPanel nbep = ((NixxisBaseExpandPanel)obj);
nbep.RaiseEvent(new RoutedEventArgs(NixxisBaseExpandPanel.MinimumPanelHeightChangedEvent));
}
public event RoutedEventHandler MinimumPanelHeightChanged
{
add { AddHandler(MinimumPanelHeightChangedEvent, value); }
remove { RemoveHandler(MinimumPanelHeightChangedEvent, value); }
}
public event RoutedEventHandler HeightToShowContentChanged
{
add { AddHandler(HeightToShowContentChangedEvent, value); }
remove { RemoveHandler(HeightToShowContentChangedEvent, value); }
}
void ItemsSourceCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
foreach (object obj in e.NewItems)
{
ContentPresenter contentPresenter = new ContentPresenter();
contentPresenter.SetBinding(ContentPresenter.ContentProperty, new Binding() { Source = obj });
contentPresenter.SetBinding(ContentPresenter.ContentTemplateProperty, new Binding() { Source = ItemTemplate });
contentPresenter.SetBinding(ContentPresenter.ContentTemplateSelectorProperty, new Binding() { Source = ItemTemplateSelector });
m_Panel.Children.Add(contentPresenter);
}
break;
case NotifyCollectionChangedAction.Move:
throw new NotImplementedException("TO DO");
break;
case NotifyCollectionChangedAction.Remove:
foreach (object obj in e.OldItems)
{
foreach (ContentPresenter cc in m_Panel.Children)
{
if (cc != null)
{
Binding binding = BindingOperations.GetBinding(cc, ContentPresenter.ContentProperty);
if (binding != null && binding.Source == obj)
{
m_Panel.Children.Remove(cc);
break;
}
}
}
}
break;
case NotifyCollectionChangedAction.Replace:
throw new NotImplementedException("TO DO");
break;
case NotifyCollectionChangedAction.Reset:
for (int i = 0; i < m_Panel.Children.Count; i++)
{
ContentPresenter cc = m_Panel.Children[i] as ContentPresenter;
if (cc != null)
{
Binding binding = BindingOperations.GetBinding(cc, ContentPresenter.ContentProperty);
if (binding != null)
{
// Not correct when static items added
m_Panel.Children.Remove(cc);
i--;
}
}
}
if (sender != null)
{
foreach (object obj in (IEnumerable)sender)
{
ContentPresenter contentPresenter = new ContentPresenter();
contentPresenter.SetBinding(ContentPresenter.ContentProperty, new Binding() { Source = obj });
contentPresenter.SetBinding(ContentPresenter.ContentTemplateProperty, new Binding() { Source = ItemTemplate });
contentPresenter.SetBinding(ContentPresenter.ContentTemplateSelectorProperty, new Binding() { Source = ItemTemplateSelector });
m_Panel.Children.Add(contentPresenter);
}
}
break;
}
}
static NixxisBaseExpandPanel()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(NixxisBaseExpandPanel), new FrameworkPropertyMetadata(typeof(NixxisBaseExpandPanel)));
}
public object ItemsSource
{
get
{
return GetValue(ItemsSourceProperty);
}
set
{
SetValue(ItemsSourceProperty, value);
}
}
public object SelectedItem
{
get
{
return GetValue(SelectedItemProperty);
}
set
{
SetValue(SelectedItemProperty, value);
}
}
public DataTemplate ItemTemplate
{
get
{
return (DataTemplate)GetValue(ItemTemplateProperty);
}
set
{
SetValue(ItemTemplateProperty, value);
}
}
public DataTemplateSelector ItemTemplateSelector
{
get
{
return (DataTemplateSelector)GetValue(ItemTemplateSelectorProperty);
}
set
{
SetValue(ItemTemplateSelectorProperty, value);
}
}
public new UIElementCollection Children
{
get
{
return (UIElementCollection)GetValue(ChildrenProperty);
}
set
{
SetValue(ChildrenProperty, value);
}
}
public ToolTip MinimizedToolTipContent
{
get
{
return (ToolTip)GetValue(MinimizedToolTipContentProperty);
}
set
{
SetValue(MinimizedToolTipContentProperty, value);
}
}
public ToolTip ToolTipContent
{
get
{
return (ToolTip)GetValue(ToolTipContentProperty);
}
set
{
SetValue(ToolTipContentProperty, value);
}
}
public ImageSource ToolTipPreviewImage
{
get
{
return (ImageSource)GetValue(ToolTipPreviewImageProperty);
}
set
{
SetValue(ToolTipPreviewImageProperty, value);
}
}
public string Title
{
get
{
return (string)GetValue(TitleProperty);
}
set
{
SetValue(TitleProperty, value);
}
}
public bool Minimized
{
get
{
return (bool)GetValue(MinimizedProperty);
}
set
{
SetValue(MinimizedProperty, value);
}
}
public double MinimumPanelWidth
{
get
{
return (double)GetValue(MinimumPanelWidthProperty);
}
set
{
SetValue(MinimumPanelWidthProperty, value);
}
}
public int MinimumNumberOfHorizontalItems
{
get
{
return (int)GetValue(MinimumNumberOfHorizontalItemsProperty);
}
set
{
SetValue(MinimumNumberOfHorizontalItemsProperty, value);
}
}
public int MinimumNumberOfVerticalItems
{
get
{
return (int)GetValue(MinimumNumberOfVerticalItemsProperty);
}
set
{
SetValue(MinimumNumberOfVerticalItemsProperty, value);
}
}
public double MinimumPanelHeight
{
get
{
return (double)GetValue(MinimumPanelHeightProperty);
}
set
{
SetValue(MinimumPanelHeightProperty, value);
}
}
public double CollapsedPanelHeight
{
get
{
return (double)GetValue(CollapsedPanelHeightProperty);
}
}
public double ItemsWidth
{
get
{
return (double)GetValue(ItemsWidthProperty);
}
set
{
SetValue(ItemsWidthProperty, value);
}
}
public double ItemsHeight
{
get
{
return (double)GetValue(ItemsHeightProperty);
}
set
{
SetValue(ItemsHeightProperty, value);
}
}
public double HeightToShowContent
{
get
{
return m_Panel.HeightToShowContent + m_ToggleButton.ActualHeight;
}
}
public ControlTemplate ExpandButtonTemplate
{
get
{
return GetValue(ExpandButtonTemplateProperty) as ControlTemplate;
}
set
{
SetValue(ExpandButtonTemplateProperty, value);
}
}
private bool m_Expanding = false;
private Grid m_InnerGrid = new Grid();
private Storyboard m_CollapseStoryboard = new Storyboard();
private Storyboard m_ExpandStoryboard = new Storyboard();
protected NixxisBasePanel m_Panel;
private ToggleButton m_ToggleButton = new ToggleButton();
private double m_BackupMinHeight = 0;
private int m_Opened_Menu = 0;
private bool m_CloseRequired = false;
private void CheckMinimumSizeForPreview()
{
if (Minimized)
{
MinHeight = HeightToShowContent;
}
else
{
MinHeight = 0;
}
}
public NixxisBaseExpandPanel(NixxisBasePanel childPanel)
{
m_Panel = childPanel;
if (m_Panel is NixxisCoverFlowPanel)
{
((NixxisCoverFlowPanel)(m_Panel)).SelectionChanged += new RoutedEventHandler(NixxisBaseExpandPanel_SelectionChanged);
}
m_Panel.HeightToShowContentChanged += new RoutedEventHandler(m_Panel_HeightToShowContentChanged);
NixxisUIElementCollection nuiec = new NixxisUIElementCollection(this, this);
nuiec.Added += new NixxisUIElementCollection.ElementAddedEventHandler(nuiec_Added);
Children = nuiec;
DoubleAnimation AnimateHeightCollapse = new DoubleAnimation();
AnimateHeightCollapse.Duration = new Duration(TimeSpan.FromMilliseconds(0));
Storyboard.SetTargetProperty(AnimateHeightCollapse, new PropertyPath(HeightProperty));
Storyboard.SetTarget(AnimateHeightCollapse, m_InnerGrid);
m_CollapseStoryboard.Children.Add(AnimateHeightCollapse);
m_CollapseStoryboard.Completed += new EventHandler(m_CollapseStoryboard_Completed);
DoubleAnimation AnimateTopCollapse = new DoubleAnimation();
AnimateTopCollapse.Duration = new Duration(TimeSpan.FromMilliseconds(500));
Storyboard.SetTargetProperty(AnimateTopCollapse, new PropertyPath(Canvas.TopProperty));
Storyboard.SetTarget(AnimateTopCollapse, m_InnerGrid);
AnimateTopCollapse.AccelerationRatio = 0.1;
AnimateTopCollapse.DecelerationRatio = 0.9;
AnimateTopCollapse.EasingFunction = new ElasticEase() { EasingMode = System.Windows.Media.Animation.EasingMode.EaseOut, Oscillations = 1, Springiness = 5 };
m_CollapseStoryboard.Children.Add(AnimateTopCollapse);
DoubleAnimation AnimateHeightExpand = new DoubleAnimation();
AnimateHeightExpand.Duration = new Duration(TimeSpan.FromMilliseconds(0));
Storyboard.SetTargetProperty(AnimateHeightExpand, new PropertyPath(HeightProperty));
Storyboard.SetTarget(AnimateHeightExpand, m_InnerGrid);
m_ExpandStoryboard.Children.Add(AnimateHeightExpand);
m_ExpandStoryboard.Completed += new EventHandler(m_ExpandStoryboard_Completed);
DoubleAnimation AnimateTopExpand = new DoubleAnimation();
AnimateTopExpand.Duration = new Duration(TimeSpan.FromMilliseconds(500));
Storyboard.SetTargetProperty(AnimateTopExpand, new PropertyPath(Canvas.TopProperty));
Storyboard.SetTarget(AnimateTopExpand, m_InnerGrid);
AnimateTopExpand.AccelerationRatio = 0.1;
AnimateTopExpand.DecelerationRatio = 0.9;
AnimateTopExpand.EasingFunction = new ElasticEase() { EasingMode = System.Windows.Media.Animation.EasingMode.EaseOut, Oscillations = 1, Springiness = 5 };
m_ExpandStoryboard.Children.Add(AnimateTopExpand);
}
void NixxisBaseExpandPanel_SelectionChanged(object sender, RoutedEventArgs e)
{
if(m_Panel is NixxisCoverFlowPanel)
{
this.SelectedItem = ((NixxisCoverFlowPanel)(m_Panel)).SelectedItem;
}
RaiseEvent(new RoutedEventArgs(NixxisBaseExpandPanel.SelectionChangedEvent));
}
void m_Panel_HeightToShowContentChanged(object sender, RoutedEventArgs e)
{
this.RaiseEvent(new RoutedEventArgs(NixxisBaseExpandPanel.HeightToShowContentChangedEvent));
}
int nuiec_Added(object sender, NixxisUIElementCollection.ElementAddedEventsArgs args)
{
if (args.element is NixxisButton)
{
((NixxisButton)args.element).DropDownOpening += new RoutedEventHandler(ExNixxisPanel_ContextMenuOpening);
((NixxisButton)args.element).DropDownClosing += new RoutedEventHandler(ExNixxisPanel_ContextMenuClosing);
}
return m_Panel.Children.Add(args.element);
}
void m_ExpandStoryboard_Completed(object sender, EventArgs e)
{
m_Panel.Minimized = false;
m_Expanding = false;
if (!m_InnerGrid.IsMouseOver)
{
grd_MouseLeave(this, null);
}
RaiseEvent(new RoutedEventArgs(NixxisBaseExpandPanel.ExpandCompletedEvent));
}
void m_CollapseStoryboard_Completed(object sender, EventArgs e)
{
MinHeight = m_BackupMinHeight;
if (Minimized)
{
m_Panel.Minimized = true;
}
RaiseEvent(new RoutedEventArgs(NixxisBaseExpandPanel.CollapseCompletedEvent));
}
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
Canvas cnv = new Canvas();
if (!IsItemsHost)
InternalChildren.Add(cnv);
m_InnerGrid.MouseLeave += new MouseEventHandler(grd_MouseLeave);
m_InnerGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0, GridUnitType.Auto) { } });
m_InnerGrid.RowDefinitions.Add(new RowDefinition());
cnv.Children.Add(m_InnerGrid);
Canvas.SetTop(m_InnerGrid, 0);
m_InnerGrid.SetBinding(BackgroundProperty, new Binding("Background") { Source = this });
m_InnerGrid.SetBinding(HeightProperty, new Binding("ActualHeight") { Source = this });
m_InnerGrid.SetBinding(WidthProperty, new Binding("ActualWidth") { Source = this });
m_ToggleButton.SizeChanged += new SizeChangedEventHandler(m_ToggleButton_SizeChanged);
if (ExpandButtonTemplate != null)
m_ToggleButton.Template = ExpandButtonTemplate;
MultiBinding mb = new MultiBinding();
mb.Bindings.Add(new Binding() { Source = m_Panel, Path = new PropertyPath(NixxisPriorityPanel.HiddenContentProperty) });
mb.Bindings.Add(new Binding() { Source = this, Path = new PropertyPath(NixxisBaseExpandPanel.MinimizedProperty) });
mb.Converter = new ExpandableConverter();
m_ToggleButton.SetBinding(TagProperty, mb);
mb = new MultiBinding();
mb.Bindings.Add(new Binding() { Source = m_ToggleButton, Path = new PropertyPath(ToggleButton.IsCheckedProperty) });
mb.Bindings.Add(new Binding() { Source = m_ToggleButton, Path = new PropertyPath(ToggleButton.TagProperty) });
mb.Converter = new ExpandableVisibilityConverter();
m_ToggleButton.SetBinding(IsEnabledProperty, mb);
m_InnerGrid.Children.Add(m_ToggleButton);
Grid.SetRow(m_ToggleButton, 0);
m_ToggleButton.Checked += new RoutedEventHandler(tb_Checked);
m_ToggleButton.Unchecked += new RoutedEventHandler(tb_Unchecked);
m_ToggleButton.ToolTip = new object();
m_ToggleButton.ToolTipOpening += new ToolTipEventHandler(m_ToggleButton_ToolTipOpening);
Grid.SetRow(m_Panel, 1);
m_InnerGrid.Children.Add(m_Panel);
}
void ExNixxisPanel_ContextMenuOpening(object sender, RoutedEventArgs e)
{
m_Opened_Menu++;
}
void ExNixxisPanel_ContextMenuClosing(object sender, RoutedEventArgs e)
{
m_Opened_Menu--;
if (m_Opened_Menu == 0 && m_CloseRequired)
{
if (!m_InnerGrid.IsMouseOver)
{
m_ToggleButton.IsChecked = false;
}
m_CloseRequired = false;
}
}
void m_ToggleButton_ToolTipOpening(object sender, ToolTipEventArgs e)
{
try
{
if (Minimized && m_Panel.Minimized)
{
ToolTipPreviewImage = CaptureScreenBitmap(m_InnerGrid);
MinimizedToolTipContent.SetBinding(DataContextProperty, new Binding() { Source = this });
m_ToggleButton.ToolTip = MinimizedToolTipContent;
}
else
{
ToolTipContent.SetBinding(DataContextProperty, new Binding() { Source = this });
m_ToggleButton.ToolTip = ToolTipContent;
}
}
catch
{
}
}
void m_ToggleButton_SizeChanged(object sender, SizeChangedEventArgs e)
{
double minHeight = m_ToggleButton.ActualHeight + ItemsHeight * MinimumNumberOfVerticalItems;
if( ((double)(GetValue(MinimumPanelHeightProperty))) < minHeight)
SetValue(MinimumPanelHeightProperty, minHeight);
SetValue(CollapsedPanelHeightProperty, m_ToggleButton.ActualHeight);
CheckMinimumSizeForPreview();
this.RaiseEvent(new RoutedEventArgs(NixxisBaseExpandPanel.HeightToShowContentChangedEvent));
}
void tb_Unchecked(object sender, RoutedEventArgs e)
{
RaiseEvent(new RoutedEventArgs(NixxisBaseExpandPanel.CollapseStartedEvent));
(m_CollapseStoryboard.Children[0] as DoubleAnimation).From = m_Panel.HeightToShowContent;
BeginStoryboard(m_CollapseStoryboard);
}
void tb_Checked(object sender, RoutedEventArgs e)
{
RaiseEvent(new RoutedEventArgs(NixxisBaseExpandPanel.ExpandStartingEvent));
m_BackupMinHeight = MinHeight;
MinHeight = 0;
UpdateLayout();
m_Expanding = true;
(m_ExpandStoryboard.Children[0] as DoubleAnimation).By = m_Panel.HeightToShowContent;
(m_ExpandStoryboard.Children[1] as DoubleAnimation).By = m_Panel.TopToShowContent + m_Panel.ActualHeight;
BeginStoryboard(m_ExpandStoryboard);
}
void grd_MouseLeave(object sender, MouseEventArgs e)
{
if (!m_Expanding)
{
if (m_Opened_Menu == 0)
m_ToggleButton.IsChecked = false;
else
m_CloseRequired = true;
}
}
private BitmapSource CaptureScreenBitmap(Panel panel)
{
BitmapSource bs = CaptureScreenBitmap(panel,
(int)panel.ActualWidth,
(int)panel.ActualHeight);
return bs;
}
private BitmapSource CaptureScreenBitmap(Visual target, int width, int height)
{
Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
RenderTargetBitmap renderBitmap = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
DrawingVisual visual = new DrawingVisual();
using (DrawingContext context = visual.RenderOpen())
{
VisualBrush brush = new VisualBrush(target);
context.DrawRectangle(brush, null, new Rect(new Point(), bounds.Size));
}
renderBitmap.Render(visual);
return renderBitmap;
}
public FrameworkElement FindByName(string name)
{
return FindByName(name, false);
}
public FrameworkElement FindByName(string name, bool recurseDropDownButtons)
{
foreach (FrameworkElement fe in (m_InnerGrid.Children[1] as NixxisBasePanel).Children)
{
if (fe.Name.Equals(name))
return fe;
if (recurseDropDownButtons && fe is NixxisButton)
{
NixxisButton Btn = (NixxisButton)fe;
if (Btn.DropDown != null)
{
foreach (FrameworkElement Item in Btn.DropDown.Items)
{
if (Item.Name.Equals(name))
return Item;
}
}
}
}
return null;
}
}
public class ExpandableConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return (bool)(values[0]) || (bool)(values[1]);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
internal class ExpandableVisibilityConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool showDownArrow = true;
try
{
if (parameter != null)
showDownArrow = bool.Parse(parameter as string);
}
catch
{
}
bool isChecked = (bool)(values[0]);
bool hasHiddenContent = (bool)(values[1]);
if (targetType == typeof(Visibility))
{
if (hasHiddenContent)
{
if (isChecked)
return Visibility.Visible;
else
if (!showDownArrow)
return Visibility.Hidden;
else
return Visibility.Visible;
}
else
{
if (isChecked)
return Visibility.Visible;
else
return Visibility.Hidden;
}
}
else
{
if (hasHiddenContent)
{
if (isChecked)
return true;
else
if (!showDownArrow)
return false;
else
return true;
}
else
{
if (isChecked)
return true;
else
return false;
}
}
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class NixxisExpandPanel : NixxisBaseExpandPanel
{
public NixxisExpandPanel()
: base(new NixxisPriorityPanel())
{
}
static NixxisExpandPanel()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(NixxisExpandPanel), new FrameworkPropertyMetadata(typeof(NixxisExpandPanel)));
}
}
public class NixxisExpandCoverFlowPanel : NixxisBaseExpandPanel
{
public NixxisExpandCoverFlowPanel()
: base(new NixxisCoverFlowPanel())
{
}
static NixxisExpandCoverFlowPanel()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(NixxisExpandCoverFlowPanel), new FrameworkPropertyMetadata(typeof(NixxisExpandCoverFlowPanel)));
}
}
public class NixxisStackPanel : Panel
{
public static readonly DependencyProperty ActAsLabelProperty = DependencyProperty.RegisterAttached("ActAsLabel", typeof(bool), typeof(NixxisStackPanel), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure));
public static readonly DependencyProperty ActAsLabeledProperty = DependencyProperty.RegisterAttached("ActAsLabeled", typeof(bool), typeof(NixxisStackPanel), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure));
public static readonly DependencyProperty KeepNextAttachedProperty = DependencyProperty.RegisterAttached("KeepNextAttached", typeof(bool), typeof(NixxisStackPanel), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure));
public static readonly DependencyProperty GranularityProperty = DependencyProperty.Register("Granularity", typeof(double), typeof(NixxisStackPanel), new FrameworkPropertyMetadata(20.0, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure));
public static void SetKeepNextAttached(UIElement element, bool value)
{
element.SetValue(KeepNextAttachedProperty, value);
}
public static bool GetKeepNextAttached(UIElement element)
{
return (bool)(element.GetValue(KeepNextAttachedProperty));
}
public static void SetActAsLabel(UIElement element, bool value)
{
element.SetValue(ActAsLabelProperty, value);
}
public static bool GetActAsLabel(UIElement element)
{
return (bool)(element.GetValue(ActAsLabelProperty));
}
public static void SetActAsLabeled(UIElement element, bool value)
{
element.SetValue(ActAsLabeledProperty, value);
}
public static bool GetActAsLabeled(UIElement element)
{
return (bool)(element.GetValue(ActAsLabeledProperty));
}
public double Granularity
{
get
{
return (double)GetValue(GranularityProperty);
}
set
{
SetValue(GranularityProperty, value);
}
}
protected override Size ArrangeOverride(Size finalSize)
{
Size returnValue = new Size(finalSize.Width, 0);
int counter = 0;
bool isAttached = false;
for (int i = 0; i < Children.Count; i++)
{
UIElement uie = (UIElement)Children[i];
if (uie.Visibility != System.Windows.Visibility.Collapsed)
{
if (!isAttached)
{
if (!uie.IsMeasureValid)
uie.Measure(finalSize);
Size sz = uie.DesiredSize;
bool oneRowToSkip = ((uie is Label || GetActAsLabel(uie)) && counter % 2 == 1) || (counter % 2 == 0 && GetActAsLabeled(uie));
if (oneRowToSkip)
counter++;
double computedHeight = ((int)(sz.Height / Granularity) + (oneRowToSkip ? 2 : 1)) * Granularity;
double attachedWidth = 0;
double attachedWidth2 = 0;
UIElement tempuie = null;
UIElement tempuie2 = null;
Size tempsz = Size.Empty;
Size tempsz2 = new Size(0,0);
if (GetKeepNextAttached(uie))
{
tempuie = (UIElement)Children[i + 1];
if (!tempuie.IsMeasureValid)
tempuie.Measure(finalSize);
tempsz = tempuie.DesiredSize;
attachedWidth = tempsz.Width;
if (GetKeepNextAttached(tempuie))
{
tempuie2 = (UIElement)Children[i + 2];
if (!tempuie2.IsMeasureValid)
tempuie2.Measure(finalSize);
tempsz2 = tempuie2.DesiredSize;
attachedWidth2 = tempsz2.Width;
if (tempuie2.Visibility != System.Windows.Visibility.Visible)
{
tempuie2 = null;
}
}
if (tempuie.Visibility != System.Windows.Visibility.Visible)
{
tempuie = null;
}
if (tempuie2!=null && tempuie2.Visibility != System.Windows.Visibility.Visible)
{
tempuie2 = null;
}
}
if (uie.Visibility == System.Windows.Visibility.Visible)
{
if (uie is Label || GetActAsLabel(uie))
{
uie.Arrange(new Rect(0, returnValue.Height + computedHeight - sz.Height, returnValue.Width - attachedWidth -attachedWidth2, sz.Height));
if(tempuie!=null)
tempuie.Arrange(new Rect(returnValue.Width - tempsz.Width -tempsz2.Width, returnValue.Height + computedHeight - sz.Height, tempsz.Width, sz.Height));
if (tempuie2 != null)
tempuie2.Arrange(new Rect(returnValue.Width - tempsz2.Width, returnValue.Height + computedHeight - sz.Height, tempsz2.Width, sz.Height));
}
else
{
if (uie is CheckBox || uie is RadioButton || uie is NixxisDetailedCheckBox)
{
uie.Arrange(new Rect(0, oneRowToSkip ? returnValue.Height + Granularity + (computedHeight - Granularity - sz.Height) /2 : returnValue.Height + (computedHeight - sz.Height) /2 , returnValue.Width - attachedWidth -attachedWidth2, sz.Height));
}
else
{
uie.Arrange(new Rect(0, oneRowToSkip ? returnValue.Height + Granularity : returnValue.Height , returnValue.Width > attachedWidth + attachedWidth2 ? returnValue.Width - attachedWidth -attachedWidth2: 0, sz.Height));
}
if (tempuie != null)
tempuie.Arrange(new Rect(returnValue.Width - tempsz.Width -tempsz2.Width, oneRowToSkip ? returnValue.Height + Granularity: returnValue.Height, tempsz.Width, sz.Height));
if (tempuie2 != null)
tempuie2.Arrange(new Rect(returnValue.Width - tempsz2.Width, oneRowToSkip ? returnValue.Height + Granularity : returnValue.Height, tempsz2.Width, sz.Height));
}
}
counter++;
returnValue.Height += computedHeight;
}
isAttached = GetKeepNextAttached(uie);
}
}
if (Double.IsPositiveInfinity(returnValue.Height))
returnValue.Height = 0;
if (double.IsPositiveInfinity(returnValue.Width))
returnValue.Width = 0;
if (returnValue.Height > finalSize.Height)
returnValue.Height = finalSize.Height;
if (returnValue.Width > finalSize.Width)
returnValue.Width = finalSize.Width;
return returnValue;
}
protected override Size MeasureOverride(Size availableSize)
{
Size returnValue = new Size( availableSize.Width, 0);
bool isAttached = false;
int counter = 0;
for(int i=0; i<Children.Count; i++)
{
UIElement uie = (UIElement)Children[i];
if (uie.Visibility != System.Windows.Visibility.Collapsed)
{
if (!isAttached)
{
// This one seems nice but it is not ok as a TextBlock with active Trimming will return true and will prevent taking care of new size...
uie.Measure(new Size(returnValue.Width, Double.PositiveInfinity));
Size sz = uie.DesiredSize;
bool oneRowToSkip = ((uie is Label || GetActAsLabel(uie)) && counter % 2 == 1) || (counter % 2 == 0 && GetActAsLabeled(uie));
if (oneRowToSkip)
counter++;
double computedHeight = ((int)(sz.Height / Granularity) + (oneRowToSkip ? 2 : 1)) * Granularity;
returnValue.Height += computedHeight;
counter++;
}
isAttached = GetKeepNextAttached(uie);
}
}
if (Double.IsPositiveInfinity(returnValue.Height))
returnValue.Height = 0;
if (double.IsPositiveInfinity(returnValue.Width))
returnValue.Width = 0;
if (returnValue.Height > availableSize.Height)
returnValue.Height = availableSize.Height;
if (returnValue.Width > availableSize.Width)
returnValue.Width = availableSize.Width;
//System.Diagnostics.Trace.WriteLine(string.Format("Measure return {0}x{1}", returnValue.Width, returnValue.Height), "++++++++");
return returnValue;
}
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
this.IsVisibleChanged += new DependencyPropertyChangedEventHandler(NixxisStackPanel_IsVisibleChanged);
}
void NixxisStackPanel_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if ((bool)e.NewValue)
{
BringIntoView();
}
}
}
}
| 41.918343 | 310 | 0.573615 | [
"MIT"
] | Nixxis/ncs-client | NixxisControls/NixxisPanel.cs | 70,844 | C# |
using System.Collections.Generic;
using System.Text;
namespace MargieBot.Utilities
{
internal class BotNameRegexComposer
{
public string ComposeFor(string botName, string botUserID, IEnumerable<string> aliases)
{
StringBuilder builder = new StringBuilder();
builder.Append($@"(<@{botUserID}>|");
builder.Append($@"\b{botName}\b");
foreach (string alias in aliases) {
builder.Append(@"|\b" + alias + @"\b");
}
builder.Append(@")");
return builder.ToString();
}
}
} | 28.666667 | 95 | 0.563123 | [
"MIT"
] | PDun/margiebot | MargieBot/src/BotHelpers/BotNameRegexComposer.cs | 604 | 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.Compute.V20180601.Outputs
{
[OutputType]
public sealed class DiagnosticsProfileResponse
{
/// <summary>
/// Boot Diagnostics is a debugging feature which allows you to view Console Output and Screenshot to diagnose VM status. <br><br> You can easily view the output of your console log. <br><br> Azure also enables you to see a screenshot of the VM from the hypervisor.
/// </summary>
public readonly Outputs.BootDiagnosticsResponse? BootDiagnostics;
[OutputConstructor]
private DiagnosticsProfileResponse(Outputs.BootDiagnosticsResponse? bootDiagnostics)
{
BootDiagnostics = bootDiagnostics;
}
}
}
| 37.357143 | 297 | 0.715105 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Compute/V20180601/Outputs/DiagnosticsProfileResponse.cs | 1,046 | C# |
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
class RegisterRequestModel
{
public string Username { get; set; }
public string Password { get; set; }
public int CharacterType { get; set; }
public RegisterRequestModel(string Username, string Password, int CharacterType)
{
this.Username = Username;
this.Password = Password;
this.CharacterType = CharacterType;
}
}
public class RegisterHandler : MonoBehaviour
{
[SerializeField]
private GameObject usernameInput;
[SerializeField]
private GameObject passwordInput;
[SerializeField]
private CharacterSelection relatedSelection;
private RestRequest FormatRegisterRequest(string apiURL, Method method)
{
string username = usernameInput.GetComponent<TMP_InputField>().text;
string password = passwordInput.GetComponent<TMP_InputField>().text;
//Debug.Log(relatedSelection.GetComponent<CharacterSelection>().GetRelatedSelections().Find(v => v.selected.Equals(true)));
int selectedCharacter = relatedSelection.value; // start by assigning main node
if (!relatedSelection.selected) // if main node is not selected, find the node that is selected
{
selectedCharacter = relatedSelection.GetRelatedSelections().Find(v => v.selected == true).value;
}
var request = new RestRequest(apiURL, method);
var body = new RegisterRequestModel(username, password, selectedCharacter);
request.AddParameter("application/json; charset=utf-8", JsonConvert.SerializeObject(body, Formatting.Indented), ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
Debug.Log(request);
return request;
}
void OnRegister()
{
SceneManager.LoadScene("Game");
}
public void Register()
{
try
{
var response = Network.Instance.restClient.Execute(FormatRegisterRequest("/register", Method.POST));
if (!response.IsSuccessful)
{
Debug.Log("Error authenticating");
return;
}
Tuple<int, SessionResponse> serverResponse = JsonConvert.DeserializeObject<Tuple<int, SessionResponse>>(response.Content);
switch (serverResponse.Item1)
{
case 1:
Session.SessionID = Convert.FromBase64String(serverResponse.Item2.SessionID);
Debug.Log("Registered, status 1, session: " + serverResponse.Item2.SessionID);
OnRegister();
break;
case -1:
Debug.Log("Username already exists!");
break;
case -2:
Debug.Log("Invalid username!");
break;
default:
Debug.Log("Something went wrong...");
break;
}
}
catch (Exception e)
{
Debug.Log("Caught exception: \n" + e.Message + " \n" + e.StackTrace);
}
}
}
| 33.541667 | 147 | 0.617391 | [
"MIT"
] | 4rgetlahm/Object-Group-Game | Unity/Assets/Scripts/Authentication/RegisterHandler.cs | 3,220 | C# |
/**
* Autogenerated by Thrift Compiler (0.12.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Thrift;
using Thrift.Collections;
using System.Runtime.Serialization;
using Thrift.Protocol;
using Thrift.Transport;
namespace Ruyi.SDK.CommonType
{
/// <summary>
/// @RuyiFeatures_desc
/// </summary>
#if !SILVERLIGHT
[Serializable]
#endif
public partial class RuyiFeatures : TBase
{
private bool _ruyi_xinput;
private bool _ruyi_dinput;
private bool _ruyi_sdkinput;
/// <summary>
/// @RuyiFeatures_ruyi_xinput_desc
/// </summary>
public bool Ruyi_xinput
{
get
{
return _ruyi_xinput;
}
set
{
__isset.ruyi_xinput = true;
this._ruyi_xinput = value;
}
}
/// <summary>
/// @RuyiFeatures_ruyi_dinput_desc
/// </summary>
public bool Ruyi_dinput
{
get
{
return _ruyi_dinput;
}
set
{
__isset.ruyi_dinput = true;
this._ruyi_dinput = value;
}
}
/// <summary>
/// @RuyiFeatures_ruyi_sdkinput_desc
/// </summary>
public bool Ruyi_sdkinput
{
get
{
return _ruyi_sdkinput;
}
set
{
__isset.ruyi_sdkinput = true;
this._ruyi_sdkinput = value;
}
}
public Isset __isset;
#if !SILVERLIGHT
[Serializable]
#endif
public struct Isset {
public bool ruyi_xinput;
public bool ruyi_dinput;
public bool ruyi_sdkinput;
}
public RuyiFeatures() {
this._ruyi_xinput = false;
this.__isset.ruyi_xinput = true;
this._ruyi_dinput = false;
this.__isset.ruyi_dinput = true;
this._ruyi_sdkinput = false;
this.__isset.ruyi_sdkinput = true;
}
public void Read (TProtocol iprot)
{
iprot.IncrementRecursionDepth();
try
{
TField field;
iprot.ReadStructBegin();
while (true)
{
field = iprot.ReadFieldBegin();
if (field.Type == TType.Stop) {
break;
}
switch (field.ID)
{
case 1:
if (field.Type == TType.Bool) {
Ruyi_xinput = iprot.ReadBool();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 2:
if (field.Type == TType.Bool) {
Ruyi_dinput = iprot.ReadBool();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 3:
if (field.Type == TType.Bool) {
Ruyi_sdkinput = iprot.ReadBool();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
default:
TProtocolUtil.Skip(iprot, field.Type);
break;
}
iprot.ReadFieldEnd();
}
iprot.ReadStructEnd();
}
finally
{
iprot.DecrementRecursionDepth();
}
}
public void Write(TProtocol oprot) {
oprot.IncrementRecursionDepth();
try
{
TStruct struc = new TStruct("RuyiFeatures");
oprot.WriteStructBegin(struc);
TField field = new TField();
if (__isset.ruyi_xinput) {
field.Name = "ruyi_xinput";
field.Type = TType.Bool;
field.ID = 1;
oprot.WriteFieldBegin(field);
oprot.WriteBool(Ruyi_xinput);
oprot.WriteFieldEnd();
}
if (__isset.ruyi_dinput) {
field.Name = "ruyi_dinput";
field.Type = TType.Bool;
field.ID = 2;
oprot.WriteFieldBegin(field);
oprot.WriteBool(Ruyi_dinput);
oprot.WriteFieldEnd();
}
if (__isset.ruyi_sdkinput) {
field.Name = "ruyi_sdkinput";
field.Type = TType.Bool;
field.ID = 3;
oprot.WriteFieldBegin(field);
oprot.WriteBool(Ruyi_sdkinput);
oprot.WriteFieldEnd();
}
oprot.WriteFieldStop();
oprot.WriteStructEnd();
}
finally
{
oprot.DecrementRecursionDepth();
}
}
public override string ToString() {
StringBuilder __sb = new StringBuilder("RuyiFeatures(");
bool __first = true;
if (__isset.ruyi_xinput) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("Ruyi_xinput: ");
__sb.Append(Ruyi_xinput);
}
if (__isset.ruyi_dinput) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("Ruyi_dinput: ");
__sb.Append(Ruyi_dinput);
}
if (__isset.ruyi_sdkinput) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("Ruyi_sdkinput: ");
__sb.Append(Ruyi_sdkinput);
}
__sb.Append(")");
return __sb.ToString();
}
}
}
| 23.43379 | 67 | 0.533905 | [
"MIT"
] | jake-ruyi/sdk | ServiceGenerated.nf2.0/GeneratedSync/Ruyi/SDK/CommonType/RuyiFeatures.cs | 5,132 | C# |
using System;
using System.Collections.Generic;
using UltimaOnline;
using UltimaOnline.Network;
using UltimaOnline.Gumps;
namespace UltimaOnline.Misc
{
public static partial class Assistants
{
private static class Settings
{
public const bool Enabled = false;
public const bool KickOnFailure = true; // It will also kick clients running without assistants
public static readonly TimeSpan HandshakeTimeout = TimeSpan.FromSeconds(30.0);
public static readonly TimeSpan DisconnectDelay = TimeSpan.FromSeconds(15.0);
public const string WarningMessage = "The server was unable to negotiate features with your assistant. "
+ "You must download and run an updated version of <A HREF=\"http://uosteam.com\">UOSteam</A>"
+ " or <A HREF=\"https://bitbucket.org/msturgill/razor-releases/downloads\">Razor</A>."
+ "<BR><BR>Make sure you've checked the option <B>Negotiate features with server</B>, "
+ "once you have this box checked you may log in and play normally."
+ "<BR><BR>You will be disconnected shortly.";
public static void Configure()
{
//DisallowFeature( Features.FilterWeather );
}
[Flags]
public enum Features : ulong
{
None = 0,
FilterWeather = 1 << 0, // Weather Filter
FilterLight = 1 << 1, // Light Filter
SmartTarget = 1 << 2, // Smart Last Target
RangedTarget = 1 << 3, // Range Check Last Target
AutoOpenDoors = 1 << 4, // Automatically Open Doors
DequipOnCast = 1 << 5, // Unequip Weapon on spell cast
AutoPotionEquip = 1 << 6, // Un/re-equip weapon on potion use
PoisonedChecks = 1 << 7, // Block heal If poisoned/Macro If Poisoned condition/Heal or Cure self
LoopedMacros = 1 << 8, // Disallow looping or recursive macros
UseOnceAgent = 1 << 9, // The use once agent
RestockAgent = 1 << 10, // The restock agent
SellAgent = 1 << 11, // The sell agent
BuyAgent = 1 << 12, // The buy agent
PotionHotkeys = 1 << 13, // All potion hotkeys
RandomTargets = 1 << 14, // All random target hotkeys (not target next, last target, target self)
ClosestTargets = 1 << 15, // All closest target hotkeys
OverheadHealth = 1 << 16, // Health and Mana/Stam messages shown over player's heads
AutolootAgent = 1 << 17, // The autoloot agent
BoneCutterAgent = 1 << 18, // The bone cutter agent
AdvancedMacros = 1 << 19, // Advanced macro engine
AutoRemount = 1 << 20, // Auto remount after dismount
AutoBandage = 1 << 21, // Auto bandage friends, self, last and mount option
EnemyTargetShare = 1 << 22, // Enemy target share on guild, party or alliance chat
FilterSeason = 1 << 23, // Season Filter
SpellTargetShare = 1 << 24, // Spell target share on guild, party or alliance chat
All = ulong.MaxValue
}
private static Features m_DisallowedFeatures = Features.None;
public static void DisallowFeature(Features feature)
{
SetDisallowed(feature, true);
}
public static void AllowFeature(Features feature)
{
SetDisallowed(feature, false);
}
public static void SetDisallowed(Features feature, bool value)
{
if (value)
m_DisallowedFeatures |= feature;
else
m_DisallowedFeatures &= ~feature;
}
public static Features DisallowedFeatures { get { return m_DisallowedFeatures; } }
}
private static class Negotiator
{
private static Dictionary<Mobile, Timer> m_Dictionary = new Dictionary<Mobile, Timer>();
private static TimerStateCallback OnHandshakeTimeout_Callback = new TimerStateCallback(OnHandshakeTimeout);
private static TimerStateCallback OnForceDisconnect_Callback = new TimerStateCallback(OnForceDisconnect);
public static void Initialize()
{
if (Settings.Enabled)
{
EventSink.Login += new LoginEventHandler(EventSink_Login);
ProtocolExtensions.Register(0xFF, true, new OnPacketReceive(OnHandshakeResponse));
}
}
private static void EventSink_Login(LoginEventArgs e)
{
Mobile m = e.Mobile;
if (m != null && m.NetState != null && m.NetState.Running)
{
Timer t;
m.Send(new BeginHandshake());
if (Settings.KickOnFailure)
m.Send(new BeginHandshake());
if (m_Dictionary.TryGetValue(m, out t) && t != null)
t.Stop();
m_Dictionary[m] = t = Timer.DelayCall(Settings.HandshakeTimeout, OnHandshakeTimeout_Callback, m);
t.Start();
}
}
private static void OnHandshakeResponse(NetState state, PacketReader pvSrc)
{
pvSrc.Trace(state);
if (state == null || state.Mobile == null || !state.Running)
return;
Timer t;
Mobile m = state.Mobile;
if (m_Dictionary.TryGetValue(m, out t))
{
if (t != null)
t.Stop();
m_Dictionary.Remove(m);
}
}
private static void OnHandshakeTimeout(object state)
{
Timer t = null;
Mobile m = state as Mobile;
if (m == null)
return;
m_Dictionary.Remove(m);
if (!Settings.KickOnFailure)
{
Console.WriteLine("Player '{0}' failed to negotiate features.", m);
}
else if (m.NetState != null && m.NetState.Running)
{
m.SendGump(new Gumps.WarningGump(1060635, 30720, Settings.WarningMessage, 0xFFC000, 420, 250, null, null));
if (m.AccessLevel <= AccessLevel.Player)
{
m_Dictionary[m] = t = Timer.DelayCall(Settings.DisconnectDelay, OnForceDisconnect_Callback, m);
t.Start();
}
}
}
private static void OnForceDisconnect(object state)
{
if (state is Mobile)
{
Mobile m = (Mobile)state;
if (m.NetState != null && m.NetState.Running)
m.NetState.Dispose();
m_Dictionary.Remove(m);
Console.WriteLine("Player {0} kicked (Failed assistant handshake)", m);
}
}
private sealed class BeginHandshake : ProtocolExtension
{
public BeginHandshake()
: base(0xFE, 8)
{
Stream.Write((uint)((ulong)Settings.DisallowedFeatures >> 32));
Stream.Write((uint)((ulong)Settings.DisallowedFeatures & 0xFFFFFFFF));
}
}
}
}
} | 41.174359 | 128 | 0.501432 | [
"MIT"
] | netcode-gamer/game.ultimaonline.io | UltimaOnline.Data/Misc/Assistants.cs | 8,029 | C# |
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ThScoreFileConverter.Models.Th165;
using ThScoreFileConverterTests.Extensions;
using ThScoreFileConverterTests.Models.Th10.Wrappers;
using ThScoreFileConverterTests.Models.Th165.Stubs;
using ThScoreFileConverterTests.Models.Wrappers;
namespace ThScoreFileConverterTests.Models
{
[TestClass]
public class Th165StatusTests
{
internal static StatusStub ValidStub { get; } = new StatusStub()
{
Signature = "ST",
Version = 2,
Checksum = 0u,
Size = 0x224,
LastName = TestUtils.CP932Encoding.GetBytes("Player1\0\0\0\0\0\0\0"),
BgmFlags = TestUtils.MakeRandomArray<byte>(8),
TotalPlayTime = 12345678,
NicknameFlags = TestUtils.MakeRandomArray<byte>(51)
};
internal static byte[] MakeData(IStatus status)
=> TestUtils.MakeByteArray(
status.LastName,
new byte[0x12],
status.BgmFlags,
new byte[0x18],
status.TotalPlayTime,
new byte[0x4C],
status.NicknameFlags,
new byte[0x155]);
internal static byte[] MakeByteArray(IStatus status)
=> TestUtils.MakeByteArray(
status.Signature.ToCharArray(),
status.Version,
status.Checksum,
status.Size,
MakeData(status));
internal static void Validate(IStatus expected, in Th165StatusWrapper actual)
{
var data = MakeData(expected);
Assert.AreEqual(expected.Signature, actual.Signature);
Assert.AreEqual(expected.Version, actual.Version);
Assert.AreEqual(expected.Checksum, actual.Checksum);
Assert.AreEqual(expected.Size, actual.Size);
CollectionAssert.That.AreEqual(data, actual.Data);
CollectionAssert.That.AreEqual(expected.LastName, actual.LastName);
CollectionAssert.That.AreEqual(expected.BgmFlags, actual.BgmFlags);
Assert.AreEqual(expected.TotalPlayTime, actual.TotalPlayTime);
CollectionAssert.That.AreEqual(expected.NicknameFlags, actual.NicknameFlags);
}
[TestMethod]
public void Th165StatusTestChapter() => TestUtils.Wrap(() =>
{
var stub = ValidStub;
var chapter = ChapterWrapper.Create(MakeByteArray(stub));
var status = new Th165StatusWrapper(chapter);
Validate(stub, status);
Assert.IsFalse(status.IsValid.Value);
});
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Th165StatusTestNullChapter() => TestUtils.Wrap(() =>
{
_ = new Th165StatusWrapper(null);
Assert.Fail(TestUtils.Unreachable);
});
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")]
[TestMethod]
[ExpectedException(typeof(InvalidDataException))]
public void Th165StatusTestInvalidSignature() => TestUtils.Wrap(() =>
{
var stub = new StatusStub(ValidStub);
stub.Signature = stub.Signature.ToLowerInvariant();
var chapter = ChapterWrapper.Create(MakeByteArray(stub));
_ = new Th165StatusWrapper(chapter);
Assert.Fail(TestUtils.Unreachable);
});
[TestMethod]
[ExpectedException(typeof(InvalidDataException))]
public void Th165StatusTestInvalidVersion() => TestUtils.Wrap(() =>
{
var stub = new StatusStub(ValidStub);
++stub.Version;
var chapter = ChapterWrapper.Create(MakeByteArray(stub));
_ = new Th165StatusWrapper(chapter);
Assert.Fail(TestUtils.Unreachable);
});
[TestMethod]
[ExpectedException(typeof(InvalidDataException))]
public void Th165StatusTestInvalidSize() => TestUtils.Wrap(() =>
{
var stub = new StatusStub(ValidStub);
--stub.Size;
var chapter = ChapterWrapper.Create(MakeByteArray(stub));
_ = new Th165StatusWrapper(chapter);
Assert.Fail(TestUtils.Unreachable);
});
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
[DataTestMethod]
[DataRow("ST", (ushort)2, 0x224, true)]
[DataRow("st", (ushort)2, 0x224, false)]
[DataRow("ST", (ushort)1, 0x224, false)]
[DataRow("ST", (ushort)2, 0x225, false)]
public void Th165StatusCanInitializeTest(string signature, ushort version, int size, bool expected)
=> TestUtils.Wrap(() =>
{
var checksum = 0u;
var data = new byte[size];
var chapter = ChapterWrapper.Create(
TestUtils.MakeByteArray(signature.ToCharArray(), version, checksum, size, data));
Assert.AreEqual(expected, Th165StatusWrapper.CanInitialize(chapter));
});
}
}
| 36.521127 | 107 | 0.609526 | [
"BSD-2-Clause"
] | fossabot/ThScoreFileConverter | ThScoreFileConverterTests/Models/Th165StatusTests.cs | 5,188 | C# |
// Copyright (c) 2020-2021 Eli Aloni (a.k.a elix22)
// Copyright (c) 2008-2021 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using UrhoNetSamples;
using Urho;
using Urho.Physics;
using Urho.Gui;
using Urho.Network;
using Urho.Resources;
using System.Collections.Generic;
using System;
namespace SceneReplication
{
public class SceneReplication : Sample
{
protected Network Network;
Camera camera;
const short ServerPort = 2345;
UIElement buttonContainer;
/// Server address / chat message line editor element.
LineEdit textEdit;
/// Connect button.
Button connectButton;
/// Disconnect button.
Button disconnectButton;
/// Start server button.
Button startServerButton;
uint clientObjectID_;
StringHash E_CLIENTOBJECTID = new StringHash("ClientObjectID");
StringHash P_ID = new StringHash("ID");
const uint CTRL_FORWARD = 1;
const uint CTRL_BACK = 2;
const uint CTRL_LEFT = 4;
const uint CTRL_RIGHT = 8;
Dictionary<Connection, Node> serverObjects_ = new Dictionary<Connection, Node>();
[Preserve]
public SceneReplication() : base(new ApplicationOptions(assetsFolder: "Data;CoreData")) { }
protected override void Start()
{
base.Start();
Network = Application.Network;
Input.SetMouseVisible(true, false);
if (IsMobile)
{
RemoveScreenJoystick();
}
CreateUI();
CreateScene();
SimpleCreateInstructionsWithWasd("This is a demo of a simple client/server application\nSynchronizing a scene between connected devices\nEnter server IP bellow and press \"Connect\" \n To connect to a Wireless LAN Server \nOr press \"Start Server\" to Start WLAN server\n" +
"All devices including the server must be on the same Wireless LAN" +
"\nTo find out server IP type ifconfig/ipconfig \n From a command shell on the same device that runs the server" +
"\nTo find out server IP running on Android" + "\n go to Settings->WI-FI->Additional settings" +
"\nUsually WLAN server IP starts with 192.x.x.x", Color.Black);
SetupViewport();
SubscribeToEvents();
}
protected override void Stop()
{
UnSubscribeFromEvents();
HandleDisconnect(new ReleasedEventArgs());
base.Stop();
}
void CreateUI()
{
var graphics = Graphics;
UIElement root = UI.Root;
var cache = ResourceCache;
XmlFile uiStyle = cache.GetXmlFile("UI/DefaultStyle.xml");
// Set style to the UI root so that elements will inherit it
root.SetDefaultStyle(uiStyle);
Font font = cache.GetFont("Fonts/Anonymous Pro.ttf");
buttonContainer = new UIElement();
root.AddChild(buttonContainer);
buttonContainer.SetFixedSize(graphics.Width, 60);
buttonContainer.SetPosition(0, graphics.Height - 60);
buttonContainer.LayoutMode = LayoutMode.Horizontal;
textEdit = new LineEdit();
textEdit.SetStyleAuto(null);
textEdit.TextElement.SetFont(font, 24);
// TBD ELI , debug only
// textEdit.TextElement.Value = "192.168.1.110";
buttonContainer.AddChild(textEdit);
connectButton = CreateButtonLocal("Connect", 180);
disconnectButton = CreateButtonLocal("Disconnect", 200);
startServerButton = CreateButtonLocal("Start Server", 220);
UpdateButtons();
Input.SetMouseVisible(true);
}
void SubscribeToEvents()
{
//user event
SubscribeToEvent(E_CLIENTOBJECTID, HandleClientObjectID);
// Subscribe HandlePostUpdate() method for processing update events. Subscribe to PostUpdate instead
// of the usual Update so that physics simulation has already proceeded for the frame, and can
// accurately follow the object with the camera
Engine.PostUpdate += HandlePostUpdate;
scene.GetComponent<PhysicsWorld>().PhysicsPreStep += HandlePhysicsPreStep;
connectButton.Released += HandleConnect;
disconnectButton.Released += HandleDisconnect;
startServerButton.Released += HandleStartServer;
Network.ServerConnected += HandleServerConnected;
Network.ServerDisconnected += HandleServerDisconnected;
Network.ConnectFailed += HandleConnectFailed;
Network.ClientConnected += HandleClientConnected;
Network.ClientDisconnected += HandleClientDisconnected;
Network.RegisterRemoteEvent(E_CLIENTOBJECTID);
}
void UnSubscribeFromEvents()
{
UnSubscribeFromEvent(E_CLIENTOBJECTID);
Engine.PostUpdate -= HandlePostUpdate;
scene.GetComponent<PhysicsWorld>().PhysicsPreStep -= HandlePhysicsPreStep;
connectButton.Released -= HandleConnect;
disconnectButton.Released -= HandleDisconnect;
startServerButton.Released -= HandleStartServer;
Network.ServerConnected -= HandleServerConnected;
Network.ServerDisconnected -= HandleServerDisconnected;
Network.ConnectFailed -= HandleConnectFailed;
Network.ClientConnected -= HandleClientConnected;
Network.ClientDisconnected -= HandleClientDisconnected;
Network.UnregisterRemoteEvent(E_CLIENTOBJECTID);
}
private void HandleConnectFailed(ConnectFailedEventArgs obj)
{
UpdateButtons();
}
private void HandleStartServer(ReleasedEventArgs obj)
{
Network.StartServer((ushort)ServerPort);
UpdateButtons();
}
private void HandleDisconnect(ReleasedEventArgs obj)
{
var network = Network;
Connection serverConnection = network.ServerConnection;
// If we were connected to server, disconnect
if (serverConnection != null)
{
serverConnection.Disconnect();
scene.Clear(true, false);
clientObjectID_ = 0;
}
// Or if we were running a server, stop it
else if (network.ServerRunning)
{
network.StopServer();
scene.Clear(true, false);
}
UpdateButtons();
}
private void HandleConnect(ReleasedEventArgs obj)
{
string address = textEdit.Text.Trim();
if (string.IsNullOrEmpty(address))
address = "localhost"; // Use localhost to connect if nothing else specified
// Empty the text edit after reading the address to connect to
textEdit.Text = string.Empty;
// Connect to server, specify scene to use as a client for replication
clientObjectID_ = 0; // Reset own object ID from possible previous connection
Network.Connect(address, ServerPort, scene);
UpdateButtons();
}
void CreateScene()
{
scene = new Scene();
var cache = ResourceCache;
scene.CreateComponent<Octree>(CreateMode.Local);
scene.CreateComponent<PhysicsWorld>(CreateMode.Local);
var lightNode = scene.CreateChild("DirectionalLight", CreateMode.Local);
lightNode.SetDirection(new Vector3(0.6f, -1.0f, 0.8f)); // The direction vector does not need to be normalized
var light = lightNode.CreateComponent<Light>(CreateMode.Local);
light.LightType = LightType.Directional;
var skyNode = scene.CreateChild("Sky", CreateMode.Local);
skyNode.SetScale(500.0f); // The scale actually does not matter
var skybox = skyNode.CreateComponent<Skybox>(CreateMode.Local);
skybox.Model = ResourceCache.GetModel("Models/Box.mdl");
skybox.SetMaterial(ResourceCache.GetMaterial("Materials/Skybox.xml"));
// Create a "floor" consisting of several tiles. Make the tiles physical but leave small cracks between them
for (int y = -20; y <= 20; ++y)
{
for (int x = -20; x <= 20; ++x)
{
var floorNode = scene.CreateChild("FloorTile", CreateMode.Local);
floorNode.Position = new Vector3(x * 20.2f, -0.5f, y * 20.2f);
floorNode.Scale = new Vector3(20.0f, 1.0f, 20.0f);
var floorObject = floorNode.CreateComponent<StaticModel>(CreateMode.Local);
floorObject.Model = cache.GetModel("Models/Box.mdl");
floorObject.Material = cache.GetMaterial("Materials/Stone.xml");
var body = floorNode.CreateComponent<RigidBody>(CreateMode.Local);
body.Friction = 1.0f;
var shape = floorNode.CreateComponent<CollisionShape>(CreateMode.Local);
shape.SetBox(Vector3.One, Vector3.Zero, Quaternion.Identity);
}
}
CameraNode = scene.CreateChild("camera", CreateMode.Local);
camera = CameraNode.CreateComponent<Camera>(CreateMode.Local);
camera.FarClip = 300.0f;
CameraNode.Position = new Vector3(0, 5, 0);
}
void SetupViewport()
{
Renderer.SetViewport(0, new Viewport(Context, scene, camera, null));
}
void HandlePostUpdate(PostUpdateEventArgs arg)
{
MoveCamera(arg.TimeStep);
}
protected void MoveCamera(float timeStep, float moveSpeed = 10.0f)
{
const float mouseSensitivity = .1f;
if (UI.FocusElement != null)
return;
var mouseMove = Input.MouseMove;
if (Network.ServerRunning || Network.ServerConnection != null)
{
Yaw += mouseSensitivity * mouseMove.X;
Pitch += mouseSensitivity * mouseMove.Y;
Pitch = MathHelper.Clamp(Pitch, -90, 90);
CameraNode.Rotation = new Quaternion(Pitch, Yaw, 0);
}
if (clientObjectID_ != 0)
{
var ballNode = scene.GetNode(clientObjectID_);
if (ballNode != null)
{
const float CAMERA_DISTANCE = 5.0f;
// Move camera some distance away from the ball
CameraNode.Position = (ballNode.Position + CameraNode.Rotation * Vector3.Back * CAMERA_DISTANCE);
}
}
}
Button CreateButtonLocal(string text, int width)
{
var cache = ResourceCache;
Font font = cache.GetFont("Fonts/Anonymous Pro.ttf");
Button button = new Button();
buttonContainer.AddChild(button);
button.SetStyleAuto(null);
button.SetFixedHeight(60);
button.SetFixedWidth(width);
var buttonText = new Text();
button.AddChild(buttonText);
buttonText.SetFont(font, 24);
buttonText.SetAlignment(HorizontalAlignment.Center, VerticalAlignment.Center);
buttonText.Value = text;
return button;
}
Node CreateControllableObject()
{
var cache = ResourceCache;
// Create the scene node & visual representation. This will be a replicated object
var ballNode = scene.CreateChild("Ball");
ballNode.Position = new Vector3(NextRandom(40.0f) - 20.0f, 5.0f, NextRandom(40.0f) - 20.0f);
ballNode.Scale = new Vector3(0.5f, 0.5f, 0.5f);
var ballObject = ballNode.CreateComponent<StaticModel>();
ballObject.Model = cache.GetModel("Models/Sphere.mdl");
ballObject.Material = cache.GetMaterial("Materials/StoneSmall.xml");
// Create the physics components
var body = ballNode.CreateComponent<RigidBody>();
body.Mass = 1.0f;
body.Friction = 1.0f;
// In addition to friction, use motion damping so that the ball can not accelerate limitlessly
body.LinearDamping = 0.5f;
body.AngularDamping = 0.5f;
var shape = ballNode.CreateComponent<CollisionShape>();
shape.SetSphere(1.0f, Vector3.Zero, Quaternion.Identity);
// Create a random colored point light at the ball so that can see better where is going
var light = ballNode.CreateComponent<Light>();
light.Range = 3.0f;
light.Color =
new Color(0.5f + ((uint)NextRandom() & 1u) * 0.5f, 0.5f + ((uint)NextRandom() & 1u) * 0.5f, 0.5f + ((uint)NextRandom() & 1u) * 0.5f);
return ballNode;
}
void UpdateButtons()
{
var network = Network;
Connection serverConnection = network.ServerConnection;
bool serverRunning = network.ServerRunning;
if (IsMobile)
{
if (serverConnection != null)
{
CreateScreenJoystick();
}
else
{
RemoveScreenJoystick();
}
}
if (connectButton != null)
{
connectButton.Visible = serverConnection == null && !serverRunning;
}
if (disconnectButton != null)
{
disconnectButton.Visible = serverConnection != null || serverRunning;
}
if (startServerButton != null)
{
startServerButton.Visible = serverConnection == null && !serverRunning;
}
}
void HandleClientDisconnected(ClientDisconnectedEventArgs args)
{
// When a client disconnects, remove the controlled object
var connection = args.Connection;
Node obj;
if (serverObjects_.TryGetValue(connection, out obj))
{
if (obj != null)
obj.Remove();
}
serverObjects_.Remove(connection);
UpdateButtons();
}
void HandleClientConnected(ClientConnectedEventArgs args)
{
var newConnection = args.Connection;
newConnection.Scene = scene;
// Then create a controllable object for that client
var newObject = CreateControllableObject();
serverObjects_[newConnection] = newObject;
// Finally send the object's node ID using a remote event
DynamicMap remoteEventData = new DynamicMap();
remoteEventData[P_ID] = newObject.ID;
newConnection.SendRemoteEvent(E_CLIENTOBJECTID, true, remoteEventData);
UpdateButtons();
}
void HandleServerDisconnected(ServerDisconnectedEventArgs arg)
{
UpdateButtons();
}
void HandleServerConnected(ServerConnectedEventArgs args)
{
UpdateButtons();
}
void HandleClientObjectID(UrhoEventArgs args)
{
clientObjectID_ = args.EventData[P_ID];
}
/* This function is different on the client and server. The client collects controls (WASD controls + yaw angle)
and sets them to its server connection object, so that they will be sent to the server automatically at a
fixed rate, by default 30 FPS. The server will actually apply the controls (authoritative simulation.)*/
void HandlePhysicsPreStep(PhysicsPreStepEventArgs args)
{
var ui = UI;
var input = Input;
Controls controls = new Controls();
var network = Network;
Connection serverConnection = network.ServerConnection;
bool serverRunning = network.ServerRunning;
controls.Yaw = Yaw;
if (serverConnection != null) // Client: collect controls
{
if (IsMobile)
{
Vector2 axis_0 = GetJoystickAxisInput();
controls.Set(CTRL_FORWARD, axis_0.Y < -0.5);
controls.Set(CTRL_BACK, axis_0.Y > 0.5);
controls.Set(CTRL_LEFT, axis_0.X < -0.5);
controls.Set(CTRL_RIGHT, axis_0.X > 0.5);
}
if (!IsMobile && UI.FocusElement == null)
{
controls.Set(CTRL_FORWARD, input.GetKeyDown(Key.W));
controls.Set(CTRL_BACK, input.GetKeyDown(Key.S));
controls.Set(CTRL_LEFT, input.GetKeyDown(Key.A));
controls.Set(CTRL_RIGHT, input.GetKeyDown(Key.D));
}
serverConnection.Controls = controls;
// In case the server wants to do position-based interest management using the NetworkPriority components, we should also
// tell it our observer (camera) position. In this sample it is not in use, but eg. the NinjaSnowWar game uses it
serverConnection.Position = (CameraNode.Position);
}
else if (serverRunning) // Server: apply controls to client objects
{
var connections = network.GetClientConnections();
foreach (var connection in connections)
{
Node ballNode = serverObjects_[connection];
if (ballNode == null)
continue;
var body = ballNode.GetComponent<RigidBody>();
// Get the last controls sent by the client
controls = connection.Controls;
// Torque is relative to the forward vector
Quaternion rotation = new Quaternion(0.0f, controls.Yaw, 0.0f);
const float MOVE_TORQUE = 3.0f;
if ((controls.Buttons & CTRL_FORWARD) != 0)
body.ApplyTorque(rotation * Vector3.Right * MOVE_TORQUE);
if ((controls.Buttons & CTRL_BACK) != 0)
body.ApplyTorque(rotation * Vector3.Left * MOVE_TORQUE);
if ((controls.Buttons & CTRL_LEFT) != 0)
body.ApplyTorque(rotation * Vector3.Forward * MOVE_TORQUE);
if ((controls.Buttons & CTRL_RIGHT) != 0)
body.ApplyTorque(rotation * Vector3.Back * MOVE_TORQUE);
}
}
}
public Vector2 GetJoystickAxisInput()
{
Vector2 axis_0 = new Vector2();
JoystickState joystick;
if (screenJoystickIndex != -1 && Input.GetJoystick(screenJoystickIndex, out joystick))
{
axis_0 = new Vector2(joystick.GetAxisPosition(JoystickState.AxisLeft_X), joystick.GetAxisPosition(JoystickState.AxisLeft_Y));
}
return axis_0;
}
}
} | 36.992767 | 287 | 0.585081 | [
"MIT"
] | Urho-Net/Samples | FeatureSamples/Source/SceneReplication/SceneReplication.cs | 20,457 | C# |
using System;
using System.Collections.Generic;
using CSharpWars.DtoModel;
using CSharpWars.Enums;
using CSharpWars.Scripting.Model;
using FluentAssertions;
using Xunit;
namespace CSharpWars.Tests.Scripting
{
public class VisionTests
{
[Fact]
public void Vision_Build_Should_Build_Correctly()
{
// Arrange
var arena = new ArenaDto { Width = 1, Height = 1 };
var bot = new BotDto { Id = Guid.NewGuid() };
var bots = new List<BotDto>(new[] { bot });
var botProperties = BotProperties.Build(bot, arena, bots);
// Act
var result = Vision.Build(botProperties);
// Assert
result.Should().NotBeNull();
result.Bots.Should().NotBeNull();
result.Bots.Should().HaveCount(0);
result.FriendlyBots.Should().NotBeNull();
result.FriendlyBots.Should().HaveCount(0);
result.EnemyBots.Should().NotBeNull();
result.EnemyBots.Should().HaveCount(0);
}
[Theory]
[InlineData(PossibleOrientations.North, 0, 0, "ME", "ME", 1, 1, 0)]
[InlineData(PossibleOrientations.North, 0, 0, "ME", "THEY", 1, 0, 1)]
[InlineData(PossibleOrientations.North, 1, 0, "ME", "ME", 1, 1, 0)]
[InlineData(PossibleOrientations.North, 1, 0, "ME", "THEY", 1, 0, 1)]
[InlineData(PossibleOrientations.North, 2, 0, "ME", "ME", 1, 1, 0)]
[InlineData(PossibleOrientations.North, 2, 0, "ME", "THEY", 1, 0, 1)]
[InlineData(PossibleOrientations.North, 0, 1, "ME", "ME", 0, 0, 0)]
[InlineData(PossibleOrientations.North, 0, 1, "ME", "THEY", 0, 0, 0)]
[InlineData(PossibleOrientations.North, 2, 1, "ME", "ME", 0, 0, 0)]
[InlineData(PossibleOrientations.North, 2, 1, "ME", "THEY", 0, 0, 0)]
[InlineData(PossibleOrientations.North, 0, 2, "ME", "ME", 0, 0, 0)]
[InlineData(PossibleOrientations.North, 0, 2, "ME", "THEY", 0, 0, 0)]
[InlineData(PossibleOrientations.North, 1, 2, "ME", "ME", 0, 0, 0)]
[InlineData(PossibleOrientations.North, 1, 2, "ME", "THEY", 0, 0, 0)]
[InlineData(PossibleOrientations.North, 2, 2, "ME", "ME", 0, 0, 0)]
[InlineData(PossibleOrientations.North, 2, 2, "ME", "THEY", 0, 0, 0)]
[InlineData(PossibleOrientations.East, 0, 0, "ME", "ME", 0, 0, 0)]
[InlineData(PossibleOrientations.East, 0, 0, "ME", "THEY", 0, 0, 0)]
[InlineData(PossibleOrientations.East, 1, 0, "ME", "ME", 0, 0, 0)]
[InlineData(PossibleOrientations.East, 1, 0, "ME", "THEY", 0, 0, 0)]
[InlineData(PossibleOrientations.East, 2, 0, "ME", "ME", 1, 1, 0)]
[InlineData(PossibleOrientations.East, 2, 0, "ME", "THEY", 1, 0, 1)]
[InlineData(PossibleOrientations.East, 0, 1, "ME", "ME", 0, 0, 0)]
[InlineData(PossibleOrientations.East, 0, 1, "ME", "THEY", 0, 0, 0)]
[InlineData(PossibleOrientations.East, 2, 1, "ME", "ME", 1, 1, 0)]
[InlineData(PossibleOrientations.East, 2, 1, "ME", "THEY", 1, 0, 1)]
[InlineData(PossibleOrientations.East, 0, 2, "ME", "ME", 0, 0, 0)]
[InlineData(PossibleOrientations.East, 0, 2, "ME", "THEY", 0, 0, 0)]
[InlineData(PossibleOrientations.East, 1, 2, "ME", "ME", 0, 0, 0)]
[InlineData(PossibleOrientations.East, 1, 2, "ME", "THEY", 0, 0, 0)]
[InlineData(PossibleOrientations.East, 2, 2, "ME", "ME", 1, 1, 0)]
[InlineData(PossibleOrientations.East, 2, 2, "ME", "THEY", 1, 0, 1)]
[InlineData(PossibleOrientations.South, 0, 0, "ME", "ME", 0, 0, 0)]
[InlineData(PossibleOrientations.South, 0, 0, "ME", "THEY", 0, 0, 0)]
[InlineData(PossibleOrientations.South, 1, 0, "ME", "ME", 0, 0, 0)]
[InlineData(PossibleOrientations.South, 1, 0, "ME", "THEY", 0, 0, 0)]
[InlineData(PossibleOrientations.South, 2, 0, "ME", "ME", 0, 0, 0)]
[InlineData(PossibleOrientations.South, 2, 0, "ME", "THEY", 0, 0, 0)]
[InlineData(PossibleOrientations.South, 0, 1, "ME", "ME", 0, 0, 0)]
[InlineData(PossibleOrientations.South, 0, 1, "ME", "THEY", 0, 0, 0)]
[InlineData(PossibleOrientations.South, 2, 1, "ME", "ME", 0, 0, 0)]
[InlineData(PossibleOrientations.South, 2, 1, "ME", "THEY", 0, 0, 0)]
[InlineData(PossibleOrientations.South, 0, 2, "ME", "ME", 1, 1, 0)]
[InlineData(PossibleOrientations.South, 0, 2, "ME", "THEY", 1, 0, 1)]
[InlineData(PossibleOrientations.South, 1, 2, "ME", "ME", 1, 1, 0)]
[InlineData(PossibleOrientations.South, 1, 2, "ME", "THEY", 1, 0, 1)]
[InlineData(PossibleOrientations.South, 2, 2, "ME", "ME", 1, 1, 0)]
[InlineData(PossibleOrientations.South, 2, 2, "ME", "THEY", 1, 0, 1)]
[InlineData(PossibleOrientations.West, 0, 0, "ME", "ME", 1, 1, 0)]
[InlineData(PossibleOrientations.West, 0, 0, "ME", "THEY", 1, 0, 1)]
[InlineData(PossibleOrientations.West, 1, 0, "ME", "ME", 0, 0, 0)]
[InlineData(PossibleOrientations.West, 1, 0, "ME", "THEY", 0, 0, 0)]
[InlineData(PossibleOrientations.West, 2, 0, "ME", "ME", 0, 0, 0)]
[InlineData(PossibleOrientations.West, 2, 0, "ME", "THEY", 0, 0, 0)]
[InlineData(PossibleOrientations.West, 0, 1, "ME", "ME", 1, 1, 0)]
[InlineData(PossibleOrientations.West, 0, 1, "ME", "THEY", 1, 0, 1)]
[InlineData(PossibleOrientations.West, 2, 1, "ME", "ME", 0, 0, 0)]
[InlineData(PossibleOrientations.West, 2, 1, "ME", "THEY", 0, 0, 0)]
[InlineData(PossibleOrientations.West, 0, 2, "ME", "ME", 1, 1, 0)]
[InlineData(PossibleOrientations.West, 0, 2, "ME", "THEY", 1, 0, 1)]
[InlineData(PossibleOrientations.West, 1, 2, "ME", "ME", 0, 0, 0)]
[InlineData(PossibleOrientations.West, 1, 2, "ME", "THEY", 0, 0, 0)]
[InlineData(PossibleOrientations.West, 2, 2, "ME", "ME", 0, 0, 0)]
[InlineData(PossibleOrientations.West, 2, 2, "ME", "THEY", 0, 0, 0)]
public void Vision_Build_Should_Identify_Bots_Correctly(
PossibleOrientations orientation, int x, int y, string playerName, string botName, int expectedBots, int expectedFriendlies, int expectedEnemies)
{
// Arrange
var arena = new ArenaDto { Width = 3, Height = 3 };
var playerBot = new BotDto { Id = Guid.NewGuid(), X = 1, Y = 1, PlayerName = playerName, Orientation = orientation };
var otherBot = new BotDto { Id = Guid.NewGuid(), X = x, Y = y, PlayerName = botName };
var bots = new List<BotDto>(new[] { playerBot, otherBot });
var botProperties = BotProperties.Build(playerBot, arena, bots);
// Act
var result = Vision.Build(botProperties);
// Assert
result.Should().NotBeNull();
result.Bots.Should().NotBeNull();
result.Bots.Should().HaveCount(expectedBots);
result.FriendlyBots.Should().NotBeNull();
result.FriendlyBots.Should().HaveCount(expectedFriendlies);
result.EnemyBots.Should().NotBeNull();
result.EnemyBots.Should().HaveCount(expectedEnemies);
}
}
} | 58.276423 | 157 | 0.586775 | [
"Unlicense"
] | Djohnnie/BuildCloudNativeApplicationsWithDotNet5-DotNetDeveloperDays-2020 | csharpwars/backend/CSharpWars/CSharpWars.Tests/Scripting/VisionTests.cs | 7,170 | C# |
using System;
namespace PipeDriveApi.Models
{
public class Note : BaseEntity
{
public int Id { get; set; }
public int? DealId { get; set; }
public int? PersonId { get; set; }
public int? OrgId { get; set; }
public string Content { get; set; }
public DateTime? AddTime { get; set; }
public DateTime? UpdateTime { get; set; }
public bool ActiveFlag { get; set; }
public bool PinnedToDeal { get; set; }
public bool PinnedToPerson { get; set; }
public bool PinnedToOrganization { get; set; }
public int? LastUpdateUserId { get; set; }
}
}
| 30.714286 | 54 | 0.584496 | [
"MIT"
] | r8zr/PipeDriveApi | Source/PipeDriveApi/PipeDriveApi/Models/Note.cs | 647 | 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("IComparableInterface.Console")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IComparableInterface.Console")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[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("b0cb9394-31ab-4c26-a1e9-2abbcaf5b4b2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.486486 | 84 | 0.752107 | [
"Apache-2.0"
] | gokceozel/IComparableInterface | IComparableInterface.Console/IComparableInterface.Console/Properties/AssemblyInfo.cs | 1,427 | C# |
using System.IO;
using System.Runtime.Serialization;
using WolvenKit.CR2W.Reflection;
using FastMember;
using static WolvenKit.CR2W.Types.Enums;
namespace WolvenKit.CR2W.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class CAIHarpyCombatLogic : CAIFlyingMonsterCombatLogic
{
public CAIHarpyCombatLogic(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CAIHarpyCombatLogic(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | 30.826087 | 131 | 0.747532 | [
"MIT"
] | DerinHalil/CP77Tools | CP77.CR2W/Types/W3/RTTIConvert/CAIHarpyCombatLogic.cs | 687 | C# |
namespace AlgoSdk.Formatters
{
public sealed class SignatureTypeFormatter : KeywordByteEnumFormatter<SignatureType>
{
public SignatureTypeFormatter() : base(SignatureTypeExtensions.TypeToString) { }
}
}
| 27.875 | 88 | 0.757848 | [
"MIT"
] | CareBoo/Algorand.SDK.Unity | Packages/com.careboo.unity-algorand-sdk/CareBoo.AlgoSdk/Serialization/Formatters/Enum/SignatureTypeFormatter.cs | 223 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Module1.Services
{
public interface ISmsSender
{
Task SendSmsAsync(string number, string message);
}
}
| 17.846154 | 57 | 0.732759 | [
"MIT"
] | sorskoot/WebHackingCourse | Module1/Module1/Module1/Services/ISmsSender.cs | 234 | C# |
using System;
using System.Collections.Generic;
namespace LocalFunctions
{
class Program
{
static void Main(string[] args)
{
void ForEach<T>(IEnumerable<T> source, Action<T> action)
{
foreach (var item in source)
{
action?.Invoke(item);
}
}
var list = new[] { "First", "Second", "Third", "Forth", "Fifth" };
ForEach(list, Console.WriteLine);
Console.ReadKey();
}
}
}
| 22.75 | 78 | 0.470696 | [
"MIT"
] | compilyator/CSharp7 | LocalFunctions/LocalFunctions.cs | 548 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the keyspaces-2022-02-10.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Keyspaces.Model
{
/// <summary>
/// Represents the properties of a keyspace.
/// </summary>
public partial class KeyspaceSummary
{
private string _keyspaceName;
private string _resourceArn;
/// <summary>
/// Gets and sets the property KeyspaceName.
/// <para>
/// The name of the keyspace.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=48)]
public string KeyspaceName
{
get { return this._keyspaceName; }
set { this._keyspaceName = value; }
}
// Check to see if KeyspaceName property is set
internal bool IsSetKeyspaceName()
{
return this._keyspaceName != null;
}
/// <summary>
/// Gets and sets the property ResourceArn.
/// <para>
/// The unique identifier of the keyspace in the format of an Amazon Resource Name (ARN).
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=20, Max=1000)]
public string ResourceArn
{
get { return this._resourceArn; }
set { this._resourceArn = value; }
}
// Check to see if ResourceArn property is set
internal bool IsSetResourceArn()
{
return this._resourceArn != null;
}
}
} | 29.230769 | 107 | 0.620614 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/Keyspaces/Generated/Model/KeyspaceSummary.cs | 2,280 | C# |
using System;
using System.Text.RegularExpressions;
using FluentValidation;
using Kesco.Persons.BusinessLogic;
using Kesco.Persons.ObjectModel;
using Kesco.Web.Mvc.Validation;
namespace Kesco.Persons.Web.Models.Requisites
{
public class RequisitesValidator : ObjectValidator<Requisites>
{
public RequisitesValidator()
{
//RuleFor(r => r.From).Cascade(CascadeMode.StopOnFirstFailure)
// .Must(DatesAreValid)
// .WithMessage( Kesco.Persons.Web.Localization.Resources
// .Validation_Requisites_DateRange_must_be_valid);
RuleFor(r => r.ShortNameRus).Cascade(CascadeMode.StopOnFirstFailure)
.Must(OneOfTheShortNamesIsProvided)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Validation_Requisites_SomeShortNames_must_be_specified)
.Must(ShortNameRusIsValid)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Validation_Requisites_ShortNameRus_must_be_correct)
.Length(0, 200)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Models_JuridicalPersonCard_ShortNameRus_Name)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Validation_String_LengthExceeded);
RuleFor(r => r.ShortNameLat).Cascade(CascadeMode.StopOnFirstFailure)
.Length(0, 200)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Models_JuridicalPersonCard_ShortNameLat_Name)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Validation_String_LengthExceeded)
.Must(StringHasOnlyLatinChars)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Models_JuridicalPersonCard_ShortNameLat_Name)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Validation_StringField_OnlyLatinChars)
;
RuleFor(r => r.FullName).Cascade(CascadeMode.StopOnFirstFailure)
.Must(FullNameIsValid)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Validation_Requisites_FullName_is_invalid)
.Length(0, 300)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Models_JuridicalPersonCard_FullName_Name)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Validation_String_LengthExceeded);
RuleFor(r => r.OKONH).Cascade(CascadeMode.StopOnFirstFailure)
.Length(0, 5)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Models_JuridicalPersonCard_OKONH_Name)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Validation_String_LengthExceeded);
RuleFor(r => r.OKVED).Cascade(CascadeMode.StopOnFirstFailure)
.Length(0, 8)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Models_JuridicalPersonCard_OKVED_Name)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Validation_String_LengthExceeded);
RuleFor(r => r.KPP).Cascade(CascadeMode.StopOnFirstFailure)
.Length(0, 20)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Models_JuridicalPersonCard_KPP_Name)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Validation_String_LengthExceeded);
RuleFor(r => r.RwID).Cascade(CascadeMode.StopOnFirstFailure)
.Length(0, 35)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Models_JuridicalPersonCard_RwID_Name)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Validation_String_LengthExceeded);
RuleFor(r => r.AddressLegal).Cascade(CascadeMode.StopOnFirstFailure)
.Length(0, 300)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Models_JuridicalPersonCard_AddressLegal_Name)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Validation_String_LengthExceeded)
;
RuleFor(r => r.AddressLegalLat).Cascade(CascadeMode.StopOnFirstFailure)
.Length(0, 300)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Models_JuridicalPersonCard_AddressLegalLat_Name)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Validation_String_LengthExceeded)
.Must(StringHasOnlyLatinChars)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Models_JuridicalPersonCard_AddressLegalLat_Name)
.WithMessage( Kesco.Persons.Web.Localization.Resources
.Validation_StringField_OnlyLatinChars)
;
}
protected bool DatesAreValid(Requisites instance, DateTime? from)
{
if (!instance.From.HasValue) return true;
if (!instance.To.HasValue) return true;
return instance.From.Value <= instance.To.Value;
}
protected bool OneOfTheShortNamesIsProvided(Requisites instance, string shortName)
{
string rus = instance.ShortNameRus ?? String.Empty;
string lat = instance.ShortNameLat ?? String.Empty;
if (String.IsNullOrWhiteSpace(rus) && String.IsNullOrWhiteSpace(lat))
return false;
return true;
}
protected bool ShortNameRusIsValid(Requisites instance, string shortName)
{
if (String.IsNullOrWhiteSpace(shortName)) return true;
return !shortName.Contains("...");
}
protected bool FullNameIsValid(Requisites instance, string fullName)
{
if (!instance.IncorporationFormID.HasValue) return true;
if (String.IsNullOrWhiteSpace(fullName)) return false;
//IncorporationForm form = Repository.IncorporationForms.GetInstance(
// instance.IncorporationFormID.Value);
//if (form != null) {
// return fullName.StartsWith(form.Name);
//}
return true;
}
}
} | 38.085106 | 84 | 0.758473 | [
"MIT"
] | Kesco-m/Kesco.App.Web.MVC.Persons | Kesco.Persons.Web/Models/Requisites/RequisitesValidator.cs | 5,372 | C# |
//===================================================================================
// Microsoft patterns & practices
// Composite Application Guidance for Windows Presentation Foundation and Silverlight
//===================================================================================
// Copyright (c) Microsoft Corporation. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===================================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious. No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===================================================================================
using System;
namespace Microsoft.Practices.Prism.Regions
{
/// <summary>
/// Provides navigation for regions.
/// </summary>
public interface IRegionNavigationService : INavigateAsync
{
/// <summary>
/// Gets or sets the region owning this service.
/// </summary>
/// <value>A Region.</value>
IRegion Region { get; set; }
/// <summary>
/// Gets the journal.
/// </summary>
/// <value>The journal.</value>
IRegionNavigationJournal Journal { get; }
/// <summary>
/// Raised when the region is about to be navigated to content.
/// </summary>
event EventHandler<RegionNavigationEventArgs> Navigating;
/// <summary>
/// Raised when the region is navigated to content.
/// </summary>
event EventHandler<RegionNavigationEventArgs> Navigated;
/// <summary>
/// Raised when a navigation request fails.
/// </summary>
event EventHandler<RegionNavigationFailedEventArgs> NavigationFailed;
}
}
| 40.962963 | 86 | 0.54566 | [
"MIT"
] | cointoss1973/Prism4.1-WPF | PrismLibrary/Desktop/Prism/Regions/IRegionNavigationService.cs | 2,212 | C# |
namespace DataStore.Models
{
using System;
public class DatabaseException : Exception
{
public DatabaseException()
{
}
public DatabaseException(string message)
: base(message)
{
}
public DatabaseException(string message, Exception innerException)
: base(message, innerException)
{
}
}
} | 19.095238 | 74 | 0.563591 | [
"MIT-feh"
] | anavarro9731/datastore | src/DataStore.Models/DatabaseException.cs | 401 | C# |
using System.Web.Mvc;
using JetBrains.Annotations;
namespace JoinRpg.Web.Areas.Admin
{
[UsedImplicitly]
public class AdminAreaRegistration : AreaRegistration
{
public override string AreaName => "Admin";
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new {action = "Index", id = UrlParameter.Optional}
);
}
}
} | 23.3 | 70 | 0.671674 | [
"MIT"
] | FulcrumVlsM/joinrpg-net | Joinrpg/Areas/Admin/AdminAreaRegistration.cs | 468 | C# |
namespace Sapher.Persistence.TypeAdapters
{
using Model = Persistence.Model;
internal static class ResponseResultStateAdapterExtensions
{
internal static Model.ResponseResultState ToDataModel(this Dtos.ResponseResultState responseResultState)
{
switch (responseResultState)
{
case Dtos.ResponseResultState.None:
return Model.ResponseResultState.None;
case Dtos.ResponseResultState.Successful:
return Model.ResponseResultState.Successful;
case Dtos.ResponseResultState.Failed:
return Model.ResponseResultState.Failed;
case Dtos.ResponseResultState.Compensated:
return Model.ResponseResultState.Compensated;
default:
return Model.ResponseResultState.None;
}
}
internal static Dtos.ResponseResultState ToDto(this Model.ResponseResultState responseResultState)
{
switch (responseResultState)
{
case Model.ResponseResultState.None:
return Dtos.ResponseResultState.None;
case Model.ResponseResultState.Successful:
return Dtos.ResponseResultState.Successful;
case Model.ResponseResultState.Failed:
return Dtos.ResponseResultState.Failed;
case Model.ResponseResultState.Compensated:
return Dtos.ResponseResultState.Compensated;
default:
return Dtos.ResponseResultState.None;
}
}
}
} | 34.306122 | 112 | 0.603212 | [
"MIT"
] | joaodiasneves/sapher | src/sapher/Persistence/TypeAdapters/ResponseResultStateAdapterExtensions.cs | 1,683 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace CommandAPI.Migrations
{
public partial class AddApplicationUserFirst : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropPrimaryKey(
name: "PK_command",
table: "command");
migrationBuilder.AddPrimaryKey(
name: "pk_command",
table: "command",
column: "id");
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
id = table.Column<string>(type: "text", nullable: false),
name = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
normalized_name = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
concurrency_stamp = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("pk_asp_net_roles", x => x.id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
id = table.Column<string>(type: "text", nullable: false),
address = table.Column<string>(type: "text", nullable: true),
user_name = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
normalized_user_name = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
email = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
normalized_email = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
email_confirmed = table.Column<bool>(type: "boolean", nullable: false),
password_hash = table.Column<string>(type: "text", nullable: true),
security_stamp = table.Column<string>(type: "text", nullable: true),
concurrency_stamp = table.Column<string>(type: "text", nullable: true),
phone_number = table.Column<string>(type: "text", nullable: true),
phone_number_confirmed = table.Column<bool>(type: "boolean", nullable: false),
two_factor_enabled = table.Column<bool>(type: "boolean", nullable: false),
lockout_end = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
lockout_enabled = table.Column<bool>(type: "boolean", nullable: false),
access_failed_count = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("pk_asp_net_users", x => x.id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
role_id = table.Column<string>(type: "text", nullable: false),
claim_type = table.Column<string>(type: "text", nullable: true),
claim_value = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("pk_asp_net_role_claims", x => x.id);
table.ForeignKey(
name: "fk_asp_net_role_claims_asp_net_roles_role_id",
column: x => x.role_id,
principalTable: "AspNetRoles",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
user_id = table.Column<string>(type: "text", nullable: false),
claim_type = table.Column<string>(type: "text", nullable: true),
claim_value = table.Column<string>(type: "text", nullable: true),
application_user_id = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("pk_asp_net_user_claims", x => x.id);
table.ForeignKey(
name: "fk_asp_net_user_claims_asp_net_users_application_user_id",
column: x => x.application_user_id,
principalTable: "AspNetUsers",
principalColumn: "id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "fk_asp_net_user_claims_asp_net_users_user_id",
column: x => x.user_id,
principalTable: "AspNetUsers",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
login_provider = table.Column<string>(type: "text", nullable: false),
provider_key = table.Column<string>(type: "text", nullable: false),
provider_display_name = table.Column<string>(type: "text", nullable: true),
user_id = table.Column<string>(type: "text", nullable: false),
application_user_id = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("pk_asp_net_user_logins", x => new { x.login_provider, x.provider_key });
table.ForeignKey(
name: "fk_asp_net_user_logins_asp_net_users_application_user_id",
column: x => x.application_user_id,
principalTable: "AspNetUsers",
principalColumn: "id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "fk_asp_net_user_logins_asp_net_users_user_id",
column: x => x.user_id,
principalTable: "AspNetUsers",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
user_id = table.Column<string>(type: "text", nullable: false),
role_id = table.Column<string>(type: "text", nullable: false),
application_user_id = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("pk_asp_net_user_roles", x => new { x.user_id, x.role_id });
table.ForeignKey(
name: "fk_asp_net_user_roles_asp_net_roles_role_id",
column: x => x.role_id,
principalTable: "AspNetRoles",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_asp_net_user_roles_asp_net_users_application_user_id",
column: x => x.application_user_id,
principalTable: "AspNetUsers",
principalColumn: "id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "fk_asp_net_user_roles_asp_net_users_user_id",
column: x => x.user_id,
principalTable: "AspNetUsers",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
user_id = table.Column<string>(type: "text", nullable: false),
login_provider = table.Column<string>(type: "text", nullable: false),
name = table.Column<string>(type: "text", nullable: false),
value = table.Column<string>(type: "text", nullable: true),
application_user_id = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("pk_asp_net_user_tokens", x => new { x.user_id, x.login_provider, x.name });
table.ForeignKey(
name: "fk_asp_net_user_tokens_asp_net_users_application_user_id",
column: x => x.application_user_id,
principalTable: "AspNetUsers",
principalColumn: "id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "fk_asp_net_user_tokens_asp_net_users_user_id",
column: x => x.user_id,
principalTable: "AspNetUsers",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.InsertData(
table: "AspNetRoles",
columns: new[] { "id", "concurrency_stamp", "name", "normalized_name" },
values: new object[] { "308660dc-ae51-480f-824d-7dca6714c3e2", "2c5cfe17-2358-4dab-9483-f8e87bea230e", "Admin", "ADMIN" });
migrationBuilder.InsertData(
table: "AspNetUsers",
columns: new[] { "id", "access_failed_count", "address", "concurrency_stamp", "email", "email_confirmed", "lockout_enabled", "lockout_end", "normalized_email", "normalized_user_name", "password_hash", "phone_number", "phone_number_confirmed", "security_stamp", "two_factor_enabled", "user_name" },
values: new object[] { "e7497add-5127-4ef2-858d-5f77371ef554", 0, null, "65ed04d8-a57b-48b8-b310-6c496f7ffd7e", "admin@admin.com", true, false, null, "ADMIN@ADMIN.COM", "ADMIN@ADMIN.COM", "AQAAAAEAACcQAAAAEHcGuuxM+KtU/yOAl/YhUDxS1e7gHzy9Yjw4uTFIXFn/aDaSEy9ZDsSHGm+Ve/nx7A==", "123456789", false, "636894b9-4982-4c21-9573-26dfd73a9077", false, "admin@admin.com" });
migrationBuilder.InsertData(
table: "AspNetUserRoles",
columns: new[] { "role_id", "user_id", "application_user_id" },
values: new object[] { "308660dc-ae51-480f-824d-7dca6714c3e2", "e7497add-5127-4ef2-858d-5f77371ef554", null });
migrationBuilder.CreateIndex(
name: "ix_asp_net_role_claims_role_id",
table: "AspNetRoleClaims",
column: "role_id");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "normalized_name",
unique: true);
migrationBuilder.CreateIndex(
name: "ix_asp_net_user_claims_application_user_id",
table: "AspNetUserClaims",
column: "application_user_id");
migrationBuilder.CreateIndex(
name: "ix_asp_net_user_claims_user_id",
table: "AspNetUserClaims",
column: "user_id");
migrationBuilder.CreateIndex(
name: "ix_asp_net_user_logins_application_user_id",
table: "AspNetUserLogins",
column: "application_user_id");
migrationBuilder.CreateIndex(
name: "ix_asp_net_user_logins_user_id",
table: "AspNetUserLogins",
column: "user_id");
migrationBuilder.CreateIndex(
name: "ix_asp_net_user_roles_application_user_id",
table: "AspNetUserRoles",
column: "application_user_id");
migrationBuilder.CreateIndex(
name: "ix_asp_net_user_roles_role_id",
table: "AspNetUserRoles",
column: "role_id");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "normalized_email");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "normalized_user_name",
unique: true);
migrationBuilder.CreateIndex(
name: "ix_asp_net_user_tokens_application_user_id",
table: "AspNetUserTokens",
column: "application_user_id");
}
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");
migrationBuilder.DropPrimaryKey(
name: "pk_command",
table: "command");
migrationBuilder.AddPrimaryKey(
name: "PK_command",
table: "command",
column: "id");
}
}
}
| 48.910299 | 380 | 0.528325 | [
"MIT"
] | startdusk/CommandAPISolution | src/CommandAPI/Migrations/20211107030926_AddApplicationUserFirst.cs | 14,724 | C# |
using ExampleFunctionAppProject;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using Unify.AzureFunctionAppTools;
using Unify.AzureFunctionAppTools.ExceptionHandling;
using Unify.AzureFunctionAppTools.Preprocessing;
namespace ExampleFunctionApp.UnitTests
{
/// <summary>
/// Tests related to <see cref="GetUserRequestContextFactory"/>.
/// Note: Example code is not not exaustivly tested by this test fixture.
/// </summary>
[TestFixture]
public class GetUserContextFactoryTestFixture
{
/// <summary>
/// Test: Query parameters are correctly validated.
/// </summary>
[Test]
public void ValidQueryParamsValidationTest()
{
var contextFactory = new GetUserRequestContextFactory(
Mock.Of<IUnhandledErrorFactory>(),
Mock.Of<RequestPreprocessorCollection<GetUserRequestContextFactory>>());
IDictionary<string, string[]> testParams = new Dictionary<string, string[]>
{
[FunctionConstants.UserIdParamName] = new[] { Guid.NewGuid().ToString() }
};
RequestValidationResult result = contextFactory.ValidateQueryParameters(testParams);
Assert.AreEqual(result.Status, RequestValidationStatus.Passed);
}
/// <summary>
/// Test: User id query parameter fails validation when it is provided as an invalid format.
/// </summary>
[Test]
[TestCase("notAGuid", TestName = "InvalidUserIdQueryParamValidationTest_NotAGuid")]
[TestCase("", TestName = "InvalidUserIdQueryParamValidationTest_EmptyString")]
[TestCase(null, TestName = "InvalidUserIdQueryParamValidationTest_Null")]
public void InvalidUserIdQueryParamValidationTest(string invalidValue)
{
var contextFactory = new GetUserRequestContextFactory(
Mock.Of<IUnhandledErrorFactory>(),
Mock.Of<RequestPreprocessorCollection<GetUserRequestContextFactory>>());
IDictionary<string, string[]> testParams = new Dictionary<string, string[]>
{
[FunctionConstants.UserIdParamName] = new[] { invalidValue }
};
RequestValidationResult result = contextFactory.ValidateQueryParameters(testParams);
Assert.AreEqual(result.Status, RequestValidationStatus.Failed);
}
}
} | 39.370968 | 100 | 0.670217 | [
"MIT"
] | UNIFYSolutions/Unify.AzureFunctionAppTools | Example/ExampleFunctionApp.UnitTests/GetUserContextFactoryTestFixture.cs | 2,441 | C# |
/*******************************************************************************
IMPORTANT NOTE - This file was contributed by one of our users. While the rest of
Cubiquity is distributed free for non-commercial use, the contents of this file
are under the more liberal zlib license. Please see the copyright notice below.
********************************************************************************
Copyright (c) 2013 Ian Joseph Fischer and David Williams
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*******************************************************************************/
using UnityEngine;
namespace Cubiquity
{
[System.Serializable]
/// A three-dimensional vector type with integer components.
/**
* This class is commonly used for representing positions of voxels inside volumes.
*/
public struct Vector3i
{
/// The 'x' component of the vector.
public int x;
/// The 'y' component of the vector.
public int y;
/// The 'z' component of the vector.
public int z;
/// A vector with all components set to zero.
public static readonly Vector3i zero = new Vector3i(0, 0, 0);
/// A vector with all components set to one.
public static readonly Vector3i one = new Vector3i(1, 1, 1);
/// A unit vector pointing along the positive z axis.
public static readonly Vector3i forward = new Vector3i(0, 0, 1);
/// A unit vector pointing along the negative z axis.
public static readonly Vector3i back = new Vector3i(0, 0, -1);
/// A unit vector pointing along the positive y axis.
public static readonly Vector3i up = new Vector3i(0, 1, 0);
/// A unit vector pointing along the negative y axis.
public static readonly Vector3i down = new Vector3i(0, -1, 0);
/// A unit vector pointing along the negative x axis.
public static readonly Vector3i left = new Vector3i(-1, 0, 0);
/// A unit vector pointing along the positive x axis.
public static readonly Vector3i right = new Vector3i(1, 0, 0);
/// Constructs a vector from the supplied components.
public Vector3i(int x, int y, int z)
{
this.x = x;
this.y = y;
this.z = z;
}
/// Constructs a vector from the supplied components (z is set to zero).
public Vector3i(int x, int y)
{
this.x = x;
this.y = y;
this.z = 0;
}
/// Constructs a vector by copying the supplied vector.
public Vector3i(Vector3i a)
{
this.x = a.x;
this.y = a.y;
this.z = a.z;
}
/// Constructs a vector by copying the supplied vector and casting the components to ints.
public Vector3i(Vector3 a)
{
this.x = (int)a.x;
this.y = (int)a.y;
this.z = (int)a.z;
}
/// Accesses the component at the specified index.
public int this[int key]
{
get
{
switch(key)
{
case 0:
{
return x;
}
case 1:
{
return y;
}
case 2:
{
return z;
}
default:
{
Debug.LogError("Invalid Vector3i index value of: " + key);
return 0;
}
}
}
set
{
switch(key)
{
case 0:
{
x = value;
return;
}
case 1:
{
y = value;
return;
}
case 2:
{
z = value;
return;
}
default:
{
Debug.LogError("Invalid Vector3i index value of: " + key);
return;
}
}
}
}
/// Scales 'a' by 'b' and returns the result.
public static Vector3i Scale(Vector3i a, Vector3i b)
{
return new Vector3i(a.x * b.x, a.y * b.y, a.z * b.z);
}
/// Computes the distance between two positions.
public static float Distance(Vector3i a, Vector3i b)
{
return Mathf.Sqrt(DistanceSquared(a, b));
}
/// Computes the squared distance between two positions.
public static int DistanceSquared(Vector3i a, Vector3i b)
{
int dx = b.x - a.x;
int dy = b.y - a.y;
int dz = b.z - a.z;
return dx * dx + dy * dy + dz * dz;
}
/// A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a hash table.
public override int GetHashCode()
{
// Microsoft use XOR in their example here: http://msdn.microsoft.com/en-us/library/ms173147.aspx
// We also use shifting, as the compoents are typically small and this should reduce collisions.
return x ^ (y << 8) ^ (z << 16);
}
/// Determines whether the specified System.Object is equal to the current Cubiquity.Vector3i.
public override bool Equals(object other)
{
if(!(other is Vector3i))
{
return false;
}
Vector3i vector = (Vector3i)other;
return x == vector.x &&
y == vector.y &&
z == vector.z;
}
/// Returns a System.String that represents the current Cubiquity.Vector3i.
public override string ToString()
{
return string.Format("Vector3i({0} {1} {2})", x, y, z);
}
/// Determines whether a specified instance of Vector3i is equal to another specified Vector3i.
public static bool operator ==(Vector3i a, Vector3i b)
{
return a.x == b.x &&
a.y == b.y &&
a.z == b.z;
}
/// Determines whether a specified instance of Vector3i is not equal to another specified Vector3i.
public static bool operator !=(Vector3i a, Vector3i b)
{
return a.x != b.x ||
a.y != b.y ||
a.z != b.z;
}
/// Component-wise subtraction of one vector from another, returning a new vector as the result.
public static Vector3i operator -(Vector3i a, Vector3i b)
{
return new Vector3i(a.x - b.x, a.y - b.y, a.z - b.z);
}
/// Component-wise addition of one vector to another, returning a new vector as the result.
public static Vector3i operator +(Vector3i a, Vector3i b)
{
return new Vector3i(a.x + b.x, a.y + b.y, a.z + b.z);
}
/// Component-wise multiplication of one vector with another, returning a new vector as the result.
public static Vector3i operator *(Vector3i a, int d)
{
return new Vector3i(a.x * d, a.y * d, a.z * d);
}
/// Component-wise division of one vector with another, returning a new vector as the result.
public static Vector3i operator *(int d, Vector3i a)
{
return new Vector3i(a.x * d, a.y * d, a.z * d);
}
/// Cast a Vector3i to Unity's Vector3 type.
public static explicit operator Vector3(Vector3i v)
{
return new Vector3(v.x, v.y, v.z);
}
/// Cast Unity's Vector3 type to a Vector3i
public static explicit operator Vector3i(Vector3 v)
{
return new Vector3i(v);
}
/// Component-wise minimum of one vector and another, returning a new vector as the result.
public static Vector3i Min(Vector3i lhs, Vector3i rhs)
{
return new Vector3i(Mathf.Min(lhs.x, rhs.x), Mathf.Min(lhs.y, rhs.y), Mathf.Min(lhs.z, rhs.z));
}
/// Component-wise maximum of one vector and another, returning a new vector as the result.
public static Vector3i Max(Vector3i lhs, Vector3i rhs)
{
return new Vector3i(Mathf.Max(lhs.x, rhs.x), Mathf.Max(lhs.y, rhs.y), Mathf.Max(lhs.z, rhs.z));
}
/// Component-wise clamping of one vector and another, returning a new vector as the result.
public static Vector3i Clamp(Vector3i value, Vector3i min, Vector3i max)
{
return new Vector3i(Mathf.Clamp(value.x, min.x, max.x), Mathf.Clamp(value.y, min.y, max.y), Mathf.Clamp(value.z, min.z, max.z));
}
}
}
| 30.05597 | 131 | 0.636375 | [
"MIT"
] | Rockswell/vxl-unity3d | Assets/Cubiquity/Scripts/Vector3i.cs | 8,055 | C# |
namespace WebApi.Models
{
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
}
}
| 17.555556 | 44 | 0.594937 | [
"MIT"
] | metiftikci/Proje-B | src/WebApi/Models/LoginModel.cs | 158 | C# |
namespace BC7.Business.Implementation.Payments.Commands.DonateViaAffiliateProgram
{
public class DonateViaAffiliateProgramViewModel
{
public string PaymentUrl { get; set; }
}
} | 28.142857 | 82 | 0.751269 | [
"MIT"
] | XardasLord/BitClub7 | BC7.Business.Implementation/Payments/Commands/DonateViaAffiliateProgram/DonateViaAffiliateProgramViewModel.cs | 199 | C# |
using System;
using Autodesk.DesignScript.Runtime;
using Autodesk.Revit.DB;
using tData = Autodesk.Revit.DB.TransmissionData;
using modelPath = Autodesk.Revit.DB.ModelPath;
namespace Synthetic.Revit
{
/// <summary>
/// Wrapper for Revit API TransmissionData
/// </summary>
public class TransmissionData
{
internal TransmissionData () { }
/// <summary>
/// Reads the TransmissionData from a file.
/// </summary>
/// <param name="FilePath">Path to the file.</param>
/// <returns name="TransmissionData">Revit TransmissionData</returns>
public static tData Read (string FilePath)
{
ModelPath mPath = Autodesk.Revit.DB.ModelPathUtils.ConvertUserVisiblePathToModelPath(FilePath);
return tData.ReadTransmissionData(mPath);
}
/// <summary>
/// Writes modified TransmissionData from a file. File must be closed to write TransmissionData.
/// </summary>
/// <param name="FilePath">Path to the file.</param>
/// <param name="transmissionData">A Revit TransmissionData object</param>
/// <returns name="FilePath">Returns the FilePath to the project.</returns>
public static string Write (string FilePath, tData transmissionData)
{
ModelPath mPath = Autodesk.Revit.DB.ModelPathUtils.ConvertUserVisiblePathToModelPath(FilePath);
tData.WriteTransmissionData(mPath, transmissionData);
return FilePath;
}
/// <summary>
/// Verifies whether the file is flagged as Transmitted or not.
/// </summary>
/// <param name="FilePath">Path to the file.</param>
/// <returns name="bool">Returns true if file is marked as Transmitted. False if is not transmitted.</returns>
public static bool IsTransmitted (string FilePath)
{
ModelPath mPath = Autodesk.Revit.DB.ModelPathUtils.ConvertUserVisiblePathToModelPath(FilePath);
tData td = tData.ReadTransmissionData(mPath);
return td.IsTransmitted;
}
/// <summary>
/// Set's the file to Transmitted or not.
/// </summary>
/// <param name="FilePath">Path to the file.</param>
/// <param name="IsTransmitted">True to flag the file as Transmitted.</param>
/// <returns name="FilePath">Returns the FilePath.</returns>
public static string SetIsTransmitted (string FilePath, bool IsTransmitted)
{
ModelPath mPath = Autodesk.Revit.DB.ModelPathUtils.ConvertUserVisiblePathToModelPath(FilePath);
tData td = tData.ReadTransmissionData(mPath);
if(td.IsTransmitted != IsTransmitted)
{
td.IsTransmitted = IsTransmitted;
tData.WriteTransmissionData(mPath, td);
}
return FilePath;
}
}
}
| 35.52439 | 119 | 0.630278 | [
"MIT"
] | amcgoey/Synthetic | 11.Synthetic Revit/TransmissionData.cs | 2,915 | C# |
using RX_Explorer.Interface;
using System;
using System.ComponentModel;
using System.Threading.Tasks;
using Windows.Storage;
namespace RX_Explorer.Class
{
public sealed class RecycleStorageFile : FileSystemStorageFile, IRecycleStorageItem
{
public string OriginPath { get; private set; }
public override string Name => System.IO.Path.GetFileName(OriginPath);
public override string DisplayName => Name;
public override string Type => ((StorageItem as StorageFile)?.FileType) ?? System.IO.Path.GetExtension(OriginPath).ToUpper();
public override string ModifiedTimeDescription
{
get
{
if (ModifiedTime == DateTimeOffset.FromFileTime(0))
{
return string.Empty;
}
else
{
return ModifiedTime.ToString("G");
}
}
}
public override Task DeleteAsync(bool PermanentDelete, ProgressChangedEventHandler ProgressHandler = null)
{
return DeleteAsync();
}
public RecycleStorageFile(StorageFile File, string OriginPath, DateTimeOffset DeleteTime) : base(File)
{
this.OriginPath = OriginPath;
ModifiedTime = DeleteTime.ToLocalTime();
}
public RecycleStorageFile(Win32_File_Data Data, string OriginPath, DateTimeOffset DeleteTime) : base(Data)
{
this.OriginPath = OriginPath;
ModifiedTime = DeleteTime.ToLocalTime();
}
public async Task<bool> DeleteAsync()
{
using (FullTrustProcessController.ExclusiveUsage Exclusive = await FullTrustProcessController.GetAvailableController())
{
return await Exclusive.Controller.DeleteItemInRecycleBinAsync(Path);
}
}
public async Task<bool> RestoreAsync()
{
using (FullTrustProcessController.ExclusiveUsage Exclusive = await FullTrustProcessController.GetAvailableController())
{
return await Exclusive.Controller.RestoreItemInRecycleBinAsync(OriginPath);
}
}
}
}
| 32.632353 | 133 | 0.617846 | [
"Apache-2.0"
] | crramirez/RX-Explorer | RX_Explorer/Class/RecycleStorageFile.cs | 2,221 | C# |
using System;
using Foundation;
using AppKit;
namespace Synthesia
{
public partial class MainWindow : NSWindow
{
public MainWindow(IntPtr handle) : base(handle) { }
[Export("initWithCoder:")]
public MainWindow(NSCoder coder) : base(coder) { }
public override void AwakeFromNib() { base.AwakeFromNib(); }
}
}
| 19.222222 | 66 | 0.66763 | [
"MIT"
] | Synthesia-LLC/metadata-editor | mac-gui/MainWindow.cs | 348 | C# |
using PingDong.Newmoon.Venues.DomainEvents;
using PingDong.Testings;
using Xunit;
namespace PingDong.Newmoon.Venues
{
public class VenueRegisteredDomainEventTest
{
[Fact]
public void ConstructorAssignedProperties()
{
var tester = new DtoClassTester<VenueRegisteredDomainEvent>();
Assert.True(tester.VerifyPropertiesAssignedFromConstructor());
}
}
}
| 24 | 74 | 0.671296 | [
"MIT"
] | pingdong/newmoon.places | src/Venues.Core.UnitTests/Domain Events/VenueRegisterdDomainEventTest.cs | 434 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Lasm.UAlive
{
public static partial class HUMAssets
{
public static partial class Data
{
public struct GameObjectIs
{
public GameObject gameObject;
public GameObjectIs(GameObject gameObject)
{
this.gameObject = gameObject;
}
}
public struct ComponentListTo<T> where T : MonoBehaviour
{
public IEnumerable<T> components;
public ComponentListTo(IEnumerable<T> components)
{
this.components = components;
}
}
public struct Find { }
public struct All
{
public Find find;
public All(Find find)
{
this.find = find;
}
}
public struct FindUsingType
{
public Type type;
public FindUsingType(Type type)
{
this.type = type;
}
}
public struct AssetsUsingType
{
public FindUsingType find;
public AssetsUsingType(FindUsingType find)
{
this.find = find;
}
}
public struct Assets
{
public Find find;
public Assets(Find find)
{
this.find = find;
}
}
public struct AssetsWith
{
public Assets assets;
public AssetsWith(Assets assets)
{
this.assets = assets;
}
}
public struct AssetsWithUsingType
{
public AssetsUsingType assets;
public AssetsWithUsingType(AssetsUsingType assets)
{
this.assets = assets;
}
}
public struct PrefabsUsingType
{
public FindUsingType find;
public PrefabsUsingType(FindUsingType find)
{
this.find = find;
}
}
public struct Prefabs
{
public Find find;
public Prefabs(Find find)
{
this.find = find;
}
}
public struct BehavioursUsingType
{
public FindUsingType find;
public BehavioursUsingType(FindUsingType find)
{
this.find = find;
}
}
public struct Behaviours
{
public Find find;
public Behaviours(Find find)
{
this.find = find;
}
}
}
}
} | 23.410448 | 68 | 0.40102 | [
"MIT"
] | jrDev1/UAlive | Humility/Assets/HUMAssets_Data.cs | 3,139 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("IE.Utilities.Extensions")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("IE.Utilities.Extensions")]
[assembly: System.Reflection.AssemblyTitleAttribute("IE.Utilities.Extensions")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 42.541667 | 81 | 0.65524 | [
"MIT"
] | TheArchitect123/IE.Mobile.Forms | Utilities/Extensions/IE.Utilities/IE.Utilities.Extensions/obj/Release/netstandard2.0/IE.Utilities.Extensions.AssemblyInfo.cs | 1,021 | C# |
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.ServiceModel;
namespace Workday.HumanResources
{
[GeneratedCode("System.ServiceModel", "4.0.0.0"), EditorBrowsable(EditorBrowsableState.Advanced), DebuggerStepThrough, MessageContract(IsWrapped = false)]
public class Get_Location_AttributesInput
{
[MessageHeader(Namespace = "urn:com.workday/bsvc")]
public Workday_Common_HeaderType Workday_Common_Header;
[MessageBodyMember(Namespace = "urn:com.workday/bsvc", Order = 0)]
public Get_Location_Attributes_RequestType Get_Location_Attributes_Request;
public Get_Location_AttributesInput()
{
}
public Get_Location_AttributesInput(Workday_Common_HeaderType Workday_Common_Header, Get_Location_Attributes_RequestType Get_Location_Attributes_Request)
{
this.Workday_Common_Header = Workday_Common_Header;
this.Get_Location_Attributes_Request = Get_Location_Attributes_Request;
}
}
}
| 33.586207 | 155 | 0.827515 | [
"MIT"
] | matteofabbri/Workday.WebServices | Workday.HumanResources/Get_Location_AttributesInput.cs | 974 | C# |
using System;
using Examples;
namespace Examples {
public class Object1 {}
}
public class Example {
public static void Main() {
/* inserted */
int _7 = 27;
object obj1 = new Object1();
func(obj1);
}
public static void func(string s) {}
}
| 17.533333 | 38 | 0.634981 | [
"Apache-2.0"
] | thufv/DeepFix-C- | data/Mutation/CS1503_5_mutation_15/[E]CS1503.cs | 265 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("__Debugger")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("__Debugger")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("64671446-00ee-46f4-97ff-b96e3e2ee248")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.611111 | 84 | 0.740768 | [
"Apache-2.0",
"MIT"
] | Spool5520/ultraviolet | Source/UvDebug/Desktop/Properties/AssemblyInfo.cs | 1,357 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Windows.Forms {
using System.Windows.Forms.VisualStyles;
using System.Drawing;
using System.Drawing.Text;
using System.Windows.Forms.Internal;
using System.Drawing.Imaging;
using System.ComponentModel;
using System.Windows.Forms.Layout;
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer"]/*' />
public abstract class ToolStripRenderer {
private static readonly object EventRenderSplitButtonBackground = new object();
private static readonly object EventRenderItemBackground = new object();
private static readonly object EventRenderItemImage = new object();
private static readonly object EventRenderItemText = new object();
private static readonly object EventRenderToolStripBackground = new object();
private static readonly object EventRenderGrip = new object();
private static readonly object EventRenderButtonBackground = new object();
private static readonly object EventRenderLabelBackground = new object();
private static readonly object EventRenderMenuItemBackground = new object();
private static readonly object EventRenderDropDownButtonBackground = new object();
private static readonly object EventRenderOverflowButtonBackground = new object();
private static readonly object EventRenderImageMargin = new object();
private static readonly object EventRenderBorder = new object();
private static readonly object EventRenderArrow = new object();
private static readonly object EventRenderStatusStripPanelBackground = new object();
private static readonly object EventRenderToolStripStatusLabelBackground = new object();
private static readonly object EventRenderSeparator = new object();
private static readonly object EventRenderItemCheck = new object();
private static readonly object EventRenderToolStripPanelBackground = new object();
private static readonly object EventRenderToolStripContentPanelBackground = new object();
private static readonly object EventRenderStatusStripSizingGrip = new object();
private static ColorMatrix disabledImageColorMatrix;
private EventHandlerList events;
private bool isAutoGenerated = false;
private static bool isScalingInitialized = false;
// arrows are rendered as isosceles triangles, whose heights are half the base in order to have 45 degree angles
// Offset2X is half of the base
// Offset2Y is height of the isosceles triangle
private static int OFFSET_2PIXELS = 2;
private static int OFFSET_4PIXELS = 4;
protected static int Offset2X = OFFSET_2PIXELS;
protected static int Offset2Y = OFFSET_2PIXELS;
private static int offset4X = OFFSET_4PIXELS;
private static int offset4Y = OFFSET_4PIXELS;
// this is used in building up the half pyramid of rectangles that are drawn in a
// status strip sizing grip.
private static Rectangle[] baseSizeGripRectangles = new Rectangle[] { new Rectangle(8,0,2,2),
new Rectangle(8,4,2,2),
new Rectangle(8,8,2,2),
new Rectangle(4,4,2,2),
new Rectangle(4,8,2,2),
new Rectangle(0,8,2,2) };
protected ToolStripRenderer() {
}
internal ToolStripRenderer(bool isAutoGenerated) {
this.isAutoGenerated = isAutoGenerated;
}
// this is used in building disabled images.
private static ColorMatrix DisabledImageColorMatrix {
get {
if (disabledImageColorMatrix == null) {
// this is the result of a GreyScale matrix multiplied by a transparency matrix of .5
float[][] greyscale = new float[5][];
greyscale[0] = new float[5] {0.2125f, 0.2125f, 0.2125f, 0, 0};
greyscale[1] = new float[5] {0.2577f, 0.2577f, 0.2577f, 0, 0};
greyscale[2] = new float[5] {0.0361f, 0.0361f, 0.0361f, 0, 0};
greyscale[3] = new float[5] {0, 0, 0, 1, 0};
greyscale[4] = new float[5] {0.38f, 0.38f, 0.38f, 0, 1};
float[][] transparency = new float[5][];
transparency[0] = new float[5] {1, 0, 0, 0, 0};
transparency[1] = new float[5] {0, 1, 0, 0, 0};
transparency[2] = new float[5] {0, 0, 1, 0, 0};
transparency[3] = new float[5] {0, 0, 0, .7F, 0};
transparency[4] = new float[5] {0, 0, 0, 0, 0};
disabledImageColorMatrix = ControlPaint.MultiplyColorMatrix(transparency, greyscale);
}
return disabledImageColorMatrix;
}
}
/// <devdoc>
/// <para>Gets the list of event handlers that are attached to this component.</para>
/// </devdoc>
private EventHandlerList Events {
get {
if (events == null) {
events = new EventHandlerList();
}
return events;
}
}
internal bool IsAutoGenerated {
get { return isAutoGenerated; }
}
// if we're in a low contrast, high resolution situation, use this renderer under the covers instead.
internal virtual ToolStripRenderer RendererOverride {
get {
return null;
}
}
/// -----------------------------------------------------------------------------
///
/// <include file='doc\WinBarRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderArrow"]/*' />
public event ToolStripArrowRenderEventHandler RenderArrow {
add {
AddHandler(EventRenderArrow, value);
}
remove {
RemoveHandler(EventRenderArrow, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderToolStripBackground"]/*' />
/// <devdoc>
/// <para>Occurs when the display style has changed</para>
/// </devdoc>
public event ToolStripRenderEventHandler RenderToolStripBackground {
add {
AddHandler(EventRenderToolStripBackground, value);
}
remove {
RemoveHandler(EventRenderToolStripBackground, value);
}
}
public event ToolStripPanelRenderEventHandler RenderToolStripPanelBackground {
add {
AddHandler(EventRenderToolStripPanelBackground, value);
}
remove {
RemoveHandler(EventRenderToolStripPanelBackground, value);
}
}
public event ToolStripContentPanelRenderEventHandler RenderToolStripContentPanelBackground {
add {
AddHandler(EventRenderToolStripContentPanelBackground, value);
}
remove {
RemoveHandler(EventRenderToolStripContentPanelBackground, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderBorder"]/*' />
/// <devdoc>
/// <para>Occurs when the display style has changed</para>
/// </devdoc>
public event ToolStripRenderEventHandler RenderToolStripBorder {
add {
AddHandler(EventRenderBorder, value);
}
remove {
RemoveHandler(EventRenderBorder, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderButtonBackground"]/*' />
/// <devdoc>
/// <para>Occurs when the display style has changed</para>
/// </devdoc>
public event ToolStripItemRenderEventHandler RenderButtonBackground {
add {
AddHandler(EventRenderButtonBackground, value);
}
remove {
RemoveHandler(EventRenderButtonBackground, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderDropDownButtonBackground"]/*' />
/// <devdoc>
/// <para>Occurs when the display style has changed</para>
/// </devdoc>
public event ToolStripItemRenderEventHandler RenderDropDownButtonBackground {
add {
AddHandler(EventRenderDropDownButtonBackground, value);
}
remove {
RemoveHandler(EventRenderDropDownButtonBackground, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderOverflowButtonBackground"]/*' />
/// <devdoc>
/// <para>Occurs when the display style has changed</para>
/// </devdoc>
public event ToolStripItemRenderEventHandler RenderOverflowButtonBackground {
add {
AddHandler(EventRenderOverflowButtonBackground, value);
}
remove {
RemoveHandler(EventRenderOverflowButtonBackground, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderGrip"]/*' />
/// <devdoc>
/// <para>Occurs when the display style has changed</para>
/// </devdoc>
public event ToolStripGripRenderEventHandler RenderGrip {
add {
AddHandler(EventRenderGrip, value);
}
remove {
RemoveHandler(EventRenderGrip, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderItem"]/*' />
/// <devdoc>
/// <para>Occurs when the display style has changed</para>
/// </devdoc>
public event ToolStripItemRenderEventHandler RenderItemBackground {
add {
AddHandler(EventRenderItemBackground, value);
}
remove {
RemoveHandler(EventRenderItemBackground, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderItemImage"]/*' />
/// <devdoc>
/// Draws the split button
/// </devdoc>
public event ToolStripItemImageRenderEventHandler RenderItemImage {
add {
AddHandler(EventRenderItemImage, value);
}
remove {
RemoveHandler(EventRenderItemImage, value);
}
}
/// <include file='doc\WinBarRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderItemCheck"]/*' />
/// <devdoc>
/// Draws the checkmark
/// </devdoc>
public event ToolStripItemImageRenderEventHandler RenderItemCheck {
add {
AddHandler(EventRenderItemCheck, value);
}
remove {
RemoveHandler(EventRenderItemCheck, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderItemText"]/*' />
/// <devdoc>
/// Draws the split button
/// </devdoc>
public event ToolStripItemTextRenderEventHandler RenderItemText {
add {
AddHandler(EventRenderItemText, value);
}
remove {
RemoveHandler(EventRenderItemText, value);
}
}
public event ToolStripRenderEventHandler RenderImageMargin {
add {
AddHandler(EventRenderImageMargin, value);
}
remove {
RemoveHandler(EventRenderImageMargin, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderLabelBackground"]/*' />
/// <devdoc>
/// <para>Occurs when the display style has changed</para>
/// </devdoc>
public event ToolStripItemRenderEventHandler RenderLabelBackground {
add {
AddHandler(EventRenderLabelBackground, value);
}
remove {
RemoveHandler(EventRenderLabelBackground, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderMenuItemBackground"]/*' />
/// <devdoc>
/// <para>Occurs when the display style has changed</para>
/// </devdoc>
public event ToolStripItemRenderEventHandler RenderMenuItemBackground {
add {
AddHandler(EventRenderMenuItemBackground, value);
}
remove {
RemoveHandler(EventRenderMenuItemBackground, value);
}
}
/// <include file='doc\WinBarRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderStatusStripPanelBackground"]/*' />
/// <devdoc>
/// Draws the split button
/// </devdoc>
public event ToolStripItemRenderEventHandler RenderToolStripStatusLabelBackground {
add {
AddHandler(EventRenderToolStripStatusLabelBackground, value);
}
remove {
RemoveHandler(EventRenderToolStripStatusLabelBackground, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderToolStripBackground"]/*' />
/// <devdoc>
/// <para>Occurs when the display style has changed</para>
/// </devdoc>
public event ToolStripRenderEventHandler RenderStatusStripSizingGrip {
add {
AddHandler(EventRenderStatusStripSizingGrip, value);
}
remove {
RemoveHandler(EventRenderStatusStripSizingGrip, value);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderSplitButtonBackground"]/*' />
/// <devdoc>
/// Draws the split button
/// </devdoc>
public event ToolStripItemRenderEventHandler RenderSplitButtonBackground {
add {
AddHandler(EventRenderSplitButtonBackground, value);
}
remove {
RemoveHandler(EventRenderSplitButtonBackground, value);
}
}
/// <include file='doc\WinBarRenderer.uex' path='docs/doc[@for="ToolStripRenderer.RenderSeparator"]/*' />
public event ToolStripSeparatorRenderEventHandler RenderSeparator {
add {
AddHandler(EventRenderSeparator, value);
}
remove {
RemoveHandler(EventRenderSeparator, value);
}
}
#region EventHandlerSecurity
/// -----------------------------------------------------------------------------
///
private void AddHandler(object key, Delegate value) {
Events.AddHandler(key, value);
}
private void RemoveHandler(object key, Delegate value) {
Events.RemoveHandler(key, value);
}
#endregion
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.CreateDisabledImage"]/*' />
public static Image CreateDisabledImage(Image normalImage) {
return CreateDisabledImage(normalImage, null);
}
/// <include file='doc\WinBarRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawArrow"]/*' />
public void DrawArrow(ToolStripArrowRenderEventArgs e) {
OnRenderArrow(e);
ToolStripArrowRenderEventHandler eh = Events[EventRenderArrow] as ToolStripArrowRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawBackground"]/*' />
/// <devdoc>
/// Draw the background color
/// </devdoc>
public void DrawToolStripBackground(ToolStripRenderEventArgs e) {
OnRenderToolStripBackground(e);
ToolStripRenderEventHandler eh = Events[EventRenderToolStripBackground] as ToolStripRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawGrip"]/*' />
/// <devdoc>
/// Draw the background color
/// </devdoc>
public void DrawGrip(ToolStripGripRenderEventArgs e) {
OnRenderGrip(e);
ToolStripGripRenderEventHandler eh = Events[EventRenderGrip] as ToolStripGripRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawItem"]/*' />
/// <devdoc>
/// Draw the item's background.
/// </devdoc>
public void DrawItemBackground(ToolStripItemRenderEventArgs e)
{
OnRenderItemBackground(e);
ToolStripItemRenderEventHandler eh = Events[EventRenderItemBackground] as ToolStripItemRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawImageMargin"]/*' />
/// <devdoc>
/// Draw the background color
/// </devdoc>
public void DrawImageMargin(ToolStripRenderEventArgs e) {
OnRenderImageMargin(e);
ToolStripRenderEventHandler eh = Events[EventRenderImageMargin] as ToolStripRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawLabel"]/*' />
/// <devdoc>
/// Draw the background color
/// </devdoc>
public void DrawLabelBackground(ToolStripItemRenderEventArgs e)
{
OnRenderLabelBackground(e);
ToolStripItemRenderEventHandler eh = Events[EventRenderLabelBackground] as ToolStripItemRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawButton"]/*' />
/// <devdoc>
/// Draw the item's background.
/// </devdoc>
public void DrawButtonBackground(ToolStripItemRenderEventArgs e)
{
OnRenderButtonBackground(e);
ToolStripItemRenderEventHandler eh = Events[EventRenderButtonBackground] as ToolStripItemRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawBorder"]/*' />
public void DrawToolStripBorder(ToolStripRenderEventArgs e)
{
OnRenderToolStripBorder(e);
ToolStripRenderEventHandler eh = Events[EventRenderBorder] as ToolStripRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawDropDownButton"]/*' />
/// <devdoc>
/// Draw the item's background.
/// </devdoc>
public void DrawDropDownButtonBackground(ToolStripItemRenderEventArgs e)
{
OnRenderDropDownButtonBackground(e);
ToolStripItemRenderEventHandler eh = Events[EventRenderDropDownButtonBackground] as ToolStripItemRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawOverflowButton"]/*' />
/// <devdoc>
/// Draw the item's background.
/// </devdoc>
public void DrawOverflowButtonBackground(ToolStripItemRenderEventArgs e)
{
OnRenderOverflowButtonBackground(e);
ToolStripItemRenderEventHandler eh = Events[EventRenderOverflowButtonBackground] as ToolStripItemRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawItemImage"]/*' />
/// <devdoc>
/// Draw image
/// </devdoc>
public void DrawItemImage(ToolStripItemImageRenderEventArgs e) {
OnRenderItemImage(e);
ToolStripItemImageRenderEventHandler eh = Events[EventRenderItemImage] as ToolStripItemImageRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\WinBarRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawItemCheck"]/*' />
/// <devdoc>
/// Draw image
/// </devdoc>
public void DrawItemCheck(ToolStripItemImageRenderEventArgs e) {
OnRenderItemCheck(e);
ToolStripItemImageRenderEventHandler eh = Events[EventRenderItemCheck] as ToolStripItemImageRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawItemText"]/*' />
/// <devdoc>
/// Draw text
/// </devdoc>
public void DrawItemText(ToolStripItemTextRenderEventArgs e) {
OnRenderItemText(e);
ToolStripItemTextRenderEventHandler eh = Events[EventRenderItemText] as ToolStripItemTextRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawMenuItem"]/*' />
/// <devdoc>
/// Draw the item's background.
/// </devdoc>
public void DrawMenuItemBackground(ToolStripItemRenderEventArgs e)
{
OnRenderMenuItemBackground(e);
ToolStripItemRenderEventHandler eh = Events[EventRenderMenuItemBackground] as ToolStripItemRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawSplitButton"]/*' />
/// <devdoc>
/// Draw the background color
/// </devdoc>
public void DrawSplitButton(ToolStripItemRenderEventArgs e) {
OnRenderSplitButtonBackground(e);
ToolStripItemRenderEventHandler eh = Events[EventRenderSplitButtonBackground] as ToolStripItemRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\WinBarRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawToolStripStatusLabel"]/*' />
/// <devdoc>
/// Draw the background color
/// </devdoc>
public void DrawToolStripStatusLabelBackground(ToolStripItemRenderEventArgs e) {
OnRenderToolStripStatusLabelBackground(e);
ToolStripItemRenderEventHandler eh = Events[EventRenderToolStripStatusLabelBackground] as ToolStripItemRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
//
public void DrawStatusStripSizingGrip(ToolStripRenderEventArgs e) {
OnRenderStatusStripSizingGrip(e);
ToolStripRenderEventHandler eh = Events[EventRenderStatusStripSizingGrip] as ToolStripRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.DrawSeparator"]/*' />
/// <devdoc>
/// Draw the separator
/// </devdoc>
public void DrawSeparator(ToolStripSeparatorRenderEventArgs e) {
OnRenderSeparator(e);
ToolStripSeparatorRenderEventHandler eh = Events[EventRenderSeparator] as ToolStripSeparatorRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
public void DrawToolStripPanelBackground(ToolStripPanelRenderEventArgs e) {
OnRenderToolStripPanelBackground(e);
ToolStripPanelRenderEventHandler eh = Events[EventRenderToolStripPanelBackground] as ToolStripPanelRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
public void DrawToolStripContentPanelBackground(ToolStripContentPanelRenderEventArgs e) {
OnRenderToolStripContentPanelBackground(e);
ToolStripContentPanelRenderEventHandler eh = Events[EventRenderToolStripContentPanelBackground] as ToolStripContentPanelRenderEventHandler;
if (eh != null) {
eh(this, e);
}
}
// consider make public
internal virtual Region GetTransparentRegion(ToolStrip toolStrip) {
return null;
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.Initialize"]/*' />
protected internal virtual void Initialize(ToolStrip toolStrip){
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.Initialize"]/*' />
protected internal virtual void InitializePanel(ToolStripPanel toolStripPanel){
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.Initialize"]/*' />
protected internal virtual void InitializeContentPanel(ToolStripContentPanel contentPanel){
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.InitializeItem"]/*' />
protected internal virtual void InitializeItem (ToolStripItem item){
}
protected static void ScaleArrowOffsetsIfNeeded() {
if (isScalingInitialized) {
return;
}
if (DpiHelper.IsScalingRequired) {
Offset2X = DpiHelper.LogicalToDeviceUnitsX(OFFSET_2PIXELS);
Offset2Y = DpiHelper.LogicalToDeviceUnitsY(OFFSET_2PIXELS);
offset4X = DpiHelper.LogicalToDeviceUnitsX(OFFSET_4PIXELS);
offset4Y = DpiHelper.LogicalToDeviceUnitsY(OFFSET_4PIXELS);
}
isScalingInitialized = true;
}
/// <include file='doc\WinBarRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderArrow"]/*' />
protected virtual void OnRenderArrow(ToolStripArrowRenderEventArgs e){
if (RendererOverride != null) {
RendererOverride.OnRenderArrow(e);
return;
}
Graphics g = e.Graphics;
Rectangle dropDownRect = e.ArrowRectangle;
using (Brush brush = new SolidBrush(e.ArrowColor)) {
Point middle = new Point(dropDownRect.Left + dropDownRect.Width / 2, dropDownRect.Top + dropDownRect.Height / 2);
// if the width is odd - favor pushing it over one pixel right.
//middle.X += (dropDownRect.Width % 2);
Point[] arrow = null;
ScaleArrowOffsetsIfNeeded();
// using (offset4X - Offset2X) instead of (Offset2X) to compensate for rounding error in scaling
int horizontalOffset = DpiHelper.IsScalingRequirementMet ? offset4X - Offset2X : Offset2X;
switch (e.Direction) {
case ArrowDirection.Up:
arrow = new Point[] {
new Point(middle.X - Offset2X, middle.Y + 1),
new Point(middle.X + Offset2X + 1, middle.Y + 1),
new Point(middle.X, middle.Y - Offset2Y)};
break;
case ArrowDirection.Left:
arrow = new Point[] {
new Point(middle.X + Offset2X, middle.Y - offset4Y),
new Point(middle.X + Offset2X, middle.Y + offset4Y),
new Point(middle.X - horizontalOffset, middle.Y)};
break;
case ArrowDirection.Right:
arrow = new Point[] {
new Point(middle.X - Offset2X, middle.Y - offset4Y),
new Point(middle.X - Offset2X, middle.Y + offset4Y),
new Point(middle.X + horizontalOffset, middle.Y)};
break;
case ArrowDirection.Down:
default:
arrow = new Point[] {
new Point(middle.X - Offset2X, middle.Y - 1),
new Point(middle.X + Offset2X + 1, middle.Y - 1),
new Point(middle.X, middle.Y + Offset2Y) };
break;
}
g.FillPolygon(brush, arrow);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderToolStripBackground"]/*' />
/// <devdoc>
/// Draw the winbar background. ToolStrip users should override this if they want to draw differently.
/// </devdoc>
protected virtual void OnRenderToolStripBackground(ToolStripRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderToolStripBackground(e);
return;
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderBorder"]/*' />
/// <devdoc>
/// Draw the border around the ToolStrip. This should be done as the last step.
/// </devdoc>
protected virtual void OnRenderToolStripBorder(ToolStripRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderToolStripBorder(e);
return;
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderGrip"]/*' />
/// <devdoc>
/// Draw the grip. ToolStrip users should override this if they want to draw differently.
/// </devdoc>
protected virtual void OnRenderGrip(ToolStripGripRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderGrip(e);
return;
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderItem"]/*' />
/// <devdoc>
/// Draw the items background
/// </devdoc>
protected virtual void OnRenderItemBackground(ToolStripItemRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderItemBackground(e);
return;
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderImageMargin"]/*' />
/// <devdoc>
/// Draw the items background
/// </devdoc>
protected virtual void OnRenderImageMargin(ToolStripRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderImageMargin(e);
return;
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderButtonBackground"]/*' />
/// <devdoc>
/// Draw the button background
/// </devdoc>
protected virtual void OnRenderButtonBackground(ToolStripItemRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderButtonBackground(e);
return;
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderDropDownButtonBackground"]/*' />
/// <devdoc>
/// Draw the button background
/// </devdoc>
protected virtual void OnRenderDropDownButtonBackground(ToolStripItemRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderDropDownButtonBackground(e);
return;
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderOverflowButtonBackground"]/*' />
/// <devdoc>
/// Draw the button background
/// </devdoc>
protected virtual void OnRenderOverflowButtonBackground(ToolStripItemRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderOverflowButtonBackground(e);
return;
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderItemImage"]/*' />
/// <devdoc>
/// Draw the item'si mage. ToolStrip users should override this function to change the
/// drawing of all images.
/// </devdoc>
protected virtual void OnRenderItemImage(ToolStripItemImageRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderItemImage(e);
return;
}
Rectangle imageRect = e.ImageRectangle;
Image image = e.Image;
if (imageRect != Rectangle.Empty && image != null) {
bool disposeImage = false;
if (e.ShiftOnPress && e.Item.Pressed) {
imageRect.X +=1;
}
if (!e.Item.Enabled) {
image = CreateDisabledImage(image, e.ImageAttributes);
disposeImage = true;
}
if (e.Item.ImageScaling == ToolStripItemImageScaling.None) {
e.Graphics.DrawImage(image, imageRect, new Rectangle(Point.Empty,imageRect.Size), GraphicsUnit.Pixel);
}
else {
e.Graphics.DrawImage(image, imageRect);
}
if (disposeImage) {
image.Dispose();
}
}
}
/// <include file='doc\WinBarRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderItemCheck"]/*' />
protected virtual void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderItemCheck(e);
return;
}
Rectangle imageRect = e.ImageRectangle;
Image image = e.Image;
if (imageRect != Rectangle.Empty && image != null) {
if (!e.Item.Enabled) {
image = CreateDisabledImage(image, e.ImageAttributes);
}
e.Graphics.DrawImage(image, imageRect, 0, 0, imageRect.Width,
imageRect.Height, GraphicsUnit.Pixel, e.ImageAttributes);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderItemText"]/*' />
/// <devdoc>
/// Draw the item's text. ToolStrip users should override this function to change the
/// drawing of all text.
/// </devdoc>
protected virtual void OnRenderItemText(ToolStripItemTextRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderItemText(e);
return;
}
ToolStripItem item = e.Item;
Graphics g = e.Graphics;
Color textColor = e.TextColor;
Font textFont = e.TextFont;
string text = e.Text;
Rectangle textRect = e.TextRectangle;
TextFormatFlags textFormat = e.TextFormat;
// if we're disabled draw in a different color.
textColor = (item.Enabled) ? textColor : SystemColors.GrayText;
if (e.TextDirection != ToolStripTextDirection.Horizontal && textRect.Width > 0 && textRect.Height > 0) {
// Perf: this is a bit heavy handed.. perhaps we can share the bitmap.
Size textSize = LayoutUtils.FlipSize(textRect.Size);
using (Bitmap textBmp = new Bitmap(textSize.Width, textSize.Height,PixelFormat.Format32bppPArgb)) {
using (Graphics textGraphics = Graphics.FromImage(textBmp)) {
// now draw the text..
textGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
TextRenderer.DrawText(textGraphics, text, textFont, new Rectangle(Point.Empty, textSize), textColor, textFormat);
textBmp.RotateFlip((e.TextDirection == ToolStripTextDirection.Vertical90) ? RotateFlipType.Rotate90FlipNone : RotateFlipType.Rotate270FlipNone);
g.DrawImage(textBmp, textRect);
}
}
}
else {
TextRenderer.DrawText(g, text, textFont, textRect, textColor, textFormat);
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderLabelBackground"]/*' />
/// <devdoc>
/// Draw the button background
/// </devdoc>
protected virtual void OnRenderLabelBackground(ToolStripItemRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderLabelBackground(e);
return;
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderMenuItemBackground"]/*' />
/// <devdoc>
/// Draw the items background
/// </devdoc>
protected virtual void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderMenuItemBackground(e);
return;
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderSeparator"]/*' />
/// <devdoc>
/// Draws a toolbar separator. ToolStrip users should override this function to change the
/// drawing of all separators.
/// </devdoc>
protected virtual void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderSeparator(e);
return;
}
}
protected virtual void OnRenderToolStripPanelBackground(ToolStripPanelRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderToolStripPanelBackground(e);
return;
}
}
protected virtual void OnRenderToolStripContentPanelBackground(ToolStripContentPanelRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderToolStripContentPanelBackground(e);
return;
}
}
/// <include file='doc\WinBarRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderStatusStripPanelBackground"]/*' />
protected virtual void OnRenderToolStripStatusLabelBackground(ToolStripItemRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderToolStripStatusLabelBackground(e);
return;
}
}
protected virtual void OnRenderStatusStripSizingGrip(ToolStripRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderStatusStripSizingGrip(e);
return;
}
Graphics g = e.Graphics;
StatusStrip statusStrip = e.ToolStrip as StatusStrip;
// we have a set of stock rectangles. Translate them over to where the grip is to be drawn
// for the white set, then translate them up and right one pixel for the grey.
if (statusStrip != null) {
Rectangle sizeGripBounds = statusStrip.SizeGripBounds;
if (!LayoutUtils.IsZeroWidthOrHeight(sizeGripBounds)) {
Rectangle[] whiteRectangles = new Rectangle[baseSizeGripRectangles.Length];
Rectangle[] greyRectangles = new Rectangle[baseSizeGripRectangles.Length];
for (int i = 0; i < baseSizeGripRectangles.Length; i++) {
Rectangle baseRect = baseSizeGripRectangles[i];
if (statusStrip.RightToLeft == RightToLeft.Yes) {
baseRect.X = sizeGripBounds.Width - baseRect.X - baseRect.Width;
}
baseRect.Offset(sizeGripBounds.X, sizeGripBounds.Bottom - 12 /*height of pyramid (10px) + 2px padding from bottom*/);
whiteRectangles[i] = baseRect;
if (statusStrip.RightToLeft == RightToLeft.Yes) {
baseRect.Offset(1, -1);
}
else {
baseRect.Offset(-1, -1);
}
greyRectangles[i] = baseRect;
}
g.FillRectangles(SystemBrushes.ButtonHighlight, whiteRectangles);
g.FillRectangles(SystemBrushes.ButtonShadow, greyRectangles);
}
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderSplitButtonBackground"]/*' />
/// <devdoc>
/// Draw the item's background.
/// </devdoc>
protected virtual void OnRenderSplitButtonBackground(ToolStripItemRenderEventArgs e) {
if (RendererOverride != null) {
RendererOverride.OnRenderSplitButtonBackground(e);
return;
}
}
// Only paint background effects if no backcolor has been set or no background image has been set.
internal bool ShouldPaintBackground (Control control) {
return (control.RawBackColor == Color.Empty && control.BackgroundImage == null);
}
private static Image CreateDisabledImage(Image normalImage, ImageAttributes imgAttrib) {
if (imgAttrib == null) {
imgAttrib = new ImageAttributes();
}
imgAttrib.ClearColorKey();
imgAttrib.SetColorMatrix(DisabledImageColorMatrix);
Size size = normalImage.Size;
Bitmap disabledBitmap = new Bitmap(size.Width, size.Height);
using (Graphics graphics = Graphics.FromImage(disabledBitmap)) {
graphics.DrawImage(normalImage,
new Rectangle(0, 0, size.Width, size.Height),
0, 0, size.Width, size.Height,
GraphicsUnit.Pixel,
imgAttrib);
}
return disabledBitmap;
}
}
}
| 42.70775 | 169 | 0.556559 | [
"MIT"
] | kevingosse/winforms | src/System.Windows.Forms/src/System/Windows/Forms/ToolStripRenderer.cs | 45,740 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace LibreLancer.Shaders
{
using System;
public class DepthPass_AlphaTest
{
private static byte[] vertex_bytes = new byte[220] {
27, 178, 1, 0, 140, 212, 70, 117, 136, 91, 202, 17, 154, 52, 123, 216, 159, 249, 93, 73, 23, 191, 212, 164, 45, 207, 13, 162, 229, 14,
44, 224, 244, 73, 95, 173, 219, 146, 214, 75, 37, 45, 205, 194, 128, 210, 196, 210, 48, 160, 40, 192, 204, 93, 63, 74, 225, 97, 182, 205,
105, 73, 62, 194, 131, 113, 229, 160, 238, 244, 234, 209, 184, 219, 206, 171, 20, 64, 232, 131, 46, 62, 241, 181, 156, 251, 124, 45, 111, 143,
229, 103, 44, 33, 97, 167, 242, 160, 90, 63, 111, 75, 183, 226, 252, 124, 68, 211, 64, 161, 249, 249, 124, 91, 216, 61, 86, 119, 156, 62,
130, 79, 215, 15, 79, 195, 128, 137, 182, 94, 6, 83, 2, 22, 40, 149, 224, 133, 226, 116, 200, 79, 31, 225, 19, 248, 6, 229, 166, 226,
15, 97, 59, 185, 156, 239, 140, 169, 168, 74, 212, 44, 22, 149, 90, 158, 41, 136, 158, 6, 93, 203, 81, 67, 200, 250, 48, 62, 19, 113,
113, 53, 244, 1, 73, 100, 140, 110, 167, 64, 68, 1, 191, 90, 31, 234, 131, 12, 214, 199, 228, 72, 205, 63, 131, 210, 123, 215, 162, 73,
21, 236, 151, 255, 150, 55, 100, 225, 112, 0
};
private static byte[] fragment_bytes = new byte[166] {
27, 230, 0, 96, 140, 195, 56, 134, 60, 196, 141, 50, 60, 51, 104, 93, 125, 75, 154, 51, 154, 249, 234, 239, 42, 183, 66, 66, 218, 94,
203, 221, 252, 65, 30, 31, 136, 127, 255, 107, 171, 146, 168, 93, 150, 52, 47, 145, 20, 211, 183, 155, 253, 68, 121, 19, 92, 105, 203, 115,
171, 204, 14, 19, 151, 139, 164, 26, 138, 113, 181, 94, 214, 73, 94, 44, 8, 147, 243, 133, 69, 206, 207, 7, 94, 199, 189, 11, 45, 235,
102, 203, 179, 147, 143, 236, 241, 56, 126, 132, 207, 183, 131, 111, 80, 54, 172, 251, 102, 231, 200, 31, 75, 3, 30, 215, 183, 66, 62, 68,
201, 73, 53, 61, 20, 8, 128, 107, 63, 111, 71, 49, 229, 85, 171, 139, 228, 169, 137, 28, 232, 91, 248, 176, 116, 83, 194, 159, 212, 169,
196, 246, 118, 248, 122, 75, 66, 217, 17, 208, 116, 69, 235, 161, 13, 25
};
static ShaderVariables[] variants;
private static bool iscompiled = false;
private static int GetIndex(ShaderFeatures features)
{
ShaderFeatures masked = (features & ((ShaderFeatures)(0)));
return 0;
}
public static ShaderVariables Get(ShaderFeatures features)
{
return variants[GetIndex(features)];
}
public static ShaderVariables Get()
{
return variants[0];
}
public static void Compile()
{
if (iscompiled)
{
return;
}
iscompiled = true;
ShaderVariables.Log("Compiling DepthPass_AlphaTest");
string vertsrc;
string fragsrc;
vertsrc = ShCompHelper.FromArray(vertex_bytes);
fragsrc = ShCompHelper.FromArray(fragment_bytes);
variants = new ShaderVariables[1];
variants[0] = ShaderVariables.Compile(vertsrc, fragsrc, "");
}
}
}
| 51.30303 | 142 | 0.541642 | [
"MIT"
] | HaydnTrigg/Librelancer | src/LibreLancer/Shaders/DepthPass_AlphaTest.cs | 3,388 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using TreinamentoInfraestrutura.Domain;
namespace TreinamentoInfraestrutura.Data
{
public class ApplicationContext : DbContext
{
//Gravando seus logs em um arquivo | append = usar o mesmo log
private readonly StreamWriter _writer = new StreamWriter("meu_log_do_ef_core.txt", append: true);
public DbSet<Departamento> Departamentos { get; set; }
public DbSet<Funcionario> Funcionarios { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//QuerySplittingBehavior este comando faz a divisão de consulta quando tiver relacionamento
const string strConnection = "Server=DESKTOP-N8415MR\\SQLEXPRESS;Database=DominandoEFCore;User Id=sa;Password=root;pooling=true;";
optionsBuilder
.UseSqlServer(
strConnection, o => o
.MaxBatchSize(100) //enviar muitos registros em uma única massa Habilitando Batch Size
.CommandTimeout(5)
.EnableRetryOnFailure(4, TimeSpan.FromSeconds(10), null)) //Habilitando resiliência para sua aplicação
.LogTo(Console.WriteLine, LogLevel.Information)
.EnableSensitiveDataLogging();
// optionsBuilder
// .UseSqlServer(strConnection)
//.LogTo(Console.WriteLine); // Configurando um log simplificado
//.LogTo(Console.WriteLine, LogLevel.Information); //visualizando apenas os logs do tipo Information
//.LogTo(Console.WriteLine, new[] {CoreEventId.ContextInitialized, RelationalEventId.CommandExecuted},
// LogLevel.Information,
// DbContextLoggerOptions.LocalTime | DbContextLoggerOptions.SingleLine
//); //Filtrando eventos de seus logs
//.LogTo(_writer.WriteLine, LogLevel.Information); //Gravando seus logs em um arquivo
//.EnableDetailedErrors(); //Habilitando erros detalhados
//.EnableSensitiveDataLogging();//Habilitando visualização dos dados sensíveis
}
public override void Dispose()
{
base.Dispose();
_writer.Dispose();
}
}
}
| 45.740741 | 142 | 0.639271 | [
"MIT"
] | itasouza/DominandoEntityFrameworkCore | DominandoEFCore/TreinamentoInfraestrutura/Data/ApplicationContext.cs | 2,480 | C# |
namespace Wikiled.Twitter.Monitor.Service.Configuration
{
public class TwitterConfig
{
public string Persistency { get; set; }
public bool HashKeywords { get; set; }
public string[] Keywords { get; set; }
public string[] Users { get; set; }
public string[] Languages { get; set; }
}
}
| 21.375 | 56 | 0.605263 | [
"Apache-2.0"
] | AndMu/Wikiled.Twitter.Monitor.Service | src/Wikiled.Twitter.Monitor.Service/Configuration/TwitterConfig.cs | 344 | C# |
using System;
using System.Runtime.CompilerServices;
namespace Cake.AppCenter
{
/// <summary>
/// Settings for appcenter codepush release.
/// Release an update to an app deployment.
/// </summary>
[CompilerGenerated]
public sealed class AppCenterCodepushReleaseSettings : AutoToolSettings
{
/// <summary>
/// -t|--target-binary-version <arg>
/// Semver expression that specifies the binary app version(s) this release is targeting (e.g. 1.1.0, ~1.2.3)
/// </summary>
public string TargetBinaryVersion { get; set; }
/// <summary>
/// -c|--update-contents-path <arg>
/// Path to update contents folder
/// </summary>
public string UpdateContentsPath { get; set; }
/// <summary>
/// -r|--rollout <arg>
/// Percentage of users this release should be available to
/// </summary>
public string Rollout { get; set; }
/// <summary>
/// --disable-duplicate-release-error
/// When this flag is set, releasing a package that is identical to the latest release will produce a warning instead of an error
/// </summary>
public bool? DisableDuplicateReleaseError { get; set; }
/// <summary>
/// -k|--private-key-path <arg>
/// Specifies the location of a RSA private key to sign the release with.NOTICE: use it for react native applications only, client SDK on other platforms will be ignoring signature verification for now!
/// </summary>
public string PrivateKeyPath { get; set; }
/// <summary>
/// -m|--mandatory
/// Specifies whether this release should be considered mandatory
/// </summary>
public bool? Mandatory { get; set; }
/// <summary>
/// -x|--disabled
/// Specifies whether this release should be immediately downloadable
/// </summary>
public bool? Disabled { get; set; }
/// <summary>
/// --description <arg>
/// Description of the changes made to the app in this release
/// </summary>
public string Description { get; set; }
/// <summary>
/// -d|--deployment-name <arg>
/// Deployment to release the update to
/// </summary>
public string DeploymentName { get; set; }
/// <summary>
/// -a|--app <arg>
/// Specify app in the <ownerName>/<appName> format
/// </summary>
public string App { get; set; }
/// <summary>
/// --disable-telemetry
/// Disable telemetry for this command
/// </summary>
public bool? DisableTelemetry { get; set; }
/// <summary>
/// -v|--version
/// Display appcenter version
/// </summary>
public bool? Version { get; set; }
/// <summary>
/// --quiet
/// Auto-confirm any prompts without waiting for input
/// </summary>
public bool? Quiet { get; set; }
/// <summary>
/// -h|--help
/// Display help for current command
/// </summary>
public bool? Help { get; set; }
/// <summary>
/// --env <arg>
/// Environment when using API token
/// </summary>
public string Env { get; set; }
/// <summary>
/// --token <arg>
/// API token
/// </summary>
public string Token { get; set; }
/// <summary>
/// --output <arg>
/// Output format: json
/// </summary>
public string Output { get; set; }
/// <summary>
/// --debug
/// Display extra output for debugging
/// </summary>
public bool? Debug { get; set; }
}
} | 31.605769 | 204 | 0.636447 | [
"MIT"
] | cake-contrib/Cake.AppCenter | src/Cake.AppCenter/Codepush/Release/AppCenterCodepushReleaseSettings.cs | 3,287 | C# |
/*
* WebAPI
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: data
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter;
namespace IO.Swagger.Model
{
/// <summary>
/// LicensePermission
/// </summary>
[DataContract]
public partial class LicensePermission : IEquatable<LicensePermission>, IValidatableObject
{
/// <summary>
/// Defines Mode
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum ModeEnum
{
/// <summary>
/// Enum Deny for value: Deny
/// </summary>
[EnumMember(Value = "Deny")]
Deny = 1,
/// <summary>
/// Enum Allow for value: Allow
/// </summary>
[EnumMember(Value = "Allow")]
Allow = 2
}
/// <summary>
/// Gets or Sets Mode
/// </summary>
[DataMember(Name="mode", EmitDefaultValue=false)]
public ModeEnum? Mode { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="LicensePermission" /> class.
/// </summary>
/// <param name="mode">mode.</param>
/// <param name="name">name.</param>
/// <param name="specification">specification.</param>
/// <param name="utcDateTime">utcDateTime.</param>
/// <param name="values">values.</param>
/// <param name="value">value.</param>
public LicensePermission(ModeEnum? mode = default(ModeEnum?), string name = default(string), string specification = default(string), DateTime? utcDateTime = default(DateTime?), List<string> values = default(List<string>), string value = default(string))
{
this.Mode = mode;
this.Name = name;
this.Specification = specification;
this.UtcDateTime = utcDateTime;
this.Values = values;
this.Value = value;
}
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Gets or Sets Specification
/// </summary>
[DataMember(Name="specification", EmitDefaultValue=false)]
public string Specification { get; set; }
/// <summary>
/// Gets or Sets UtcDateTime
/// </summary>
[DataMember(Name="utcDateTime", EmitDefaultValue=false)]
public DateTime? UtcDateTime { get; set; }
/// <summary>
/// Gets or Sets Values
/// </summary>
[DataMember(Name="values", EmitDefaultValue=false)]
public List<string> Values { get; set; }
/// <summary>
/// Gets or Sets Value
/// </summary>
[DataMember(Name="value", EmitDefaultValue=false)]
public string Value { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class LicensePermission {\n");
sb.Append(" Mode: ").Append(Mode).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Specification: ").Append(Specification).Append("\n");
sb.Append(" UtcDateTime: ").Append(UtcDateTime).Append("\n");
sb.Append(" Values: ").Append(Values).Append("\n");
sb.Append(" Value: ").Append(Value).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as LicensePermission);
}
/// <summary>
/// Returns true if LicensePermission instances are equal
/// </summary>
/// <param name="input">Instance of LicensePermission to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(LicensePermission input)
{
if (input == null)
return false;
return
(
this.Mode == input.Mode ||
(this.Mode != null &&
this.Mode.Equals(input.Mode))
) &&
(
this.Name == input.Name ||
(this.Name != null &&
this.Name.Equals(input.Name))
) &&
(
this.Specification == input.Specification ||
(this.Specification != null &&
this.Specification.Equals(input.Specification))
) &&
(
this.UtcDateTime == input.UtcDateTime ||
(this.UtcDateTime != null &&
this.UtcDateTime.Equals(input.UtcDateTime))
) &&
(
this.Values == input.Values ||
this.Values != null &&
this.Values.SequenceEqual(input.Values)
) &&
(
this.Value == input.Value ||
(this.Value != null &&
this.Value.Equals(input.Value))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Mode != null)
hashCode = hashCode * 59 + this.Mode.GetHashCode();
if (this.Name != null)
hashCode = hashCode * 59 + this.Name.GetHashCode();
if (this.Specification != null)
hashCode = hashCode * 59 + this.Specification.GetHashCode();
if (this.UtcDateTime != null)
hashCode = hashCode * 59 + this.UtcDateTime.GetHashCode();
if (this.Values != null)
hashCode = hashCode * 59 + this.Values.GetHashCode();
if (this.Value != null)
hashCode = hashCode * 59 + this.Value.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 35.044444 | 261 | 0.524921 | [
"Apache-2.0"
] | zanardini/ARXivarNext-StressTest | ARXivarNext-StressTest/IO.Swagger/Model/LicensePermission.cs | 7,885 | C# |
namespace SeoHelper.Constants
{
public class TwitterCardName
{
public const string Site = "twitter:site";
public const string Creator = "twitter:creator";
}
} | 24.25 | 57 | 0.634021 | [
"MIT"
] | EngincanV/SeoHelper | src/SeoHelper/Constants/TwitterCardName.cs | 196 | C# |
using System;
using System.Collections.Generic;
namespace LeetCode.LeetAgain
{
public class ConvertToTitleSln : ISolution
{
public string ConvertToTitle(int n)
{
List<char> t = new List<char>();
while (n != 0)
{
int m = (n - 1) % 26;
t.Add((char) ('A' + m));
n = (n - 1) / 26;
}
t.Reverse();
var s = new string(t.ToArray());
return s;
}
public void Execute()
{
Console.WriteLine(ConvertToTitle(26));
Console.WriteLine(ConvertToTitle(28));
Console.WriteLine(ConvertToTitle(701));
}
}
} | 23.129032 | 51 | 0.464435 | [
"MIT"
] | YouenZeng/LeetCode | LeetCode/LeetAgain/ConvertToTitleSln.cs | 719 | C# |
using Aurora.Controls;
using Aurora.Profiles;
using Aurora.Utils;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using Xceed.Wpf.Toolkit;
namespace Aurora.Settings.Overrides.Logic {
/// <summary>
/// Evaluatable that detects when the value of the given numeric evaluatable changes by a particular amount.
/// <para>Can be used in conjunction with the <see cref="BooleanExtender"/> to make the 'true' last longer than a single eval tick.</para>
/// </summary>
[Evaluatable("Number Change Detector", category: EvaluatableCategory.Maths)]
public class NumericChangeDetector : Evaluatable<bool> {
private double? lastValue;
public NumericChangeDetector() { }
public NumericChangeDetector(Evaluatable<double> eval, bool detectRising = true, bool detectFalling = true, double threshold = 0) {
Evaluatable = eval;
DetectRising = detectRising;
DetectFalling = detectFalling;
DetectionThreshold = threshold;
}
public Evaluatable<double> Evaluatable { get; set; } = EvaluatableDefaults.Get<double>();
public bool DetectRising { get; set; } = true;
public bool DetectFalling { get; set; } = true;
public double DetectionThreshold { get; set; } = 0;
public override Visual GetControl() => new StackPanel()
.WithChild(new Control_EvaluatablePresenter { EvalType = typeof(double) }
.WithBinding(Control_EvaluatablePresenter.ExpressionProperty, this, nameof(Evaluatable), BindingMode.TwoWay))
.WithChild(new CheckBox { Content = "Trigger on increase" }
.WithBinding(CheckBox.IsCheckedProperty, this, nameof(DetectRising)))
.WithChild(new CheckBox { Content = "Trigger on decrease" }
.WithBinding(CheckBox.IsCheckedProperty, this, nameof(DetectFalling)))
.WithChild(new DockPanel { LastChildFill = true }
.WithChild(new Label { Content = "Change required", VerticalAlignment = System.Windows.VerticalAlignment.Center }, Dock.Left)
.WithChild(new DoubleUpDown { Minimum = 0 }
.WithBinding(DoubleUpDown.ValueProperty, this, nameof(DetectionThreshold))));
protected override bool Execute(IGameState gameState) {
var val = Evaluatable.Evaluate(gameState);
var @out = false;
if (lastValue.HasValue) {
// If threshold is 0, we want it to be true on any change, so we can't use >= (as this will always be true). We also can't use > as this means a
// threshold of 1 would not trigger on change 5 -> 6. By making it the smallest possible double when it's 0, it means that any change is detected
// but 0 won't be - exactly what we want.
var threshold = DetectionThreshold == 0 ? double.Epsilon : DetectionThreshold;
var delta = lastValue.Value - val;
@out = (DetectRising && delta <= -threshold) || (DetectFalling && delta >= threshold);
}
lastValue = val;
return @out;
}
public override Evaluatable<bool> Clone() => new NumericChangeDetector { Evaluatable = Evaluatable.Clone(), DetectRising = DetectRising, DetectFalling = DetectFalling, DetectionThreshold = DetectionThreshold };
}
/// <summary>
/// Evaluatable that detects when a boolean value changes.
/// </summary>
[Evaluatable("Boolean Change Detector", category: EvaluatableCategory.Logic)]
public class BooleanChangeDetector : Evaluatable<bool> {
private bool? lastValue;
public BooleanChangeDetector() { }
public BooleanChangeDetector(Evaluatable<bool> eval) : this(eval, true, true) { }
public BooleanChangeDetector(Evaluatable<bool> eval, bool detectTrue = true, bool detectFalse = true) {
Evaluatable = eval;
DetectTrue = detectTrue;
DetectFalse = detectFalse;
}
public Evaluatable<bool> Evaluatable { get; set; } = EvaluatableDefaults.Get<bool>();
public bool DetectTrue { get; set; } = true;
public bool DetectFalse { get; set; } = true;
public override Visual GetControl() => new StackPanel()
.WithChild(new Control_EvaluatablePresenter { EvalType = typeof(bool) }
.WithBinding(Control_EvaluatablePresenter.ExpressionProperty, this, nameof(Evaluatable), BindingMode.TwoWay))
.WithChild(new CheckBox { Content = "Trigger on become true" }
.WithBinding(CheckBox.IsCheckedProperty, this, nameof(DetectTrue)))
.WithChild(new CheckBox { Content = "Trigger on become false" }
.WithBinding(CheckBox.IsCheckedProperty, this, nameof(DetectFalse)));
protected override bool Execute(IGameState gameState) {
var val = Evaluatable.Evaluate(gameState);
var result = (val && lastValue == false && DetectTrue) // Result is true if: the next value is true, the old value was false and we are detecting true
|| (!val && lastValue == true && DetectFalse); // Or the next value is false, the old value was true and we are detecting false
lastValue = val;
return result;
}
public override Evaluatable<bool> Clone() => new BooleanChangeDetector { Evaluatable = Evaluatable.Clone(), DetectTrue = DetectTrue, DetectFalse = DetectFalse };
}
}
| 54.134615 | 219 | 0.640142 | [
"MIT"
] | ADoesGit/Aurora | Project-Aurora/Project-Aurora/Settings/Overrides/Logic/Boolean/Boolean_ChangeDetector.cs | 5,529 | C# |
using System.Collections.Generic;
using System.Runtime.Remoting.Messaging;
using Bluff.Helpers;
using Bluff.Models;
using Sony.Vegas;
namespace Bluff.Commands
{
public class ArrangeEventsByCreatedTimestamp
{
public static void Execute(Vegas vegas)
{
var videoTracks = VegasHelper.GetTracks<VideoTrack>(vegas, 1, 1, true);
var selectedTrackEvents = VegasHelper.GetTrackEvents(videoTracks);
var startingPosition = selectedTrackEvents[0].Start;
var trackEventInfos = new List<TrackEventInfo>();
foreach (var selectedTrackEvent in selectedTrackEvents)
{
trackEventInfos.Add(new TrackEventInfo(selectedTrackEvent));
}
//order the list
trackEventInfos.Sort((info1, info2) => info1.FileTimestamp.CompareTo(info2.FileTimestamp));
var baseTimeStamp = trackEventInfos[0].FileTimestamp;
using (var undo = new UndoBlock("Order Events By Name And Time"))
{
//update order of the events
foreach (var selectedTrackEvent in trackEventInfos)
{
var currentPosition = startingPosition +
Timecode.FromMilliseconds(
(selectedTrackEvent.FileTimestamp - baseTimeStamp).TotalMilliseconds);
if (selectedTrackEvent.TrackEvent.IsGrouped)
{
foreach (var groupedTrackEvents in selectedTrackEvent.TrackEvent.Group)
{
groupedTrackEvents.Start = currentPosition;
}
}
else
{
selectedTrackEvent.TrackEvent.Start = currentPosition;
}
}
}
}
}
} | 35.925926 | 116 | 0.547938 | [
"MIT"
] | AlienArc/VegasBluff | src/Bluff/Commands/ArrangeEventsByCreatedTimestamp.cs | 1,940 | C# |
using Microsoft.SqlServer.Dts.Pipeline;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
using RevolutionaryStuff.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
namespace RevolutionaryStuff.SSIS
{
/// <remarks>https://www.simple-talk.com/sql/ssis/developing-a-custom-ssis-source-component/</remarks>
/// <remarks>https://docs.microsoft.com/en-us/sql/integration-services/extending-packages-custom-objects-data-flow-types/developing-a-custom-transformation-component-with-synchronous-outputs</remarks>
public abstract class BasePipelineComponent : PipelineComponent
{
internal const int AssemblyComponentVersion = 7;
internal const int EnUsCodePage = 1252;
protected static class CommonPropertyNames
{
public const string IgnoreCase = "IgnoreCase";
public const string OutputColumnName = "OutputColumnName";
}
protected int GetCustomPropertyAsInt(string propertyName, int fallback = 0)
=> Parse.ParseInt32(GetCustomPropertyAsString(propertyName), fallback);
protected bool GetCustomPropertyAsBool(string propertyName, bool fallback = false)
=> Parse.ParseBool(GetCustomPropertyAsString(propertyName), fallback);
protected string GetCustomPropertyAsString(string propertyName, string fallback = null)
{
try
{
var p = ComponentMetaData.CustomPropertyCollection[propertyName];
if (p != null)
{
return (string)p.Value;
}
}
catch (Exception)
{ }
return fallback;
}
private enum BasePipelineComponentCodes
{
Error,
ColumnMappingSuccess,
ColumnMappingError,
InvalidBufferId,
ComponentClaimsSyncButOutputsIndicateOtherwise,
TraceRegionStart,
TraceRegionEnd,
MethodResult,
};
protected const int SampleSize = 25;
protected IDTSCustomProperty100 CreateCustomProperty(string name, string defaultValue, string description)
{
var p = ComponentMetaData.CustomPropertyCollection.New();
p.Name = name;
p.Description = description;
p.Value = defaultValue;
return p;
}
private enum BasePipelineInfoMessages
{
WaitingForDebuggerAttachment,
}
protected int StatusNotifyIncrement = 1000;
private bool DebuggerAttachmentWaitDone;
private static bool DebuggerAttachmentWaitDone_s = false;
protected void DebuggerAttachmentWait()
{
lock (this)
{
DebuggerAttachmentWaitDone_s = DebuggerAttachmentWaitDone_s && true; //to get rid of compiler warning and worse yet, optimizations...
if (!DebuggerAttachmentWaitDone)
{
#if false
for (int z = 0; z < 60 && !DebuggerAttachmentWaitDone_s; ++z)
{
System.Threading.Thread.Sleep(1000);
FireInformation(BasePipelineInfoMessages.WaitingForDebuggerAttachment, $"{this.GetType().Name} {z}/60");
}
#endif
}
DebuggerAttachmentWaitDone = true;
}
}
public override DTSValidationStatus Validate()
{
using (var tr = CreateTraceRegion())
{
var ret = base.Validate();
if (ret == DTSValidationStatus.VS_ISVALID)
{
ret = OnValidate();
}
return tr.SniffResult(ret);
}
}
protected virtual DTSValidationStatus OnValidate()
{
var ret = base.Validate();
if (ret != DTSValidationStatus.VS_ISVALID) return ret;
if (AllOutputsAreSynchronous)
{
int z = 0;
foreach (IDTSOutput100 output in ComponentMetaData.OutputCollection)
{
if (output.SynchronousInputID < 1)
{
FireInformation(BasePipelineComponentCodes.ComponentClaimsSyncButOutputsIndicateOtherwise, $"Output [{output.Name}]({z}) is claiming SynchronousInputID={output.SynchronousInputID}");
return DTSValidationStatus.VS_NEEDSNEWMETADATA;
}
++z;
}
}
return DTSValidationStatus.VS_ISVALID;
}
private readonly IDictionary<int, int> ProcessInputIterationByInputId = new Dictionary<int, int>();
private readonly IDictionary<int, Stopwatch> StopwatchesByInputId = new Dictionary<int, Stopwatch>();
public override void ProcessInput(int inputID, PipelineBuffer buffer)
{
base.ProcessInput(inputID, buffer);
if (buffer != null)
{
var sw = StopwatchesByInputId.FindOrCreate(inputID, () => new Stopwatch());
if (!buffer.EndOfRowset)
{
try
{
sw.Start();
ProcessInputIterationByInputId.Increment(inputID);
OnProcessInput(inputID, buffer);
}
finally
{
sw.Stop();
}
}
if (buffer.EndOfRowset)
{
using (CreateTraceRegion($"EndOfRowset for inputID={inputID} iterations={ProcessInputIterationByInputId.Increment(inputID,0)} elapsedTime={sw.Elapsed}", nameof(OnProcessInputEndOfRowset)))
{
OnProcessInputEndOfRowset(inputID);
}
}
}
}
protected virtual void OnProcessInputEndOfRowset(int inputID)
{ }
protected abstract void OnProcessInput(int inputID, PipelineBuffer buffer);
protected readonly bool AllOutputsAreSynchronous;
protected BasePipelineComponent(bool allOutputsAreSynchronous)
{
AllOutputsAreSynchronous = allOutputsAreSynchronous;
}
public override IDTSOutputColumn100 InsertOutputColumnAt(
int outputID,
int outputColumnIndex,
string name,
string description)
{
throw new Exception(string.Format("Fail to add output column name to {0} ", ComponentMetaData.Name), null);
}
public override void ProvideComponentProperties()
{
base.ProvideComponentProperties();
ComponentMetaData.ContactInfo = "jason@jasonthomas.com";
}
protected TraceRegion CreateTraceRegion(string message=null, [CallerMemberName] string caller = null)
=> new TraceRegion(this, message, caller);
protected class TraceRegion : BaseDisposable
{
private static int Id_s = 1;
private readonly int Id = Interlocked.Increment(ref Id_s);
private readonly BasePipelineComponent Component;
private readonly string Message;
private readonly string Caller;
private readonly Stopwatch SW = new Stopwatch();
public TraceRegion(BasePipelineComponent component, string message, string caller)
{
Requires.NonNull(component, nameof(component));
Component = component;
Message = message;
Caller = caller;
Component.FireInformation(BasePipelineComponentCodes.TraceRegionStart, $"{Message} [TRID{Id}] vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv", Caller);
SW.Start();
}
private object Result;
private bool SniffResultCalled;
public T SniffResult<T>(T res)
{
Requires.SingleCall(ref SniffResultCalled);
Result = res;
return res;
}
protected override void OnDispose(bool disposing)
{
SW.Stop();
Component.FireInformation(BasePipelineComponentCodes.TraceRegionStart, $"{Message} returned [{Result}] and took {SW.Elapsed} [TRID{Id}] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^", Caller);
base.OnDispose(disposing);
}
}
protected void FireInformation<TMessageCode>(TMessageCode code, string message, [CallerMemberName] string caller = null) where TMessageCode : struct
{
bool fireAgain = true;
var component = $"{ComponentMetaData.Name}.{caller}";
var desc = $"{code}: {message}";
Trace.WriteLine($"Information: {component}({code})=>{desc}");
ComponentMetaData.FireInformation((int)(object)code, component, desc, "", 0, ref fireAgain);
}
protected void FireError<TMessageCode>(TMessageCode code, string message, [CallerMemberName] string caller = null) where TMessageCode : struct
=> FireError(code, new Exception(message), message, caller);
protected void FireError<TMessageCode>(TMessageCode code, Exception ex, string message=null, [CallerMemberName] string caller = null, bool throwException=true) where TMessageCode : struct
{
bool cancel = true;
var component = $"{ComponentMetaData.Name}.{caller}";
var desc = $"{code}: {message ?? ex.Message}";
Trace.WriteLine($"Error: {component}({code})=>{desc}");
ComponentMetaData.FireError((int)(object)code, $"{component}", $"{desc}", "", 0, out cancel);
if (throwException)
{
throw ex;
}
}
/// <remarks>https://technet.microsoft.com/en-us/library/ms345165(v=sql.110).aspx</remarks>
protected object GetObject(string colName, PipelineBuffer buffer, ColumnBufferMapping cbm)
{
var colDataType = cbm.GetColumnFromColumnName(colName).DataType;
var n = cbm.GetPositionFromColumnName(colName);
if (buffer.IsNull(n)) return null;
switch (colDataType)
{
case DataType.DT_BOOL:
return buffer.GetBoolean(n);
case DataType.DT_I1:
return buffer.GetSByte(n);
case DataType.DT_I2:
return buffer.GetInt16(n);
case DataType.DT_I4:
return buffer.GetInt32(n);
case DataType.DT_I8:
return buffer.GetInt64(n);
case DataType.DT_UI1:
return buffer.GetByte(n);
case DataType.DT_UI2:
return buffer.GetUInt16(n);
case DataType.DT_UI4:
return buffer.GetUInt32(n);
case DataType.DT_UI8:
return buffer.GetUInt64(n);
case DataType.DT_R4:
return buffer.GetSingle(n);
case DataType.DT_R8:
return buffer.GetDouble(n);
case DataType.DT_DBDATE:
return buffer.GetDate(n);
case DataType.DT_DATE:
case DataType.DT_DBTIMESTAMP:
case DataType.DT_DBTIMESTAMP2:
case DataType.DT_FILETIME:
return buffer.GetDateTime(n);
case DataType.DT_STR:
case DataType.DT_WSTR:
case DataType.DT_NTEXT:
case DataType.DT_TEXT:
return buffer.GetString(n);
case DataType.DT_NUMERIC:
case DataType.DT_DECIMAL:
case DataType.DT_CY:
return buffer.GetDecimal(n);
case DataType.DT_GUID:
return buffer.GetGuid(n);
}
bool cancel = true;
ComponentMetaData.FireError(123, "GetObject", string.Format("GetObject(colName={0}, colDataType={1}) is not yet supported", colName, colDataType), "", 0, out cancel);
return null;
}
protected ColumnBufferMapping CreateColumnBufferMapping(IDTSInput100 input, int? overrideBuffer=null)
{
//done via ternary operator instead of GetValueOrDefault so as to not dereference output.Buffer unless critical
var bufferId = overrideBuffer.HasValue ? overrideBuffer.Value : input.Buffer;
var cbm = new ColumnBufferMapping();
int cnt = input.InputColumnCollection.Count;
using (CreateTraceRegion($"Output.ID={input.ID} Output.Name={input.Name} #cols={cnt} for bufferId={bufferId} into cbm={cbm.ID}"))
{
if (bufferId < 1)
{
FireError(BasePipelineComponentCodes.InvalidBufferId, $"BufferId({bufferId}) for input=[{input.Name}] really should be > 0");
}
else
{
for (int x = 0; x < cnt;)
{
var column = input.InputColumnCollection[x++];
try
{
var offset = BufferManager.FindColumnByLineageID(bufferId, column.LineageID);
cbm.Add(column, offset);
FireInformation(BasePipelineComponentCodes.ColumnMappingSuccess, $"{x}/{cnt} column.Name=[{column.Name}] column.LineageID=[{column.LineageID}] => {offset}");
}
catch (Exception ex)
{
FireError(BasePipelineComponentCodes.ColumnMappingError, ex, $"{x}/{cnt} column.Name=[{column.Name}] column.LineageID=[{column.LineageID}]", throwException: false);
throw;
}
}
}
return cbm;
}
}
protected ColumnBufferMapping CreateColumnBufferMapping(IDTSOutput100 output, int? overrideBuffer = null)
{
//done via ternary operator instead of GetValueOrDefault so as to not dereference output.Buffer unless critical
var bufferId = overrideBuffer.HasValue ? overrideBuffer.Value : output.Buffer;
var cbm = new ColumnBufferMapping();
int cnt = output.OutputColumnCollection.Count;
using (CreateTraceRegion($"Output.ID={output.ID} Output.Name={output.Name} #cols={cnt} for bufferId={bufferId} into cbm={cbm.ID}"))
{
if (bufferId < 1)
{
FireError(BasePipelineComponentCodes.InvalidBufferId, $"BufferId({bufferId}) for output=[{output.Name}] really should be > 0");
}
for (int x = 0; x < cnt;)
{
var column = output.OutputColumnCollection[x++];
try
{
var offset = BufferManager.FindColumnByLineageID(bufferId, column.LineageID);
cbm.Add(column, offset);
FireInformation(BasePipelineComponentCodes.ColumnMappingSuccess, $"{x}/{cnt} column.Name=[{column.Name}] column.LineageID=[{column.LineageID}] => {offset}");
}
catch (Exception ex)
{
FireError(BasePipelineComponentCodes.ColumnMappingError, ex, $"{x}/{cnt} column.Name=[{column.Name}] column.LineageID=[{column.LineageID}]", throwException: false);
throw;
}
}
return cbm;
}
}
protected class RuntimeData : BaseDisposable
{
protected readonly BasePipelineComponent Parent;
public readonly IList<ColumnBufferMapping> InputColumnBufferMappings;
public readonly IList<ColumnBufferMapping> OutputColumnBufferMappings;
protected int GetCustomPropertyAsInt(string propertyName, int fallback = 0)
=> Parent.GetCustomPropertyAsInt(propertyName, fallback);
protected bool GetCustomPropertyAsBool(string propertyName, bool fallback = false)
=> Parent.GetCustomPropertyAsBool(propertyName, fallback);
protected string GetCustomPropertyAsString(string propertyName, string fallback = null)
=> Parent.GetCustomPropertyAsString(propertyName, fallback);
protected IDTSComponentMetaData100 ComponentMetaData
=> Parent.ComponentMetaData;
private ColumnBufferMapping CreateColumnBufferMapping(IDTSInput100 input, int? overrideBuffer = null)
=> Parent.CreateColumnBufferMapping(input, overrideBuffer);
private ColumnBufferMapping CreateColumnBufferMapping(IDTSOutput100 output, int? overrideBuffer = null)
=> Parent.CreateColumnBufferMapping(output, overrideBuffer);
public RuntimeData(BasePipelineComponent parent)
{
Requires.NonNull(parent, nameof(parent));
Parent = parent;
var cbms = new List<ColumnBufferMapping>();
for (int z = 0; z < ComponentMetaData.InputCollection.Count; ++z)
{
var cols = ComponentMetaData.InputCollection[z];
cbms.Add(Parent.CreateColumnBufferMapping(cols));
}
InputColumnBufferMappings = cbms.AsReadOnly();
cbms = new List<ColumnBufferMapping>();
for (int z = 0; z < ComponentMetaData.OutputCollection.Count; ++z)
{
var output = ComponentMetaData.OutputCollection[z];
int bufferId = Parent.GetBufferId(output);
cbms.Add(Parent.CreateColumnBufferMapping(output, bufferId));
}
OutputColumnBufferMappings = cbms.AsReadOnly();
}
}
private int GetBufferId(IDTSOutput100 output)
{
if (output.SynchronousInputID == 0)
{
return output.Buffer;
}
foreach (IDTSInput100 input in ComponentMetaData.InputCollection)
{
if (input.ID == output.SynchronousInputID)
{
return input.Buffer;
}
}
throw new Exception($"Output is synchronous to {output.SynchronousInputID} but could not find that input");
}
protected RuntimeData RD { get; private set; }
protected virtual RuntimeData ConstructRuntimeData()
=> new RuntimeData(this);
public override void PreExecute()
{
using (CreateTraceRegion())
{
DebuggerAttachmentWait();
base.PreExecute();
RD = ConstructRuntimeData();
Requires.NonNull(RD, nameof(RD));
}
}
public override void PostExecute()
{
base.PostExecute();
Stuff.Dispose(RD);
RD = null;
}
/// <summary>
/// Upgrade the metadata if it needs it.
/// Right now all this does is update the version number in the XML.
/// </summary>
/// <param name="pipelineVersion">The curreht version of the pipeline.</param>
public override void PerformUpgrade(int pipelineVersion)
{
// Get the attributes for the executable
var componentAttribute = (DtsPipelineComponentAttribute)Attribute.GetCustomAttribute(this.GetType(), typeof(DtsPipelineComponentAttribute), false);
int binaryVersion = componentAttribute.CurrentVersion;
using (CreateTraceRegion($"Upgrading {this.GetType().Name} on [{ComponentMetaData.Name}]({ComponentMetaData.ID}) from version {pipelineVersion} to version {binaryVersion}"))
{
// Set the SSIS Package's version ID for this component to the binary version...
ComponentMetaData.Version = binaryVersion;
OnPerformUpgrade(pipelineVersion, binaryVersion);
}
}
protected virtual void OnPerformUpgrade(int from, int to)
{ }
}
}
| 42.296146 | 243 | 0.564646 | [
"MIT"
] | jbt00000/RevolutionaryStuff | src/RevolutionaryStuff.SSIS/BasePipelineComponent.cs | 20,854 | C# |
using MyCompany.Core.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyCompany.Entities.Concrete
{
public class Category: IEntity
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
}
}
| 20.8 | 48 | 0.708333 | [
"MIT"
] | gnnhakan/Asp.Net-Core | MyCompany/MyCompany.Entities/Concrete/Category.cs | 314 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.17020
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Catel.Properties {
using System;
/// <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 Exceptions {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Exceptions() {
}
/// <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 (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Catel.WP7.Properties.Catel.Core.Exceptions", typeof(Exceptions).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;
}
}
/// <summary>
/// Looks up a localized string similar to BeginEdit cannot be invoked twice. A call to BeginEdit must always be closed with a call to CancelEdit or EndEdit..
/// </summary>
internal static string BeginEditCannotBeInvokedTwice {
get {
return ResourceManager.GetString("BeginEditCannotBeInvokedTwice", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot compare to other object because the other object does not implement IDataObjectBase.
/// </summary>
internal static string CannotCompareToObjectNotImplementingIDataObjectBase {
get {
return ResourceManager.GetString("CannotCompareToObjectNotImplementingIDataObjectBase", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot get the value of property '{0}'.
/// </summary>
internal static string CannotGetPropertyValueException {
get {
return ResourceManager.GetString("CannotGetPropertyValueException", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot set the value of property '{0}'.
/// </summary>
internal static string CannotSetPropertyValueException {
get {
return ResourceManager.GetString("CannotSetPropertyValueException", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to create directory '{0}'.
/// </summary>
internal static string FailedToCreateDirectory {
get {
return ResourceManager.GetString("FailedToCreateDirectory", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File not found.
/// </summary>
internal static string FileNotFound {
get {
return ResourceManager.GetString("FileNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid or no view model.
/// </summary>
internal static string InvalidViewModel {
get {
return ResourceManager.GetString("InvalidViewModel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There is no model '{0}' registered with the model attribute, so the ViewModelToModel attribute on property '{1}' is invalid.
///
///If you are sure that you have a model with this name, make sure it's public instead of private or protected for Silverlight and WP7 because non-public reflection is not allowed in Silverlight..
/// </summary>
internal static string ModelNotRegistered {
get {
return ResourceManager.GetString("ModelNotRegistered", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Properties that are not serializable are not supported.
/// </summary>
internal static string NonSerializablePropertiesNotSupported {
get {
return ResourceManager.GetString("NonSerializablePropertiesNotSupported", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unfortunately, this is not supported in Silverlight.
/// </summary>
internal static string NotSupportedInSilverlight {
get {
return ResourceManager.GetString("NotSupportedInSilverlight", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unfortunately, this is not supported in Windows Phone 7.
/// </summary>
internal static string NotSupportedInWindowsPhone7 {
get {
return ResourceManager.GetString("NotSupportedInWindowsPhone7", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There is no page registered as '{0}'.
/// </summary>
internal static string PageNotRegistered {
get {
return ResourceManager.GetString("PageNotRegistered", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Property '{0}' is not found.
/// </summary>
internal static string PropertyNotFound {
get {
return ResourceManager.GetString("PropertyNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mapped viewmodel property '{0}' to model property '{1}' is invalid because property '{1}' is not found on the model '{2}'.
/// </summary>
internal static string PropertyNotFoundInModel {
get {
return ResourceManager.GetString("PropertyNotFoundInModel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The view model of type '{0}' is not registered thus cannot be used in this context.
/// </summary>
internal static string ViewModelNotRegistered {
get {
return ResourceManager.GetString("ViewModelNotRegistered", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There is no window registered as '{0}'.
/// </summary>
internal static string WindowNotRegistered {
get {
return ResourceManager.GetString("WindowNotRegistered", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The view model is of the wrong type. Expected '{0}', but type is '{1}'.
/// </summary>
internal static string WrongViewModelType {
get {
return ResourceManager.GetString("WrongViewModelType", resourceCulture);
}
}
}
}
| 42.707763 | 215 | 0.592858 | [
"MIT"
] | gautamsi/Catel | src/Catel.Core/Catel.Core.NET40/Properties/Exceptions.WP7.Mango.Designer.cs | 9,355 | C# |
using System.Linq;
using Moq;
using NUnit.Framework;
using Xamarin.PropertyEditing.Reflection;
using Xamarin.PropertyEditing.ViewModels;
namespace Xamarin.PropertyEditing.Tests
{
public abstract class PropertiesViewModelTests
{
protected class TestClass
{
public string Property
{
get;
set;
}
}
protected class TestClassSub
: TestClass
{
[System.ComponentModel.Category ("Sub")]
public int SubProperty
{
get;
set;
}
}
[Test]
public void TypeName ()
{
var provider = new ReflectionEditorProvider ();
var obj = new TestClassSub ();
var vm = CreateVm (provider);
Assume.That (vm.TypeName, Is.Null);
vm.SelectedObjects.Add (obj);
Assert.That (vm.TypeName, Is.EqualTo (nameof (TestClassSub)));
}
[Test]
public void TypeNameNoneSelected ()
{
var provider = new ReflectionEditorProvider ();
var obj = new TestClassSub ();
var vm = CreateVm (provider);
Assume.That (vm.TypeName, Is.Null);
vm.SelectedObjects.Add (obj);
Assume.That (vm.TypeName, Is.EqualTo (nameof (TestClassSub)));
vm.SelectedObjects.Remove (obj);
Assert.That (vm.TypeName, Is.Null);
}
[Test]
public void TypeNameMultipleSameSelected ()
{
var provider = new ReflectionEditorProvider ();
var obj = new TestClassSub ();
var obj2 = new TestClassSub ();
var vm = CreateVm (provider);
Assume.That (vm.TypeName, Is.Null);
vm.SelectedObjects.Add (obj);
vm.SelectedObjects.Add (obj2);
Assert.That (vm.TypeName, Is.EqualTo (nameof (TestClassSub)));
}
[Test]
public void TypeNameMultipleNotSameSelected ()
{
var provider = new ReflectionEditorProvider ();
var obj = new TestClassSub ();
var obj2 = new TestClass ();
var vm = CreateVm (provider);
Assume.That (vm.TypeName, Is.Null);
vm.SelectedObjects.Add (obj);
vm.SelectedObjects.Add (obj2);
Assert.That (vm.TypeName, Is.Not.EqualTo (nameof (TestClassSub)));
Assert.That (vm.TypeName, Is.Not.EqualTo (nameof (TestClass)));
}
[Test]
public void ObjectName ()
{
var obj = new object ();
const string name = "name";
var editor = new Mock<IObjectEditor> ();
editor.SetupGet (e => e.Properties).Returns (new IPropertyInfo[0]);
editor.SetupGet (e => e.Target).Returns (obj);
editor.As<INameableObject> ().Setup (n => n.GetNameAsync ()).ReturnsAsync (name);
var provider = new Mock<IEditorProvider> ();
provider.Setup (p => p.GetObjectEditorAsync (obj)).ReturnsAsync (editor.Object);
var vm = CreateVm (provider.Object);
Assume.That (vm.ObjectName, Is.Null);
bool changed = false;
vm.PropertyChanged += (o, e) => {
if (e.PropertyName == nameof (PropertiesViewModel.ObjectName))
changed = true;
};
vm.SelectedObjects.Add (obj);
Assert.That (vm.ObjectName, Is.EqualTo (name));
Assert.That (changed, Is.True);
}
[Test]
public void IsObjectNameable ()
{
var obj = new object ();
const string name = "name";
var editor = new Mock<IObjectEditor> ();
editor.SetupGet (e => e.Properties).Returns (new IPropertyInfo[0]);
editor.SetupGet (e => e.Target).Returns (obj);
editor.As<INameableObject> ().Setup (n => n.GetNameAsync ()).ReturnsAsync (name);
var provider = new Mock<IEditorProvider> ();
provider.Setup (p => p.GetObjectEditorAsync (obj)).ReturnsAsync (editor.Object);
var vm = CreateVm (provider.Object);
Assume.That (vm.IsObjectNameable, Is.False);
bool changed = false;
vm.PropertyChanged += (o, e) => {
if (e.PropertyName == nameof (PropertiesViewModel.IsObjectNameable))
changed = true;
};
vm.SelectedObjects.Add (obj);
Assert.That (vm.IsObjectNameable, Is.True);
Assert.That (changed, Is.True);
}
[Test]
public void ObjectNameNoneSelected ()
{
var obj = new object ();
const string name = "name";
var editor = new Mock<IObjectEditor> ();
editor.SetupGet (e => e.Properties).Returns (new IPropertyInfo[0]);
editor.SetupGet (e => e.Target).Returns (obj);
editor.As<INameableObject> ().Setup (n => n.GetNameAsync ()).ReturnsAsync (name);
var provider = new Mock<IEditorProvider> ();
provider.Setup (p => p.GetObjectEditorAsync (obj)).ReturnsAsync (editor.Object);
var vm = CreateVm (provider.Object);
Assume.That (vm.ObjectName, Is.Null);
vm.SelectedObjects.Add (obj);
Assume.That (vm.ObjectName, Is.EqualTo (name));
vm.SelectedObjects.Remove (obj);
Assert.That (vm.ObjectName, Is.Null);
}
[Test]
public void IsObjectNameableNoneSelected ()
{
var obj = new object ();
const string name = "name";
var editor = new Mock<IObjectEditor> ();
editor.SetupGet (e => e.Properties).Returns (new IPropertyInfo[0]);
editor.SetupGet (e => e.Target).Returns (obj);
editor.As<INameableObject> ().Setup (n => n.GetNameAsync ()).ReturnsAsync (name);
var provider = new Mock<IEditorProvider> ();
provider.Setup (p => p.GetObjectEditorAsync (obj)).ReturnsAsync (editor.Object);
var vm = CreateVm (provider.Object);
Assume.That (vm.IsObjectNameable, Is.False);
vm.SelectedObjects.Add (obj);
Assume.That (vm.IsObjectNameable, Is.True);
vm.SelectedObjects.Remove (obj);
Assert.That (vm.IsObjectNameable, Is.False);
}
[Test]
public void IsObjectNameableNotNameable ()
{
var obj = new object ();
var editor = new Mock<IObjectEditor> ();
editor.SetupGet (e => e.Target).Returns (obj);
editor.SetupGet (e => e.Properties).Returns (new IPropertyInfo[0]);
var provider = new Mock<IEditorProvider> ();
provider.Setup (p => p.GetObjectEditorAsync (obj)).ReturnsAsync (editor.Object);
var vm = CreateVm (provider.Object);
Assume.That (vm.IsObjectNameable, Is.False);
vm.SelectedObjects.Add (obj);
Assume.That (vm.IsObjectNameable, Is.False);
vm.SelectedObjects.Remove (obj);
Assert.That (vm.IsObjectNameable, Is.False);
}
[Test]
public void ObjectNameNoName ()
{
var obj = new object ();
var editor = new Mock<IObjectEditor> ();
editor.SetupGet (e => e.Properties).Returns (new IPropertyInfo[0]);
editor.SetupGet (e => e.Target).Returns (obj);
editor.As<INameableObject> ().Setup (n => n.GetNameAsync ()).ReturnsAsync ((string)null);
var provider = new Mock<IEditorProvider> ();
provider.Setup (p => p.GetObjectEditorAsync (obj)).ReturnsAsync (editor.Object);
var vm = CreateVm (provider.Object);
Assume.That (vm.ObjectName, Is.Null);
vm.SelectedObjects.Add (obj);
Assert.That (vm.ObjectName, Is.EqualTo (Properties.Resources.NoName));
}
[Test]
public void ObjectNameMultipleSelected ()
{
var obj = new object ();
var obj2 = new object ();
const string name = "name";
var editor = new Mock<IObjectEditor> ();
editor.SetupGet (e => e.Properties).Returns (new IPropertyInfo[0]);
editor.SetupGet (e => e.Target).Returns (obj);
editor.As<INameableObject> ().Setup (n => n.GetNameAsync ()).ReturnsAsync (name);
var editor2 = new Mock<IObjectEditor> ();
editor2.SetupGet (e => e.Target).Returns (obj2);
editor2.SetupGet (e => e.Properties).Returns (new IPropertyInfo[0]);
var provider = new Mock<IEditorProvider> ();
provider.Setup (p => p.GetObjectEditorAsync (obj)).ReturnsAsync (editor.Object);
provider.Setup (p => p.GetObjectEditorAsync (obj2)).ReturnsAsync (editor2.Object);
var vm = CreateVm (provider.Object);
Assume.That (vm.ObjectName, Is.Null);
vm.SelectedObjects.Add (obj);
vm.SelectedObjects.Add (obj2);
// Properties.Resources.MultipleObjectsSelected
Assert.That (vm.ObjectName, Is.Not.Null.And.Not.EqualTo (name));
vm.SelectedObjects.Remove (obj2);
Assert.That (vm.ObjectName, Is.EqualTo (name));
}
[Test]
public void IsObjectNameableMultipleSelected ()
{
var obj = new object ();
var obj2 = new object ();
const string name = "name";
var editor = new Mock<IObjectEditor> ();
editor.SetupGet (e => e.Properties).Returns (new IPropertyInfo[0]);
editor.SetupGet (e => e.Target).Returns (obj);
editor.As<INameableObject> ().Setup (n => n.GetNameAsync ()).ReturnsAsync (name);
var editor2 = new Mock<IObjectEditor> ();
editor2.SetupGet (e => e.Properties).Returns (new IPropertyInfo[0]);
editor2.SetupGet (e => e.Target).Returns (obj2);
editor2.As<INameableObject> ();
var provider = new Mock<IEditorProvider> ();
provider.Setup (p => p.GetObjectEditorAsync (obj)).ReturnsAsync (editor.Object);
provider.Setup (p => p.GetObjectEditorAsync (obj2)).ReturnsAsync (editor2.Object);
var vm = CreateVm (provider.Object);
Assume.That (vm.IsObjectNameable, Is.False);
vm.SelectedObjects.Add (obj);
Assume.That (vm.IsObjectNameable, Is.True);
vm.SelectedObjects.Add (obj2);
Assert.That (vm.IsObjectNameable, Is.True);
vm.SelectedObjects.Remove (obj2);
Assert.That (vm.IsObjectNameable, Is.True);
}
[Test]
public void IsObjectReadonlyMultipleSelected ()
{
var obj = new object ();
var obj2 = new object ();
const string name = "name";
var editor = new Mock<IObjectEditor> ();
editor.SetupGet (e => e.Properties).Returns (new IPropertyInfo[0]);
editor.SetupGet (e => e.Target).Returns (obj);
editor.As<INameableObject> ().Setup (n => n.GetNameAsync ()).ReturnsAsync (name);
var editor2 = new Mock<IObjectEditor> ();
editor2.SetupGet (e => e.Properties).Returns (new IPropertyInfo[0]);
editor2.SetupGet (e => e.Target).Returns (obj2);
editor2.As<INameableObject> ();
var provider = new Mock<IEditorProvider> ();
provider.Setup (p => p.GetObjectEditorAsync (obj)).ReturnsAsync (editor.Object);
provider.Setup (p => p.GetObjectEditorAsync (obj2)).ReturnsAsync (editor2.Object);
var vm = CreateVm (provider.Object);
Assume.That (vm.IsObjectNameReadOnly, Is.False);
vm.SelectedObjects.Add (obj);
Assume.That (vm.IsObjectNameReadOnly, Is.False);
vm.SelectedObjects.Add (obj2);
Assert.That (vm.IsObjectNameReadOnly, Is.True);
vm.SelectedObjects.Remove (obj2);
Assert.That (vm.IsObjectNameReadOnly, Is.False);
}
[Test]
public void SetObjectName()
{
var obj = new object ();
const string name = "name";
var editor = new Mock<IObjectEditor> ();
editor.SetupGet (e => e.Properties).Returns (new IPropertyInfo[0]);
editor.SetupGet (e => e.Target).Returns (obj);
var nameable = editor.As<INameableObject> ();
nameable.Setup (n => n.GetNameAsync ()).ReturnsAsync ((string)null);
var provider = new Mock<IEditorProvider> ();
provider.Setup (p => p.GetObjectEditorAsync (obj)).ReturnsAsync (editor.Object);
var vm = CreateVm (provider.Object);
Assume.That (vm.IsObjectNameable, Is.False);
vm.SelectedObjects.Add (obj);
Assume.That (vm.IsObjectNameable, Is.True);
bool changed = false;
vm.PropertyChanged += (o, e) => {
if (e.PropertyName == nameof (PropertiesViewModel.ObjectName))
changed = true;
};
vm.ObjectName = name;
nameable.Verify (n => n.SetNameAsync (name));
Assert.That (changed, Is.True);
Assert.That (vm.ObjectName, Is.EqualTo (name));
}
[Test]
public void EventsNotEnabled()
{
var obj = new object ();
var editor = new Mock<IObjectEditor> ();
editor.SetupGet (e => e.Properties).Returns (new IPropertyInfo[0]);
var provider = new Mock<IEditorProvider> ();
provider.Setup (p => p.GetObjectEditorAsync (obj)).ReturnsAsync (editor.Object);
var vm = CreateVm (provider.Object);
Assert.That (vm.EventsEnabled, Is.False);
vm.SelectedObjects.Add (obj);
Assert.That (vm.EventsEnabled, Is.False);
}
[Test]
public void Events()
{
var obj = new object ();
var ev = new Mock<IEventInfo> ();
ev.SetupGet (e => e.Name).Returns ("name");
var editor = new Mock<IObjectEditor> ();
editor.SetupGet (e => e.Properties).Returns (new IPropertyInfo[0]);
var eeditor = editor.As<IObjectEventEditor> ();
eeditor.SetupGet (e => e.Events).Returns (new[] { ev.Object });
var provider = new Mock<IEditorProvider> ();
provider.Setup (p => p.GetObjectEditorAsync (obj)).ReturnsAsync (editor.Object);
var vm = CreateVm (provider.Object);
Assume.That (vm.EventsEnabled, Is.False);
bool changed = false;
vm.PropertyChanged += (o, e) => {
if (e.PropertyName == nameof (PropertiesViewModel.EventsEnabled))
changed = true;
};
vm.SelectedObjects.Add (obj);
Assert.That (vm.EventsEnabled, Is.True);
Assert.That (changed, Is.True);
Assert.That (vm.Events.Count, Is.EqualTo (1));
Assert.That (vm.Events[0].Event, Is.SameAs (ev.Object));
}
[Test]
[Description ("Currently we just clear the events list if multiple objects are selected regardless of typ")]
public void MultipleObjectEvents ()
{
var obj = new object();
var obj2 = new object();
var ev = new Mock<IEventInfo> ();
ev.SetupGet (e => e.Name).Returns ("name");
var editor = new Mock<IObjectEditor> ();
editor.SetupGet (e => e.Properties).Returns (new IPropertyInfo[0]);
var eeditor = editor.As<IObjectEventEditor> ();
eeditor.SetupGet (e => e.Events).Returns (new[] { ev.Object });
var editor2 = new Mock<IObjectEditor> ();
editor2.SetupGet (e => e.Properties).Returns (new IPropertyInfo[0]);
var eeditor2 = editor.As<IObjectEventEditor> ();
eeditor2.SetupGet (e => e.Events).Returns (new[] { ev.Object });
var provider = new Mock<IEditorProvider> ();
provider.Setup (p => p.GetObjectEditorAsync (obj)).ReturnsAsync (editor.Object);
provider.Setup (p => p.GetObjectEditorAsync (obj2)).ReturnsAsync (editor2.Object);
var vm = CreateVm (provider.Object);
vm.SelectedObjects.Add (obj);
Assume.That (vm.EventsEnabled, Is.True);
Assume.That (vm.Events.Count, Is.EqualTo (1));
vm.SelectedObjects.Add (obj2);
Assert.That (vm.Events.Count, Is.EqualTo (0));
}
internal abstract PropertiesViewModel CreateVm (IEditorProvider provider);
}
} | 29.939655 | 110 | 0.675209 | [
"MIT"
] | Acidburn0zzz/Xamarin.PropertyEditing | Xamarin.PropertyEditing.Tests/PropertiesViewModelTests.cs | 13,894 | 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.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Features.RQName.Nodes;
namespace Microsoft.CodeAnalysis.Features.RQName
{
internal static class RQNodeBuilder
{
/// <summary>
/// Builds the RQName for a given symbol.
/// </summary>
/// <returns>The node if it could be created, otherwise null</returns>
public static UnresolvedRQNode Build(ISymbol symbol)
{
switch (symbol.Kind)
{
case SymbolKind.Namespace:
return BuildNamespace(symbol as INamespaceSymbol);
case SymbolKind.NamedType:
return BuildNamedType(symbol as INamedTypeSymbol);
case SymbolKind.Method:
return BuildMethod(symbol as IMethodSymbol);
case SymbolKind.Field:
return BuildField(symbol as IFieldSymbol);
case SymbolKind.Event:
return BuildEvent(symbol as IEventSymbol);
case SymbolKind.Property:
return BuildProperty(symbol as IPropertySymbol);
default:
return null;
}
}
private static RQNamespace BuildNamespace(INamespaceSymbol @namespace)
{
return new RQNamespace(RQNodeBuilder.GetNameParts(@namespace));
}
private static IList<string> GetNameParts(INamespaceSymbol @namespace)
{
var parts = new List<string>();
if (@namespace == null)
{
return parts;
}
while (!@namespace.IsGlobalNamespace)
{
parts.Add(@namespace.Name);
@namespace = @namespace.ContainingNamespace;
}
parts.Reverse();
return parts;
}
private static RQUnconstructedType BuildNamedType(INamedTypeSymbol type)
{
// Anything that is a valid RQUnconstructed types is ALWAYS safe for public APIs
if (type == null)
{
return null;
}
// Anonymous types are unsupported
if (type.IsAnonymousType)
{
return null;
}
// the following types are supported for BuildType() used in signatures, but are not supported
// for UnconstructedTypes
if (type != type.ConstructedFrom || type.SpecialType == SpecialType.System_Void)
{
return null;
}
// make an RQUnconstructedType
var namespaceNames = RQNodeBuilder.GetNameParts(@type.ContainingNamespace);
var typeInfos = new List<RQUnconstructedTypeInfo>();
for (var currentType = type; currentType != null; currentType = currentType.ContainingType)
{
typeInfos.Insert(0, new RQUnconstructedTypeInfo(currentType.Name, currentType.TypeParameters.Length));
}
return new RQUnconstructedType(namespaceNames, typeInfos);
}
private static RQMember BuildField(IFieldSymbol symbol)
{
var containingType = BuildNamedType(symbol.ContainingType);
if (containingType == null)
{
return null;
}
return new RQMemberVariable(containingType, symbol.Name);
}
private static RQProperty BuildProperty(IPropertySymbol symbol)
{
RQMethodPropertyOrEventName name = symbol.IsIndexer ?
RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryIndexerName() :
RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryPropertyName(symbol.Name);
if (symbol.ExplicitInterfaceImplementations.Any())
{
if (symbol.ExplicitInterfaceImplementations.Length > 1)
{
return null;
}
name = new RQExplicitInterfaceMemberName(
BuildType(symbol.ExplicitInterfaceImplementations.Single().ContainingType as ITypeSymbol),
(RQOrdinaryMethodPropertyOrEventName)name);
}
var containingType = BuildNamedType(symbol.ContainingType);
if (containingType == null)
{
return null;
}
var parameterList = BuildParameterList(symbol.Parameters);
return new RQProperty(containingType, name, typeParameterCount: 0, parameters: parameterList);
}
private static IList<RQParameter> BuildParameterList(ImmutableArray<IParameterSymbol> parameters)
{
var parameterList = new List<RQParameter>();
foreach (var parameter in parameters)
{
var parameterType = BuildType(parameter.Type);
if (parameter.RefKind == RefKind.Out)
{
parameterList.Add(new RQOutParameter(parameterType));
}
else if (parameter.RefKind == RefKind.Ref)
{
parameterList.Add(new RQRefParameter(parameterType));
}
else
{
parameterList.Add(new RQNormalParameter(parameterType));
}
}
return parameterList;
}
private static RQEvent BuildEvent(IEventSymbol symbol)
{
var containingType = BuildNamedType(symbol.ContainingType);
if (containingType == null)
{
return null;
}
RQMethodPropertyOrEventName name = RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryEventName(symbol.Name);
if (symbol.ExplicitInterfaceImplementations.Any())
{
if (symbol.ExplicitInterfaceImplementations.Length > 1)
{
return null;
}
name = new RQExplicitInterfaceMemberName(BuildType(symbol.ExplicitInterfaceImplementations.Single().ContainingType as ITypeSymbol), (RQOrdinaryMethodPropertyOrEventName)name);
}
return new RQEvent(containingType, name);
}
private static RQMethod BuildMethod(IMethodSymbol symbol)
{
if (symbol.MethodKind == MethodKind.UserDefinedOperator ||
symbol.MethodKind == MethodKind.BuiltinOperator ||
symbol.MethodKind == MethodKind.EventAdd ||
symbol.MethodKind == MethodKind.EventRemove ||
symbol.MethodKind == MethodKind.PropertySet ||
symbol.MethodKind == MethodKind.PropertyGet)
{
return null;
}
RQMethodPropertyOrEventName name;
if (symbol.MethodKind == MethodKind.Constructor)
{
name = RQOrdinaryMethodPropertyOrEventName.CreateConstructorName();
}
else if (symbol.MethodKind == MethodKind.Destructor)
{
name = RQOrdinaryMethodPropertyOrEventName.CreateDestructorName();
}
else
{
name = RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryMethodName(symbol.Name);
}
if (symbol.ExplicitInterfaceImplementations.Any())
{
if (symbol.ExplicitInterfaceImplementations.Length > 1)
{
return null;
}
name = new RQExplicitInterfaceMemberName(BuildType(symbol.ExplicitInterfaceImplementations.Single().ContainingType as ITypeSymbol), (RQOrdinaryMethodPropertyOrEventName)name);
}
var containingType = BuildNamedType(symbol.ContainingType);
if (containingType == null)
{
return null;
}
var typeParamCount = symbol.TypeParameters.Length;
var parameterList = BuildParameterList(symbol.Parameters);
return new RQMethod(containingType, name, typeParamCount, parameterList);
}
private static RQType BuildType(ITypeSymbol symbol)
{
if (symbol.IsAnonymousType)
{
return null;
}
if (symbol.SpecialType == SpecialType.System_Void)
{
return RQVoidType.Singleton;
}
else if (symbol.TypeKind == TypeKind.Pointer)
{
return new RQPointerType(BuildType((symbol as IPointerTypeSymbol).PointedAtType));
}
else if (symbol.TypeKind == TypeKind.Array)
{
return new RQArrayType((symbol as IArrayTypeSymbol).Rank, BuildType((symbol as IArrayTypeSymbol).ElementType));
}
else if (symbol.TypeKind == TypeKind.TypeParameter)
{
return new RQTypeVariableType(symbol.Name);
}
else if (symbol.TypeKind == TypeKind.Unknown)
{
return new RQErrorType(symbol.Name);
}
else if (symbol.TypeKind == TypeKind.Dynamic)
{
// NOTE: Because RQNames were defined as an interchange format before C# had "dynamic", and we didn't want
// all consumers to have to update their logic to crack the attributes about whether something is object or
// not, we just erase dynamic to object here.
return RQType.ObjectType;
}
else if (symbol.Kind == SymbolKind.NamedType || symbol.Kind == SymbolKind.ErrorType)
{
var namedTypeSymbol = symbol as INamedTypeSymbol;
var definingType = namedTypeSymbol.ConstructedFrom != null ? namedTypeSymbol.ConstructedFrom : namedTypeSymbol;
var typeChain = new List<INamedTypeSymbol>();
var type = namedTypeSymbol;
typeChain.Add(namedTypeSymbol);
while (type.ContainingType != null)
{
type = type.ContainingType;
typeChain.Add(type);
}
typeChain.Reverse();
var typeArgumentList = new List<RQType>();
foreach (var entry in typeChain)
{
foreach (var typeArgument in entry.TypeArguments)
{
typeArgumentList.Add(BuildType(typeArgument));
}
}
var containingType = BuildNamedType(definingType);
if (containingType == null)
{
return null;
}
return new RQConstructedType(containingType, typeArgumentList);
}
else
{
return null;
}
}
}
}
| 35.593651 | 191 | 0.559222 | [
"Apache-2.0"
] | JeremyKuhne/roslyn | src/Features/Core/Portable/RQName/RQNodeBuilder.cs | 11,214 | C# |
using System.Windows.Controls;
namespace One.Control.Controls.Dragablz
{
public class VerticalPositionMonitor : StackPositionMonitor
{
public VerticalPositionMonitor() : base(Orientation.Vertical)
{
}
}
}
| 20.25 | 69 | 0.687243 | [
"MIT"
] | KleinPan/One | One.Control/Controls/Dragablz/VerticalPositionMonitor.cs | 245 | C# |
using UnityEngine;
using System.Collections;
//REV: I HAVE DONE THE WORK UPTO VIDEO S03_019 29/11/30
public class TP_Camera : MonoBehaviour
{
public static TP_Camera Instance;
public Transform TargetLookAt ;
public float Distance = 5.0f;
public float DistanceMin = 3.0f;
public float DistanceMax = 10.0f;
public float DistanceSmooth = 0.05f;
public float DistanceResumeSmooth =1f;
public float X_MouseSensitivity = 5f;
public float Y_MouseSensitivity = 5f;
public float MouseWheelSensitivity = 5f;
public float X_Smooth = 0.05f;
public float Y_Smooth = 0.1f;
public float Y_MinLimit = -40f;
public float Y_MaxLimit = 80f;
public float OcclusionDistanceStep = 0.5f;
public int MaxOcclusionChecks = 10;
private float mouseX = 0f;
private float mouseY = 0f;
private float velX = 0;
private float velY = 0;
private float velZ = 0;
private float velDistance = 0f;
private float startDistance = 0f;
private Vector3 position = Vector3.zero;
private Vector3 desiredPosition = Vector3.zero;
private float desiredDistance = 0f;
private float distanceSmooth =0f;
private float preOccludedDistance=0f;
void Awake ()
{
Instance = this;
}
void Start ()
{
Distance = Mathf.Clamp (Distance, DistanceMin, DistanceMax);
startDistance = Distance;
Reset ();
}
void LateUpdate ()
{
if (TargetLookAt == null)
return;
HandlePlayerInput ();
var count = 0;
do
{
CalculateDesiredPosition();
count ++;
} while (CheckIfOccluded(count));
// CheckCameraPoints (TargetLookAt.position, desiredPosition); not wanted eventually
UpdatePosition ();
}
void HandlePlayerInput ()
{
var deadZone = 0.001f;
//RMB right mouse button
if (Input.GetMouseButton (1)) {
//The RMB is down, get mouse axis input
mouseX += Input.GetAxis ("Mouse X") * X_MouseSensitivity;
mouseY -= Input.GetAxis ("Mouse Y") * Y_MouseSensitivity;
// note the inversion by subtraction -=
}
// This is where we limit mouseY rotation
mouseY = Helper.ClampAngle (mouseY, Y_MinLimit, Y_MaxLimit);
if (Input.GetAxis ("Mouse ScrollWheel") < -deadZone || Input.GetAxis ("Mouse ScrollWheel") > deadZone) {
desiredDistance = Mathf.Clamp (Distance - Input.GetAxis ("Mouse ScrollWheel") * MouseWheelSensitivity, DistanceMin, DistanceMax);
preOccludedDistance = Distance;
distanceSmooth = DistanceSmooth;
}
// float t = 0f;
// t = Input.GetAxis ("Mouse ScrollWheel");
//Debug.Log ("Mouse ScrollWheel= " + t);
}
void CalculateDesiredPosition ()
{
//Evaluate Distance
ResetDesiredDistance();
Distance = Mathf.SmoothDamp (Distance, desiredDistance, ref velDistance, distanceSmooth);
//Calculate desired position
desiredPosition = CalculatePosition (mouseY, mouseX, Distance);
//note reversals
}
Vector3 CalculatePosition (float rotationX, float rotationY, float distance)
{
Vector3 direction = new Vector3 (0, 0, -distance);
//-ve distance points behind camera
Quaternion rotation = Quaternion.Euler (rotationX, rotationY, 0);
return TargetLookAt.position + (rotation * direction);
}
bool CheckIfOccluded (int count)
{
var isOccluded = false;
var nearestDistance = CheckCameraPoints (TargetLookAt.position, desiredPosition);
if (nearestDistance != -1) {
if (count < MaxOcclusionChecks)
{
isOccluded = true;
Distance -= OcclusionDistanceStep;
if (Distance < 0.8f)//.25 ORI test for shudder
Distance = 0.8f;//.25 ORI
}
else
Distance = nearestDistance - Camera.main.nearClipPlane;
desiredDistance = Distance;
distanceSmooth = DistanceResumeSmooth;
}
return isOccluded;
}
float CheckCameraPoints (Vector3 fromm, Vector3 to)
{
var nearestDistance = -1f;
RaycastHit hitInfo;
Helper.ClipPlanePoints clipPlanePoints = Helper.ClipPlaneAtNear (to);
// Draw lines in the editor to make it easier to visual
Debug.DrawLine (fromm, to + transform.forward * -GetComponent<Camera>().nearClipPlane, Color.red);
//centreline
Debug.DrawLine (fromm, clipPlanePoints.UpperLeft);
Debug.DrawLine (fromm, clipPlanePoints.LowerLeft);
Debug.DrawLine (fromm, clipPlanePoints.UpperRight);
Debug.DrawLine (fromm, clipPlanePoints.LowerRight);
//box it in
Debug.DrawLine (clipPlanePoints.LowerLeft, clipPlanePoints.UpperLeft);
Debug.DrawLine (clipPlanePoints.UpperLeft, clipPlanePoints.UpperRight);
Debug.DrawLine (clipPlanePoints.UpperRight, clipPlanePoints.LowerRight);
Debug.DrawLine (clipPlanePoints.LowerRight, clipPlanePoints.LowerLeft);
//
if (Physics.Linecast (fromm, clipPlanePoints.UpperLeft, out hitInfo) && hitInfo.collider.tag != "Player")
nearestDistance = hitInfo.distance;
//
if (Physics.Linecast (fromm, clipPlanePoints.UpperLeft, out hitInfo) && hitInfo.collider.tag != "Player")
if (hitInfo.distance < nearestDistance || nearestDistance == -1)
nearestDistance = hitInfo.distance;
if (Physics.Linecast (fromm, clipPlanePoints.LowerLeft, out hitInfo) && hitInfo.collider.tag != "Player")
if (hitInfo.distance < nearestDistance || nearestDistance == -1)
nearestDistance = hitInfo.distance;
//
if (Physics.Linecast (fromm, clipPlanePoints.LowerRight, out hitInfo) && hitInfo.collider.tag != "Player")
if (hitInfo.distance < nearestDistance || nearestDistance == -1)
nearestDistance = hitInfo.distance;
if (Physics.Linecast (fromm, clipPlanePoints.UpperRight, out hitInfo) && hitInfo.collider.tag != "Player")
if (hitInfo.distance < nearestDistance || nearestDistance == -1)
nearestDistance = hitInfo.distance;
if (Physics.Linecast (fromm, to + transform.forward * -GetComponent<Camera>().nearClipPlane, out hitInfo) && hitInfo.collider.tag != "Player")
if (hitInfo.distance < nearestDistance || nearestDistance == -1)
nearestDistance = hitInfo.distance;
return nearestDistance;
}
void ResetDesiredDistance()
{
if(desiredDistance < preOccludedDistance)
{
var pos= CalculatePosition(mouseY,mouseX,preOccludedDistance);
var nearestDistance = CheckCameraPoints(TargetLookAt.position,pos);
if(nearestDistance == -1 || nearestDistance > preOccludedDistance)
{
desiredDistance =preOccludedDistance;
}
}
}
void UpdatePosition ()
{
var posX = Mathf.SmoothDamp (position.x, desiredPosition.x, ref velX, X_Smooth);
var posY = Mathf.SmoothDamp (position.y, desiredPosition.y, ref velY, Y_Smooth);
var posZ = Mathf.SmoothDamp (position.z, desiredPosition.z, ref velZ, X_Smooth);
//X_Smooth is correct
position = new Vector3 (posX, posY, posZ);
transform.position = position;
transform.LookAt (TargetLookAt);
}
public void Reset ()
{
mouseX = 0;
mouseY = 10;
Distance = startDistance;
desiredDistance = Distance;
preOccludedDistance =Distance;
}
public static void UseExistingOrCreateMainCamera ()
{
GameObject tempCamera;
GameObject targetLookAt;
TP_Camera myCamera;
if (Camera.main != null) {
tempCamera = Camera.main.gameObject;
} else {
tempCamera = new GameObject ("Main Camera");
tempCamera.AddComponent <Camera>();
tempCamera.tag = "MainCamera";
tempCamera.AddComponent <TP_Camera>();
}
myCamera = tempCamera.GetComponent ("TP_Camera") as TP_Camera;
targetLookAt = GameObject.Find ("targetLookAt") as GameObject;
if (targetLookAt == null) {
targetLookAt = new GameObject ("targetLookAt");
targetLookAt.transform.position = Vector3.zero;
}
myCamera.TargetLookAt = targetLookAt.transform;
}
}
| 30.707819 | 144 | 0.722997 | [
"MIT"
] | perthboy/UnityBase | Assets/_MyScripts/TP_Camera.cs | 7,462 | C# |
namespace ChinazoCP.Data;
[SingletonGame]
[AutoReset] //usually needs reset
public class ChinazoGameContainer : CardGameContainer<ChinazoCard, ChinazoPlayerItem, ChinazoSaveInfo>
{
public ChinazoGameContainer(BasicData basicData,
TestOptions test,
IGameInfo gameInfo,
IAsyncDelayer delay,
IEventAggregator aggregator,
CommandContainer command,
IGamePackageResolver resolver,
IListShuffler<ChinazoCard> deckList,
IRandomGenerator random) : base(basicData, test, gameInfo, delay, aggregator, command, resolver, deckList, random)
{
}
internal Action<BasicList<ChinazoCard>>? ModifyCards { get; set; }
} | 37.722222 | 122 | 0.731959 | [
"MIT"
] | musictopia2/GamingPackXV3 | CP/Games/ChinazoCP/Data/ChinazoGameContainer.cs | 679 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Sannel.House.SensorLogging.Data.Migrations.SqlServer.Migrations
{
public partial class Inital : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "SensorEntries",
columns: table => new
{
SensorEntryId = table.Column<Guid>(nullable: false),
DeviceId = table.Column<int>(nullable: false),
SensorType = table.Column<int>(nullable: false),
CreationDate = table.Column<DateTime>(nullable: false),
Values = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_SensorEntries", x => x.SensorEntryId);
});
migrationBuilder.CreateIndex(
name: "IX_SensorEntries_DeviceId",
table: "SensorEntries",
column: "DeviceId");
migrationBuilder.CreateIndex(
name: "IX_SensorEntries_SensorType",
table: "SensorEntries",
column: "SensorType");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "SensorEntries");
}
}
}
| 34.186047 | 79 | 0.544218 | [
"Apache-2.0"
] | Sannel/Sannel.House.SensorEntries | src/Migrations/Sannel.House.SensorLogging.Data.Migrations.SqlServer/Migrations/20190104044602_Inital.cs | 1,472 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Inventors.ECP.Profiling
{
public class TimingViolation :
Record
{
public TimingViolation(UInt32 signal, double elapsedTime, double timeLimit, UInt32 context)
{
Signal = signal;
ElapsedTime = elapsedTime;
TimeLimit = timeLimit;
Context = context;
}
public UInt32 Signal { get; }
public UInt32 Context { get; }
public double ElapsedTime { get; }
public double TimeLimit { get; }
}
}
| 22 | 99 | 0.617555 | [
"MIT"
] | Inventors-Way/Inventors.ECP | Inventors.ECP/Profiling/TimingViolation.cs | 640 | C# |
/*
* Dyspatch API
*
* # Introduction The Dyspatch API is based on the REST paradigm, and features resource based URLs with standard HTTP response codes to indicate errors. We use standard HTTP authentication and request verbs, and all responses are JSON formatted. See our [Implementation Guide](https://docs.dyspatch.io/development/implementing_dyspatch/) for more details on how to implement Dyspatch. ## API Client Libraries Dyspatch provides API Clients for popular languages and web frameworks. - [Java](https://github.com/getdyspatch/dyspatch-java) - [Javascript](https://github.com/getdyspatch/dyspatch-javascript) - [Python](https://github.com/getdyspatch/dyspatch-python) - [C#](https://github.com/getdyspatch/dyspatch-dotnet) - [Go](https://github.com/getdyspatch/dyspatch-golang) - [Ruby](https://github.com/getdyspatch/dyspatch-ruby)
*
* The version of the OpenAPI document: 2020.11
* Contact: support@dyspatch.io
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = IO.Dyspatch.Client.OpenAPIDateConverter;
namespace IO.Dyspatch.Model
{
/// <summary>
/// draft metadata
/// </summary>
[DataContract]
public partial class DraftMetaRead : IEquatable<DraftMetaRead>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="DraftMetaRead" /> class.
/// </summary>
/// <param name="id">An opaque, unique identifier for a draft.</param>
/// <param name="templateId">An opaque, unique identifier for a template.</param>
/// <param name="name">The name of a draft.</param>
/// <param name="url">The API url for a specific draft.</param>
/// <param name="createdAt">The time of initial creation.</param>
/// <param name="updatedAt">The time of last update.</param>
public DraftMetaRead(string id = default(string), string templateId = default(string), string name = default(string), string url = default(string), DateTimeOffset createdAt = default(DateTimeOffset), DateTimeOffset updatedAt = default(DateTimeOffset))
{
this.Id = id;
this.TemplateId = templateId;
this.Name = name;
this.Url = url;
this.CreatedAt = createdAt;
this.UpdatedAt = updatedAt;
}
/// <summary>
/// An opaque, unique identifier for a draft
/// </summary>
/// <value>An opaque, unique identifier for a draft</value>
[DataMember(Name="id", EmitDefaultValue=false)]
public string Id { get; set; }
/// <summary>
/// An opaque, unique identifier for a template
/// </summary>
/// <value>An opaque, unique identifier for a template</value>
[DataMember(Name="templateId", EmitDefaultValue=false)]
public string TemplateId { get; set; }
/// <summary>
/// The name of a draft
/// </summary>
/// <value>The name of a draft</value>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// The API url for a specific draft
/// </summary>
/// <value>The API url for a specific draft</value>
[DataMember(Name="url", EmitDefaultValue=false)]
public string Url { get; set; }
/// <summary>
/// The time of initial creation
/// </summary>
/// <value>The time of initial creation</value>
[DataMember(Name="createdAt", EmitDefaultValue=false)]
public DateTimeOffset CreatedAt { get; set; }
/// <summary>
/// The time of last update
/// </summary>
/// <value>The time of last update</value>
[DataMember(Name="updatedAt", EmitDefaultValue=false)]
public DateTimeOffset UpdatedAt { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class DraftMetaRead {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" TemplateId: ").Append(TemplateId).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Url: ").Append(Url).Append("\n");
sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n");
sb.Append(" UpdatedAt: ").Append(UpdatedAt).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as DraftMetaRead);
}
/// <summary>
/// Returns true if DraftMetaRead instances are equal
/// </summary>
/// <param name="input">Instance of DraftMetaRead to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(DraftMetaRead input)
{
if (input == null)
return false;
return
(
this.Id == input.Id ||
(this.Id != null &&
this.Id.Equals(input.Id))
) &&
(
this.TemplateId == input.TemplateId ||
(this.TemplateId != null &&
this.TemplateId.Equals(input.TemplateId))
) &&
(
this.Name == input.Name ||
(this.Name != null &&
this.Name.Equals(input.Name))
) &&
(
this.Url == input.Url ||
(this.Url != null &&
this.Url.Equals(input.Url))
) &&
(
this.CreatedAt == input.CreatedAt ||
(this.CreatedAt != null &&
this.CreatedAt.Equals(input.CreatedAt))
) &&
(
this.UpdatedAt == input.UpdatedAt ||
(this.UpdatedAt != null &&
this.UpdatedAt.Equals(input.UpdatedAt))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Id != null)
hashCode = hashCode * 59 + this.Id.GetHashCode();
if (this.TemplateId != null)
hashCode = hashCode * 59 + this.TemplateId.GetHashCode();
if (this.Name != null)
hashCode = hashCode * 59 + this.Name.GetHashCode();
if (this.Url != null)
hashCode = hashCode * 59 + this.Url.GetHashCode();
if (this.CreatedAt != null)
hashCode = hashCode * 59 + this.CreatedAt.GetHashCode();
if (this.UpdatedAt != null)
hashCode = hashCode * 59 + this.UpdatedAt.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 40.509434 | 830 | 0.560899 | [
"Apache-2.0"
] | getdyspatch/dyspatch-dotnet | src/IO.Dyspatch/Model/DraftMetaRead.cs | 8,588 | C# |
using Microsoft.AspNetCore.Mvc;
namespace AdminLte.TagHelpers.Demo.Pages.Shared.Components.HeaderLeft
{
public class HeaderLeftViewComponent : ViewComponent
{
public IViewComponentResult Invoke() => View();
}
} | 25.777778 | 69 | 0.741379 | [
"MIT"
] | iyilm4z/admin-lte-dotnet | src/AdminLte.TagHelpers.Demo/Pages/Shared/Components/HeaderLeft/HeaderLeftViewComponent.cs | 234 | C# |
using System;
using Vortice.Direct3D12;
using Vortice.Mathematics;
namespace Veldrid.D3D12
{
internal class D3D12Sampler : Sampler
{
private string _name;
public ID3D12SamplerState DeviceSampler { get; }
public D3D12Sampler(ID3D12Device device, ref SamplerDescription description)
{
ComparisonFunction comparision = description.ComparisonKind == null ? ComparisonFunction.Never : D3D12Formats.VdToD3D11ComparisonFunc(description.ComparisonKind.Value);
Vortice.Direct3D12.SamplerDescription samplerStateDesc = new Vortice.Direct3D12.SamplerDescription
{
AddressU = D3D12Formats.VdToD3D11AddressMode(description.AddressModeU),
AddressV = D3D12Formats.VdToD3D11AddressMode(description.AddressModeV),
AddressW = D3D12Formats.VdToD3D11AddressMode(description.AddressModeW),
Filter = D3D12Formats.ToD3D11Filter(description.Filter, description.ComparisonKind.HasValue),
MinLOD = description.MinimumLod,
MaxLOD = description.MaximumLod,
MaxAnisotropy = (int)description.MaximumAnisotropy,
ComparisonFunction = comparision,
MipLODBias = description.LodBias,
BorderColor = ToRawColor4(description.BorderColor)
};
DeviceSampler = device.CreateSamplerState(samplerStateDesc);
}
private static Color4 ToRawColor4(SamplerBorderColor borderColor)
{
switch (borderColor)
{
case SamplerBorderColor.TransparentBlack:
return new Color4(0, 0, 0, 0);
case SamplerBorderColor.OpaqueBlack:
return new Color4(0, 0, 0, 1);
case SamplerBorderColor.OpaqueWhite:
return new Color4(1, 1, 1, 1);
default:
throw Illegal.Value<SamplerBorderColor>();
}
}
public override string Name
{
get => _name;
set
{
_name = value;
DeviceSampler.DebugName = value;
}
}
public override bool IsDisposed => DeviceSampler.NativePointer == IntPtr.Zero;
public override void Dispose()
{
DeviceSampler.Dispose();
}
}
}
| 36.363636 | 180 | 0.605 | [
"MIT"
] | TeamStriked/striked3d | thirtparty/veldrid/Veldrid/D3D12/D3D12Sampler.cs | 2,402 | C# |
namespace Fonet.Fo.Properties
{
internal class CharacterMaker : CharacterProperty.Maker
{
new public static PropertyMaker Maker(string propName)
{
return new CharacterMaker(propName);
}
protected CharacterMaker(string name) : base(name) { }
public override bool IsInherited()
{
return false;
}
private Property m_defaultProp = null;
public override Property Make(PropertyList propertyList)
{
if (m_defaultProp == null)
{
m_defaultProp = Make(propertyList, "none", propertyList.getParentFObj());
}
return m_defaultProp;
}
}
} | 23.193548 | 89 | 0.573018 | [
"Apache-2.0"
] | DaveDezinski/Fo.Net | src/Fo/Properties/CharacterMaker.cs | 719 | C# |
/*
* Original author: Brian Pratt <bspratt .at. proteinms.net>,
* MacCoss Lab, Department of Genome Sciences, UW
*
* Copyright 2014 University of Washington - Seattle, WA
*
* 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 C:\proj\pwiz\pwiz\pwiz_tools\Skyline\Model\Lib\Library.csKIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace pwiz.Skyline.Model.IonMobility
{
public class DbVersionInfo
{
/*
CREATE TABLE VersionInfo (
SchemaVersion INT
)
*/
public virtual int SchemaVersion { get; set; }
}
}
| 33.90625 | 133 | 0.666359 | [
"Apache-2.0"
] | austinkeller/pwiz | pwiz_tools/Skyline/Model/IonMobility/DbVersionInfo.cs | 1,087 | C# |
using System;
namespace Grauenwolf.TravellerTools.Characters
{
public static class PatronBuilder
{
public static string PickAlliesAndEnemies(Dice dice)
{
if (dice == null)
throw new ArgumentNullException(nameof(dice), $"{nameof(dice)} is null.");
switch (dice.D66())
{
case 11: return "Naval Officer";
case 12: return "Imperial Diplomat";
case 13: return "Crooked Trader";
case 14: return "Medical Doctor";
case 15: return "Eccentric Scientist";
case 16: return "Mercenary";
case 21: return "Famous Performer";
case 22: return "Alien Thief";
case 23: return "Free Trader";
case 24: return "Explorer";
case 25: return "Marine Captain";
case 26: return "Corporate Executive";
case 31: return "Researcher";
case 32: return "Cultural Attaché";
case 33: return "Religious Leader";
case 34: return "Conspirator";
case 35: return "Rich Noble";
case 36: return "Artificial Intelligence";
case 41: return "Bored Noble";
case 42: return "Planetary Governor";
case 43: return "Inveterate Gambler";
case 44: return "Crusading Journalist";
case 45: return "Doomsday Cultist";
case 46: return "Corporate Agent";
case 51: return "Criminal Syndicate";
case 52: return "Military Governor";
case 53: return "Army Quartermaster";
case 54: return "Private Investigator";
case 55: return "Starport Administrator";
case 56: return "Retired Admiral";
case 61: return "Alien Ambassador";
case 62: return "Smuggler";
case 63: return "Weapons Inspector";
case 64: return "Elder Statesman";
case 65: return "Planetary Warlord";
case 66: return "Imperial Agent";
}
return "";
}
public static string PickMission(Dice dice)
{
if (dice == null)
throw new ArgumentNullException(nameof(dice), $"{nameof(dice)} is null.");
switch (dice.D66())
{
case 11: return "Assassinate a " + PickTarget(dice);
case 12: return "Frame a " + PickTarget(dice);
case 13: return "Destroy a " + PickTarget(dice);
case 14: return "Steal from a " + PickTarget(dice);
case 15: return "Aid in a burglary";
case 16: return "Stop a burglary";
case 21: return "Retrieve data or an object from a secure facility";
case 22: return "Discredit a " + PickTarget(dice);
case 23: return "Find a lost cargo";
case 24: return "Find a lost person";
case 25: return "Deceive a " + PickTarget(dice);
case 26: return "Sabotage a " + PickTarget(dice);
case 31: return "Transport goods";
case 32: return "Transport a person";
case 33: return "Transport data";
case 34: return "Transport goods secretly";
case 35: return "Transport goods quickly";
case 36: return "Transport dangerous goods";
case 41: return "Investigate a crime";
case 42: return "Investigate a theft";
case 43: return "Investigate a murder";
case 44: return "Investigate a mystery";
case 45: return "Investigate a " + PickTarget(dice);
case 46: return "Investigate an event";
case 51: return "Join an expedition";
case 52: return "Survey a planet";
case 53: return "Explore a new system";
case 54: return "Explore a ruin";
case 55: return "Salvage a ship";
case 56: return "Capture a creature";
case 61: return "Hijack a ship";
case 62: return "Entertain a noble";
case 63: return "Protect a " + PickTarget(dice);
case 64: return "Save a " + PickTarget(dice);
case 65: return "Aid a " + PickTarget(dice);
case 66: return "It is a trap – the Patron intends to betray the Traveller. Fake mission: " + PickMission(dice);
}
return "";
}
public static string PickPatron(Dice dice)
{
if (dice == null)
throw new ArgumentNullException(nameof(dice), $"{nameof(dice)} is null.");
switch (dice.D66())
{
case 11: return "Assassin";
case 12: return "Smuggler";
case 13: return "Terrorist";
case 14: return "Embezzler";
case 15: return "Thief";
case 16: return "Revolutionary";
case 21: return "Clerk";
case 22: return "Administrator";
case 23: return "Mayor";
case 24: return "Minor Noble";
case 25: return "Physician";
case 26: return "Tribal Leader";
case 31: return "Diplomat";
case 32: return "Courier";
case 33: return "Spy";
case 34: return "Ambassador";
case 35: return "Noble";
case 36: return "Police Officer";
case 41: return "Merchant";
case 42: return "Free Trader";
case 43: return "Broker";
case 44: return "Corporate Executive";
case 45: return "Corporate Agent";
case 46: return "Financier";
case 51: return "Belter";
case 52: return "Researcher";
case 53: return "Naval Officer";
case 54: return "Pilot";
case 55: return "Starport Administrator";
case 56: return "Scout";
case 61: return "Alien";
case 62: return "Playboy";
case 63: return "Stowaway";
case 64: return "Family Relative";
case 65: return "Agent of a Foreign Power";
case 66: return "Imperial Agent";
}
return "";
}
public static string PickTarget(Dice dice)
{
if (dice == null)
throw new ArgumentNullException(nameof(dice), $"{nameof(dice)} is null.");
switch (dice.D66())
{
case 11: return "Common Trade Goods";
case 12: return "Common Trade Goods";
case 13: return "Random Trade Goods";
case 14: return "Random Trade Goods";
case 15: return "Illegal Trade Goods";
case 16: return "Illegal Trade Goods";
case 21: return "Computer Data";
case 22: return "Alien Artifact";
case 23: return "Personal Effects";
case 24: return "Work of Art";
case 25: return "Historical Artifact";
case 26: return "Weapon";
case 31: return "Starport";
case 32: return "Asteroid Base";
case 33: return "City";
case 34: return "Research station";
case 35: return "Bar or Nightclub";
case 36: return "Medical Facility";
case 41: case 42: case 43: return PickPatron(dice);
case 44: case 45: case 46: return PickAlliesAndEnemies(dice);
case 51: return "Local Government";
case 52: return "Planetary Government";
case 53: return "Corporation";
case 54: return "Imperial Intelligence";
case 55: return "Criminal Syndicate";
case 56: return "Criminal Gang";
case 61: return "Free Trader";
case 62: return "Yacht";
case 63: return "Cargo Hauler";
case 64: return "Police Cutter";
case 65: return "Space Station";
case 66: return "Warship";
}
return "";
}
//public class Patron
//{
// public string Mission { get; set; }
//}
}
} | 44.173469 | 128 | 0.500231 | [
"MIT"
] | Grauenwolf/TravellerTools | TravellerTools/Grauenwolf.TravellerTools.Shared/Characters/PatronBuilder.cs | 8,663 | 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("EntryPopCode.WinPhone81")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EntryPopCode.WinPhone81")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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")]
[assembly: ComVisible(false)] | 36.655172 | 84 | 0.745061 | [
"Apache-2.0"
] | NoleHealth/xamarin-forms-book-preview-2 | Chapter23/EntryPopCode/EntryPopCode/EntryPopCode.WinPhone81/Properties/AssemblyInfo.cs | 1,066 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
using Random = System.Random;
[Serializable]
public class ItemToPool {
public int amountToPool;
public GameObject objectToPool;
public bool shouldExpand;
}
/**
* <summary>
* Class <c>ManagerPool</c>
* <para>
* The Generic Object-Pool Managing Class. Is inherited by all sub-type
* Object-Poolers. Inherits from the ManagerGeneric <c>Class</c>
* </para>
* </summary>
*/
public abstract class ManagerPool : ManagerGeneric {
protected static List<GameObject> _pooledObjects = new List<GameObject>();
public List<ItemToPool> itemsToPool;
/**
* <summary>
* Function <c>Start</c>
* <para>
* Runs when the GameObject that this script is attached to is
* initialised. Creates the ObjectPools to be used by inheriting
* Classes. Also shuffles the order of the items in the Pool.
* </para>
* </summary>
*/
protected void Start() {
foreach (var item in itemsToPool)
for (var i = 0; i < item.amountToPool; i++) {
var obj = Instantiate(item.objectToPool);
obj.SetActive(false);
_pooledObjects.Add(obj);
}
// Shuffle the Items
_pooledObjects = Shuffle(_pooledObjects);
}
/**
* <summary>
* Function <c>Shuffle</c>
* <para>
* Randomises the order of items in a given list
* </para>
* <param name="list">A list of type T to be randomised</param>
* <typeparam name="T">The type stored by the list</typeparam>
* <returns>A list of type T with randomised order</returns>
* </summary>
*/
private List<T> Shuffle<T>(List<T> list) {
var rng = new Random();
var n = list.Count;
while (n > 1) {
n--;
var k = rng.Next(n + 1);
var value = list[k];
list[k] = list[n];
list[n] = value;
}
return list;
}
/**
* <summary>
* Function <c>GetPooledObject</c>
* <para>
* Retrieves a specific family of Object from the Object-Pooler
* </para>
* <param name="requestTag">A <c>tag</c> to specify the family of item that
* should be retrieved from the Pool</param>
* <returns>A GameObject of the specified family</returns>
* </summary>
*/
public GameObject GetPooledObject(string requestTag) {
if (_pooledObjects == null) return null;
foreach (var pObj in _pooledObjects)
if (!pObj.activeInHierarchy && pObj.CompareTag(requestTag))
return pObj;
foreach (var item in itemsToPool)
if (item.objectToPool.CompareTag(requestTag))
if (item.shouldExpand) {
var obj = Instantiate(item.objectToPool);
obj.SetActive(false);
_pooledObjects.Add(obj);
return obj;
}
return null;
}
// protected void ShrinkPool<T>() {
// var activeItems = 0;
//
// foreach (var item in _pooledObjects)
// if (item.activeInHierarchy)
// activeItems++;
//
// float usedRatio = activeItems / _pooledObjects.Capacity;
//
// if (usedRatio > 0.7f)
// }
}
| 28.15 | 79 | 0.561871 | [
"MIT"
] | Renegade-Master/Unity_CrossPlatform_MobileAndPC_Game | MobileGame/Assets/Scripts/ManagerPool.cs | 3,380 | C# |
namespace Mellowood.Roles.Dto
{
public class FlatPermissionDto
{
public string Name { get; set; }
public string DisplayName { get; set; }
public string Description { get; set; }
}
} | 21.454545 | 47 | 0.567797 | [
"MIT"
] | Carben-dev/Mellowood | src/Mellowood.Application/Roles/Dto/FlatPermissionDto.cs | 238 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.