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 DragonSpark.Model.Sequences;
using System.Collections.Generic;
namespace DragonSpark.Compose.Extents.Commands;
public sealed class SequenceCommandExtent<T> : CommandExtent<IEnumerable<T>>
{
public static SequenceCommandExtent<T> Default { get; } = new SequenceCommandExtent<T>();
SequenceCommandExtent() {}
public CommandExtent<T[]> Array => DefaultCommandExtent<T[]>.Default;
public CommandExtent<Array<T>> Immutable => DefaultCommandExtent<Array<T>>.Default;
} | 31.866667 | 90 | 0.784519 | [
"MIT"
] | DragonSpark/Framework | DragonSpark/Compose/Extents/Commands/SequenceCommandExtent.cs | 480 | C# |
using UnityEngine;
namespace GameplayIngredients.Logic
{
[AddComponentMenu(ComponentMenu.logicPath + "Random Logic")]
[Callable("Logic", "Logic/ic-generic-logic.png")]
public class RandomLogic : LogicBase
{
public Callable[] RandomCalls;
public override void Execute(GameObject instigator = null)
{
int r = Random.Range(0, RandomCalls.Length);
Callable.Call(RandomCalls[r], instigator);
}
public override string GetDefaultName()
{
return $"Call One at Random...";
}
}
}
| 24.416667 | 66 | 0.614334 | [
"MIT"
] | UltraCombos/net.peeweek.gameplay-ingredients | Runtime/LevelScripting/Logic/RandomLogic.cs | 586 | C# |
using DevTools.Infrastructure.Models;
using System.Linq;
namespace DevTools.Application.Models.Dto
{
public class ProjectDto
{
public ProjectId Id { get; set; }
public string Name { get; set; }
public AddressDto[] Addresses { get; set; }
public ProjectDto(Project project)
{
Id = project.Id;
Name = project.Name;
Addresses = project.Addresses.Select(x => new AddressDto(x)).ToArray();
}
public ProjectDto()
{ }
}
}
| 23.086957 | 83 | 0.578154 | [
"MIT"
] | BorczGrzegorz/DevTools | DevTools.Application/Models/Dto/ProjectDto.cs | 533 | C# |
using System;
namespace Least_Squares_Method
{
class Sum
{
public double SumXFirstDegree(double[] xArray)
{
double sum = 0;
foreach (var elem in xArray)
{
sum += elem;
}
return sum;
}
public double SumXSquares(double[] xArray)
{
double sum = 0;
foreach (var elem in xArray)
{
sum += elem * elem;
}
return sum;
}
public double SumXCubes(double[] xArray)
{
double sum = 0;
foreach (var elem in xArray)
{
sum += elem * elem * elem;
}
return sum;
}
public double SumXFourthDegree(double[] xArray)
{
double sum = 0;
foreach (var elem in xArray)
{
sum += elem * elem * elem * elem;
}
return sum;
}
public double SumXMultY(double[] xArray, double[] yArray)
{
double sum = 0;
for (var i = 0; i < xArray.Length; i++)
{
sum += xArray[i] * yArray[i];
}
return sum;
}
public double SumSquareXMultY(double[] xArray, double[] yArray)
{
double sum = 0;
for (var i = 0; i < xArray.Length; i++)
{
sum += xArray[i] * xArray[i] * yArray[i];
}
return sum;
}
public double SumLogX(double[] xArray)
{
double sum = 0;
foreach (var elem in xArray)
{
sum += Math.Log(elem);
}
return sum;
}
public double SumLogXMultLogX(double[] xArray)
{
double sum = 0;
foreach (var elem in xArray)
{
sum += Math.Log(elem) * Math.Log(elem);
}
return sum;
}
public double SumYMultLogX(double[] xArray, double[] yArray)
{
double sum = 0;
for (var i = 0; i < xArray.Length; i++)
{
sum += (yArray[i] * Math.Log(xArray[i]));
}
return sum;
}
public double Sum1DevX(double[] xArray)
{
double sum = 0;
foreach (var elem in xArray)
{
sum += 1.0 / elem;
}
return sum;
}
public double Sum1DevXSquare(double[] xArray)
{
double sum = 0;
foreach (var elem in xArray)
{
sum += 1.0 / (elem * elem);
}
return sum;
}
public double SumYDevX(double[] xArray, double[] yArray)
{
double sum = 0;
for (var i = 0; i < xArray.Length; i++)
{
sum += yArray[i] / xArray[i];
}
return sum;
}
}
} | 24.015748 | 71 | 0.396721 | [
"MIT"
] | AlexeyShpavda/NumericalAnalysisMethods | Least Squares Method/Sum.cs | 3,052 | C# |
using System;
namespace Registration.Api.Requests
{
public class GetServiceItemsRequest : BaseRequest
{
public GetServiceItemsRequest()
{
}
public Registration.Domain.ReadModel.Program[] ProgramIds { get; set; }
public bool OnlineOnly { get; set; }
}
}
| 21.928571 | 79 | 0.641694 | [
"MIT"
] | Liang-Zhinian/CqrsFrameworkDotNet | Sample/Reservation/v1/Registration/Registration.Api/Requests/GetServiceItemsRequest.cs | 309 | C# |
namespace Alpha.Travel.Domain.Entities
{
using System;
public sealed class ApiClient : BaseEntity
{
public Guid ClientId { get; set; }
public string Name { get; set; }
}
} | 18.727273 | 46 | 0.616505 | [
"MIT"
] | SalZaki/AlphaTravel | Alpha.Travel.Domain/Entities/ApiClient.cs | 208 | C# |
using System;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace ISLA2.Areas.HelpPage.ModelDescriptions
{
internal static class ModelNameHelper
{
// Modify this to provide custom model name mapping.
public static string GetModelName(Type type)
{
ModelNameAttribute modelNameAttribute = type.GetCustomAttribute<ModelNameAttribute>();
if (modelNameAttribute != null && !String.IsNullOrEmpty(modelNameAttribute.Name))
{
return modelNameAttribute.Name;
}
string modelName = type.Name;
if (type.IsGenericType)
{
// Format the generic type name to something like: GenericOfAgurment1AndArgument2
Type genericType = type.GetGenericTypeDefinition();
Type[] genericArguments = type.GetGenericArguments();
string genericTypeName = genericType.Name;
// Trim the generic parameter counts from the name
genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`'));
string[] argumentTypeNames = genericArguments.Select(t => GetModelName(t)).ToArray();
modelName = String.Format(CultureInfo.InvariantCulture, "{0}Of{1}", genericTypeName, String.Join("And", argumentTypeNames));
}
return modelName;
}
}
} | 39.833333 | 140 | 0.634589 | [
"Apache-2.0"
] | philldellow/ISLA2 | ISLA2/ISLA2/Areas/HelpPage/ModelDescriptions/ModelNameHelper.cs | 1,434 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the groundstation-2019-05-23.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.GroundStation.Model
{
/// <summary>
///
/// </summary>
public partial class GetConfigResponse : AmazonWebServiceResponse
{
private string _configArn;
private ConfigTypeData _configData;
private string _configId;
private ConfigCapabilityType _configType;
private string _name;
private Dictionary<string, string> _tags = new Dictionary<string, string>();
/// <summary>
/// Gets and sets the property ConfigArn.
/// <para>
/// ARN of a <code>Config</code>
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string ConfigArn
{
get { return this._configArn; }
set { this._configArn = value; }
}
// Check to see if ConfigArn property is set
internal bool IsSetConfigArn()
{
return this._configArn != null;
}
/// <summary>
/// Gets and sets the property ConfigData.
/// <para>
/// Data elements in a <code>Config</code>.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public ConfigTypeData ConfigData
{
get { return this._configData; }
set { this._configData = value; }
}
// Check to see if ConfigData property is set
internal bool IsSetConfigData()
{
return this._configData != null;
}
/// <summary>
/// Gets and sets the property ConfigId.
/// <para>
/// UUID of a <code>Config</code>.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string ConfigId
{
get { return this._configId; }
set { this._configId = value; }
}
// Check to see if ConfigId property is set
internal bool IsSetConfigId()
{
return this._configId != null;
}
/// <summary>
/// Gets and sets the property ConfigType.
/// <para>
/// Type of a <code>Config</code>.
/// </para>
/// </summary>
public ConfigCapabilityType ConfigType
{
get { return this._configType; }
set { this._configType = value; }
}
// Check to see if ConfigType property is set
internal bool IsSetConfigType()
{
return this._configType != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// Name of a <code>Config</code>.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// Tags assigned to a <code>Config</code>.
/// </para>
/// </summary>
public Dictionary<string, string> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
}
} | 28.16129 | 111 | 0.548683 | [
"Apache-2.0"
] | TallyUpTeam/aws-sdk-net | sdk/src/Services/GroundStation/Generated/Model/GetConfigResponse.cs | 4,365 | C# |
using System;
namespace Prism.Ioc
{
public static class IContainerRegistryExtensions
{
public static void RegisterInstance<TInterface>(this IContainerRegistry containerRegistry, TInterface instance)
{
containerRegistry.RegisterInstance(typeof(TInterface), instance);
}
public static void RegisterSingleton(this IContainerRegistry containerRegistry, Type type)
{
containerRegistry.RegisterSingleton(type, type);
}
public static void RegisterSingleton<TFrom, TTo>(this IContainerRegistry containerRegistry) where TTo : TFrom
{
containerRegistry.RegisterSingleton(typeof(TFrom), typeof(TTo));
}
public static void RegisterSingleton<T>(this IContainerRegistry containerRegistry)
{
containerRegistry.RegisterSingleton(typeof(T));
}
public static void Register(this IContainerRegistry containerRegistry, Type type)
{
containerRegistry.Register(type, type);
}
public static void Register<T>(this IContainerRegistry containerRegistry)
{
containerRegistry.Register(typeof(T));
}
public static void Register(this IContainerRegistry containerRegistry, Type type, string name)
{
containerRegistry.Register(type, type, name);
}
public static void Register<T>(this IContainerRegistry containerRegistry, string name)
{
containerRegistry.Register(typeof(T), name);
}
public static void Register<TFrom, TTo>(this IContainerRegistry containerRegistry) where TTo : TFrom
{
containerRegistry.Register(typeof(TFrom), typeof(TTo));
}
public static void Register<TFrom, TTo>(this IContainerRegistry containerRegistry, string name) where TTo : TFrom
{
containerRegistry.Register(typeof(TFrom), typeof(TTo), name);
}
}
}
| 34.12069 | 121 | 0.662961 | [
"MIT"
] | Anapher/Prism | Source/Prism/Ioc/IContainerRegistryExtensions.cs | 1,981 | C# |
using System;
using System.Collections.Generic;
using System.Threading;
using GraphX.Measure;
using GraphX.PCL.Common.Enums;
using QuickGraph;
namespace GraphX.PCL.Common.Interfaces
{
public interface IGXLogicCore<TVertex, TEdge, TGraph>: IDisposable
where TVertex : class, IGraphXVertex
where TEdge : class, IGraphXEdge<TVertex>
where TGraph : class, IMutableBidirectionalGraph<TVertex, TEdge>
{
/// <summary>
/// Get an algorithm factory that provides different algorithm creation methods
/// </summary>
IAlgorithmFactory<TVertex, TEdge, TGraph> AlgorithmFactory { get; }
/// <summary>
/// Gets or sets algorithm storage that contain all currently defined algorithm objects by type (default or external)
/// Actual storage data is vital for correct edge routing operation after graph was regenerated.
/// </summary>
IAlgorithmStorage<TVertex, TEdge> AlgorithmStorage { get; set; }
/// <summary>
/// Gets or sets main graph object
/// </summary>
TGraph Graph { get; set; }
/// <summary>
/// Gets or sets if async algorithm computations are enabled
/// </summary>
bool AsyncAlgorithmCompute { get; set; }
/// <summary>
/// Gets or sets if edge curving technique enabled for smoother edges. Default value is True.
/// </summary>
bool EdgeCurvingEnabled { get; set; }
/// <summary>
/// Gets or sets roughly the length of each line segment in the polyline
/// approximation to a continuous curve in WPF units. The smaller the
/// number the smoother the curve, but slower the performance. Default is 8.
/// </summary>
double EdgeCurvingTolerance { get; set; }
/// <summary>
/// Gets or sets if parallel edges are enabled. All edges between the same nodes will be separated by ParallelEdgeDistance value.
/// This is post-process procedure and it may be performance-costly.
/// </summary>
bool EnableParallelEdges { get; set; }
/// <summary>
/// Gets or sets distance by which edges are parallelized if EnableParallelEdges is true. Default value is 5.
/// </summary>
int ParallelEdgeDistance { get; set; }
/// <summary>
/// Gets if edge routing will be performed on Compute() method execution
/// </summary>
bool IsEdgeRoutingEnabled { get; }
//bool EnableEdgeLabelsOverlapRemoval { get; set; }
/// <summary>
/// Gets is LayoutAlgorithmTypeEnum.Custom (NOT external) layout selected and used. Custom layout used to manualy generate graph.
/// </summary>
bool IsCustomLayout { get; }
/// <summary>
/// Gets or sets default layout algorithm that will be used on graph generation/relayouting
/// </summary>
LayoutAlgorithmTypeEnum DefaultLayoutAlgorithm { get; set; }
/// <summary>
/// Gets or sets default overlap removal algorithm that will be used on graph generation/relayouting
/// </summary>
OverlapRemovalAlgorithmTypeEnum DefaultOverlapRemovalAlgorithm { get; set; }
/// <summary>
/// Gets or sets default edge routing algorithm that will be used on graph generation/relayouting
/// </summary>
EdgeRoutingAlgorithmTypeEnum DefaultEdgeRoutingAlgorithm { get; set; }
/// <summary>
/// Gets or sets default layout algorithm parameters that will be used on graph generation/relayouting
/// </summary>
ILayoutParameters DefaultLayoutAlgorithmParams { get; set; }
/// <summary>
/// Gets or sets default overlap removal algorithm parameters that will be used on graph generation/relayouting
/// </summary>
IOverlapRemovalParameters DefaultOverlapRemovalAlgorithmParams { get; set; }
/// <summary>
/// Gets or sets default edge routing algorithm parameters that will be used on graph generation/relayouting
/// </summary>
IEdgeRoutingParameters DefaultEdgeRoutingAlgorithmParams { get; set; }
/// <summary>
/// Gets or sets external layout algorithm that will be used instead of the default one.
/// Negates DefaultLayoutAlgorithm property value if set.
/// </summary>
IExternalLayout<TVertex, TEdge> ExternalLayoutAlgorithm { get; set; }
/// <summary>
/// Gets or sets external overlap removal algorithm that will be used instead of the default one.
/// Negates DefaultOverlapRemovalAlgorithm property value if set.
/// </summary>
IExternalOverlapRemoval<TVertex> ExternalOverlapRemovalAlgorithm { get; set; }
/// <summary>
/// Gets or sets external edge routing algorithm that will be used instead of the default one.
/// Negates DefaultEdgeRoutingAlgorithm property value if set.
/// </summary>
IExternalEdgeRouting<TVertex, TEdge> ExternalEdgeRoutingAlgorithm { get; set; }
/// <summary>
/// Computes all edge routes related to specified vertex
/// </summary>
/// <param name="dataVertex">Vertex data</param>
/// <param name="vertexPosition">Vertex position</param>
/// <param name="vertexSize">Vertex size</param>
void ComputeEdgeRoutesByVertex(TVertex dataVertex, Point? vertexPosition = null, Size? vertexSize = null);
//void CreateNewAlgorithmFactory();
//void CreateNewAlgorithmStorage(IExternalLayout<TVertex> layout, IExternalOverlapRemoval<TVertex> or, IExternalEdgeRouting<TVertex, TEdge> er);
/// <summary>
/// Computes graph using parameters set in LogicCore properties
/// </summary>
/// <param name="cancellationToken">Optional cancellation token for async operation abort</param>
IDictionary<TVertex, Point> Compute(CancellationToken cancellationToken);
/// <summary>
/// Gets if current algorithm set needs vertices sizes
/// </summary>
bool AreVertexSizesNeeded();
/// <summary>
/// Gets if current algorithms set actualy needs overlap removal algorithm
/// </summary>
bool AreOverlapNeeded();
/// <summary>
/// Generate layout algorithm according to LogicCore layout algorithm default/external properties set
/// </summary>
/// <param name="vertexSizes">Vertices sizes</param>
/// <param name="vertexPositions">Vertices positions</param>
IExternalLayout<TVertex, TEdge> GenerateLayoutAlgorithm(Dictionary<TVertex, Size> vertexSizes, IDictionary<TVertex, Point> vertexPositions);
/// <summary>
/// Generate overlap removal algorithm according to LogicCore overlap removal algorithm default/external properties set
/// </summary>
/// <param name="rectangles">Vertices rectangular sizes</param>
IExternalOverlapRemoval<TVertex> GenerateOverlapRemovalAlgorithm(Dictionary<TVertex, Rect> rectangles = null);
/// <summary>
/// Generate layout algorithm according to LogicCore layout algorithm default/external properties set
/// </summary>
/// <param name="desiredSize">Desired rectangular area size that will be taken into account</param>
/// <param name="vertexPositions">Vertices positions</param>
/// <param name="rectangles">Vertices rectangular sizes</param>
IExternalEdgeRouting<TVertex, TEdge> GenerateEdgeRoutingAlgorithm(Size desiredSize, IDictionary<TVertex, Point> vertexPositions = null, IDictionary<TVertex, Rect> rectangles = null);
/// <summary>
/// Creates algorithm objects based on default/external LogicCore properies and stores them to be able to access them later by, for ex. edge recalculation logic.
/// Done automaticaly when graph is regenerated/relayouted.
/// </summary>
/// <param name="vertexSizes">Vertex sizes</param>
/// <param name="vertexPositions">Vertex positions</param>
bool GenerateAlgorithmStorage(Dictionary<TVertex, Size> vertexSizes,
IDictionary<TVertex, Point> vertexPositions);
/// <summary>
/// Clear LogicCore data
/// </summary>
/// <param name="clearStorages">Also clear storages data</param>
void Clear(bool clearStorages = true);
}
}
| 46.571429 | 190 | 0.659391 | [
"Apache-2.0"
] | anh123minh/DES | GraphX.PCL.Common/Interfaces/IGXLogicCore.cs | 8,478 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using PurchasingSystemServices.Data;
namespace PurchasingSystemServices.Migrations
{
[DbContext(typeof(DataContext))]
[Migration("20210117032222_AlterProductBalanceRemoveColumnProductId")]
partial class AlterProductBalanceRemoveColumnProductId
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn)
.HasAnnotation("ProductVersion", "3.1.4")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
modelBuilder.Entity("PurchasingSystemServices.Models.Category", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id")
.HasColumnType("integer")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<string>("Active")
.IsRequired()
.HasColumnName("active")
.HasColumnType("char");
b.Property<int>("CreateBy")
.HasColumnName("create_by")
.HasColumnType("integer");
b.Property<DateTime>("CreateDate")
.HasColumnName("create_date")
.HasColumnType("timestamp without time zone");
b.Property<int>("Level")
.HasColumnName("level")
.HasColumnType("integer");
b.Property<string>("Name")
.IsRequired()
.HasColumnName("name")
.HasColumnType("character varying(200)")
.HasMaxLength(200);
b.Property<int>("ParentId")
.HasColumnName("parent_id")
.HasColumnType("integer");
b.Property<int?>("UpdateBy")
.HasColumnName("update_by")
.HasColumnType("integer");
b.Property<DateTime?>("UpdateDate")
.HasColumnName("update_date")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.ToTable("category");
});
modelBuilder.Entity("PurchasingSystemServices.Models.DocumentNumber", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id")
.HasColumnType("integer")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<string>("Code")
.IsRequired()
.HasColumnName("code")
.HasColumnType("char(3)");
b.Property<int>("CreateBy")
.HasColumnName("create_by")
.HasColumnType("integer");
b.Property<DateTime>("CreateDate")
.HasColumnName("create_date")
.HasColumnType("timestamp without time zone");
b.Property<int>("CurrentSequence")
.HasColumnName("current_sequence")
.HasColumnType("integer");
b.Property<int?>("UpdateBy")
.HasColumnName("update_by")
.HasColumnType("integer");
b.Property<DateTime?>("UpdateDate")
.HasColumnName("update_date")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.ToTable("document_number");
});
modelBuilder.Entity("PurchasingSystemServices.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id")
.HasColumnType("integer")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<int>("CreateBy")
.HasColumnName("create_by")
.HasColumnType("integer");
b.Property<DateTime>("CreateDate")
.HasColumnName("create_date")
.HasColumnType("timestamp without time zone");
b.Property<long>("GrandTotal")
.HasColumnName("grand_total")
.HasColumnType("bigint");
b.Property<string>("InvoiceNumber")
.IsRequired()
.HasColumnName("invoice_number")
.HasColumnType("character varying(10)")
.HasMaxLength(10);
b.Property<DateTime>("OrderDate")
.HasColumnName("order_date")
.HasColumnType("timestamp without time zone");
b.Property<string>("OrderNumber")
.IsRequired()
.HasColumnName("order_number")
.HasColumnType("character varying(10)")
.HasMaxLength(10);
b.Property<string>("OrderStatus")
.IsRequired()
.HasColumnName("order_status")
.HasColumnType("text");
b.Property<int?>("UpdateBy")
.HasColumnName("update_by")
.HasColumnType("integer");
b.Property<DateTime?>("UpdateDate")
.HasColumnName("update_date")
.HasColumnType("timestamp without time zone");
b.Property<int>("UserId")
.HasColumnName("user_id")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("order");
});
modelBuilder.Entity("PurchasingSystemServices.Models.OrderDetail", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id")
.HasColumnType("integer")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<int>("CreateBy")
.HasColumnName("create_by")
.HasColumnType("integer");
b.Property<DateTime>("CreateDate")
.HasColumnName("create_date")
.HasColumnType("timestamp without time zone");
b.Property<string>("ItemId")
.IsRequired()
.HasColumnName("item_id")
.HasColumnType("text");
b.Property<string>("ItemName")
.IsRequired()
.HasColumnName("item_name")
.HasColumnType("text");
b.Property<string>("OrderNumber")
.IsRequired()
.HasColumnName("order_number")
.HasColumnType("character varying(10)")
.HasMaxLength(10);
b.Property<int>("OrderQuantity")
.HasColumnName("order_quantity")
.HasColumnType("integer");
b.Property<long>("SubTotal")
.HasColumnName("sub_total")
.HasColumnType("bigint");
b.Property<int?>("UpdateBy")
.HasColumnName("update_by")
.HasColumnType("integer");
b.Property<DateTime?>("UpdateDate")
.HasColumnName("update_date")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.ToTable("order_detail");
});
modelBuilder.Entity("PurchasingSystemServices.Models.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id")
.HasColumnType("integer")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<string>("Active")
.IsRequired()
.HasColumnName("active")
.HasColumnType("char");
b.Property<int>("CategoryId")
.HasColumnName("category_id")
.HasColumnType("integer");
b.Property<int>("CreateBy")
.HasColumnName("create_by")
.HasColumnType("integer");
b.Property<DateTime>("CreateDate")
.HasColumnName("create_date")
.HasColumnType("timestamp without time zone");
b.Property<string>("Name")
.IsRequired()
.HasColumnName("name")
.HasColumnType("character varying(200)")
.HasMaxLength(200);
b.Property<int?>("UpdateBy")
.HasColumnName("update_by")
.HasColumnType("integer");
b.Property<DateTime?>("UpdateDate")
.HasColumnName("update_date")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.ToTable("product");
});
modelBuilder.Entity("PurchasingSystemServices.Models.ProductBalance", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id")
.HasColumnType("integer")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<string>("Active")
.IsRequired()
.HasColumnName("active")
.HasColumnType("char");
b.Property<long>("BalanceAmount")
.HasColumnName("balance_amount")
.HasColumnType("bigint");
b.Property<int>("CreateBy")
.HasColumnName("create_by")
.HasColumnType("integer");
b.Property<DateTime>("CreateDate")
.HasColumnName("create_date")
.HasColumnType("timestamp without time zone");
b.Property<string>("Name")
.IsRequired()
.HasColumnName("name")
.HasColumnType("character varying(200)")
.HasMaxLength(200);
b.Property<int>("ProductParentId")
.HasColumnName("product_parent_id")
.HasColumnType("integer");
b.Property<int?>("UpdateBy")
.HasColumnName("update_by")
.HasColumnType("integer");
b.Property<DateTime?>("UpdateDate")
.HasColumnName("update_date")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.ToTable("product_balance");
});
modelBuilder.Entity("PurchasingSystemServices.Models.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id")
.HasColumnType("integer")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<string>("Active")
.IsRequired()
.HasColumnName("active")
.HasColumnType("char");
b.Property<int>("CreateBy")
.HasColumnName("create_by")
.HasColumnType("integer");
b.Property<DateTime>("CreateDate")
.HasColumnName("create_date")
.HasColumnType("timestamp without time zone");
b.Property<string>("Email")
.IsRequired()
.HasColumnName("email")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnName("name")
.HasColumnType("character varying(500)")
.HasMaxLength(500);
b.Property<string>("Password")
.IsRequired()
.HasColumnName("password")
.HasColumnType("varchar");
b.Property<string>("Phone")
.IsRequired()
.HasColumnName("phone")
.HasColumnType("varchar")
.HasMaxLength(14);
b.Property<int?>("UpdateBy")
.HasColumnName("update_by")
.HasColumnType("integer");
b.Property<DateTime?>("UpdateDate")
.HasColumnName("update_date")
.HasColumnType("timestamp without time zone");
b.Property<string>("UserRole")
.IsRequired()
.HasColumnName("role_code")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("user");
});
modelBuilder.Entity("PurchasingSystemServices.Models.UserBalance", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id")
.HasColumnType("integer")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<string>("Active")
.IsRequired()
.HasColumnName("active")
.HasColumnType("char");
b.Property<long>("BalanceAmount")
.HasColumnName("balance_amount")
.HasColumnType("bigint");
b.Property<int>("CreateBy")
.HasColumnName("create_by")
.HasColumnType("integer");
b.Property<DateTime>("CreateDate")
.HasColumnName("create_date")
.HasColumnType("timestamp without time zone");
b.Property<int?>("UpdateBy")
.HasColumnName("update_by")
.HasColumnType("integer");
b.Property<DateTime?>("UpdateDate")
.HasColumnName("update_date")
.HasColumnType("timestamp without time zone");
b.Property<int>("UserId")
.HasColumnName("user_id")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("user_balance");
});
modelBuilder.Entity("PurchasingSystemServices.Models.UserRole", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id")
.HasColumnType("integer")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<string>("Code")
.IsRequired()
.HasColumnName("code")
.HasColumnType("char")
.HasMaxLength(1);
b.Property<string>("Role")
.HasColumnName("role")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("user_role");
});
#pragma warning restore 612, 618
}
}
}
| 39.866516 | 128 | 0.453833 | [
"MIT"
] | yosioliver/purchasingsystem-backend | PurchasingSystemServices/Migrations/20210117032222_AlterProductBalanceRemoveColumnProductId.Designer.cs | 17,623 | C# |
using MemorieDeFleurs.UI.WPF.Model;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Windows;
using YasT.Framework.Logging;
namespace MemorieDeFleurs.UI.WPF.Views.Helpers
{
/// <summary>
/// 外部化したテキストリソース管理クラス
///
/// Visual Studio の XAML コードエディタで使用する (インテリセンス、ビルド警告等) ため、
/// アプリケーション起動時のリソースディクショナリは App.xaml に記載する。
/// テキストリソースを XAML 内で利用するときは、 StaticResource または DyanmicResource で指定する。
/// ソースコード中でリソースにアクセスする場合は <see cref="TextResourceFinder"/> を呼び出す。
/// </summary>
public class TextResourceManager
{
private class TextResource
{
public string CultureName { get; private set; }
public TextResource(string culture)
{
CultureName = culture;
}
public ResourceDictionary Resource
{
get { return new ResourceDictionary() { Source = new Uri($"Resources/{CultureName}/Text.{CultureName}.xaml", UriKind.Relative) }; }
}
}
private TextResourceManager() { }
private static IDictionary<string, TextResource> _resources = new SortedDictionary<string, TextResource>()
{
{ "ja-JP", new TextResource("ja-JP") },
{ "en-US", new TextResource("en-US") }
};
/// <summary>
/// このクラスのインスタンス
/// </summary>
public static TextResourceManager Instance
{
get
{
lock(_resources)
{
if(_instance == null)
{
_instance = new TextResourceManager();
_instance.UpdateCultureInfo(Thread.CurrentThread.CurrentUICulture);
}
}
return _instance;
}
}
private static TextResourceManager _instance;
/// <summary>
/// リソースを切り替える
/// </summary>
/// <param name="culture">切替後の言語を示すカルチャー情報</param>
public void UpdateCultureInfo(CultureInfo culture)
{
LogUtil.DEBUGLOG_MethodCalled(culture.Name, $"CurrentUICulture={Thread.CurrentThread.CurrentUICulture.Name}");
if(culture == null) { return; /* _resource を検索できないので何もしない */ }
if(culture == CultureInfo.InvariantCulture) { return; /* _resource に登録していないので何もしない */ }
if(culture == Thread.CurrentThread.CurrentUICulture) { return; /* リソース変更不要なので何もしない */ }
TextResource maker;
if(_resources.TryGetValue(culture.Name, out maker))
{
// リソースを切り替える
Thread.CurrentThread.CurrentUICulture = culture;
App.Current.Resources.MergedDictionaries[0] = maker.Resource;
}
else
{
// ResourceDictionary がないので対応できない
throw new ApplicationException($"Unsupported culture:{culture.Name}");
}
}
}
}
| 33.255319 | 148 | 0.550224 | [
"Apache-2.0"
] | Yasuhiro-Tanabe/YtAppCSharp | MemorieDeFleurs/MemorieDeFleurs.UI.WPF/Views/Helpers/TextResourceManager.cs | 3,604 | C# |
using System;
namespace LicenceTrackerProto.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
} | 19.727273 | 70 | 0.682028 | [
"Apache-2.0"
] | Geoff1900/LicenceTrackerProto | LicenceTrackerProto/LicenceTrackerProto/Models/ErrorViewModel.cs | 217 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the robomaker-2018-06-29.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.RoboMaker.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.RoboMaker.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for OutputLocation Object
/// </summary>
public class OutputLocationUnmarshaller : IUnmarshaller<OutputLocation, XmlUnmarshallerContext>, IUnmarshaller<OutputLocation, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
OutputLocation IUnmarshaller<OutputLocation, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public OutputLocation Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
OutputLocation unmarshalledObject = new OutputLocation();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("s3Bucket", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.S3Bucket = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("s3Prefix", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.S3Prefix = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static OutputLocationUnmarshaller _instance = new OutputLocationUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static OutputLocationUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.295918 | 156 | 0.611159 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/RoboMaker/Generated/Model/Internal/MarshallTransformations/OutputLocationUnmarshaller.cs | 3,459 | C# |
using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace MasterDevs.ChromeDevTools.Protocol.Chrome.Network
{
/// <summary>
/// Returns all browser cookies. Depending on the backend support, will return detailed cookie information in the <code>cookies</code> field.
/// </summary>
[Command(ProtocolName.Network.GetAllCookies)]
[SupportedBy("Chrome")]
public class GetAllCookiesCommand: ICommand<GetAllCookiesCommandResponse>
{
}
}
| 29.176471 | 142 | 0.788306 | [
"MIT"
] | Digitalbil/ChromeDevTools | source/ChromeDevTools/Protocol/Chrome/Network/GetAllCookiesCommand.cs | 496 | 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("Sunglasses")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Sunglasses")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2c20a94b-8065-4a10-8788-109dd57912ed")]
// 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.648649 | 84 | 0.744436 | [
"MIT"
] | pavlinpetkov88/ProgramingBasic | DrawingWithLoops/Sunglasses/Properties/AssemblyInfo.cs | 1,396 | C# |
/**
* Copyright 2013 Canada Health Infoway, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: $LastChangedBy: tmcgrady $
* Last modified: $LastChangedDate: 2011-05-04 15:47:15 -0400 (Wed, 04 May 2011) $
* Revision: $LastChangedRevision: 2623 $
*/
/* This class was auto-generated by the message builder generator tools. */
namespace Ca.Infoway.Messagebuilder.Model.Ab_mr2007_v02_r02.Cr.Prpa_mt101103ca {
using Ca.Infoway.Messagebuilder.Annotation;
using Ca.Infoway.Messagebuilder.Datatype;
using Ca.Infoway.Messagebuilder.Datatype.Impl;
using Ca.Infoway.Messagebuilder.Model;
using System;
[Hl7PartTypeMappingAttribute(new string[] {"PRPA_MT101103CA.DeceasedTime"})]
public class DeceasedTime : MessagePartBean {
private TS value;
public DeceasedTime() {
this.value = new TSImpl();
}
/**
* <summary>Business Name: Deceased Date</summary>
*
* <remarks>Relationship: PRPA_MT101103CA.DeceasedTime.value
* Conformance/Cardinality: REQUIRED (0-1)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"value"})]
public PlatformDate Value {
get { return this.value.Value; }
set { this.value.Value = value; }
}
}
} | 36.803922 | 83 | 0.658498 | [
"ECL-2.0",
"Apache-2.0"
] | CanadaHealthInfoway/message-builder-dotnet | message-builder-release-ab-v02_r02/Main/Ca/Infoway/Messagebuilder/Model/Ab_mr2007_v02_r02/Cr/Prpa_mt101103ca/DeceasedTime.cs | 1,877 | C# |
using SFA.DAS.Authorization.ModelBinding;
using System;
namespace SFA.DAS.EmployerCommitmentsV2.Web.Models.Cohort
{
public class MessageViewModel : IAuthorizationContextModel
{
public string AccountHashedId { get; set; }
public long AccountId { get; set; }
public Guid? ReservationId { get; set; }
public string AccountLegalEntityHashedId { get; set; }
public string LegalEntityName { get; set; }
public long AccountLegalEntityId { get; set; }
public string StartMonthYear { get; set; }
public string CourseCode { get; set; }
public long ProviderId { get; set; }
public string ProviderName { get; set; }
public string Message { get; set; }
public string TransferSenderId { get; set; }
public long? DecodedTransferSenderId { get; set; }
}
} | 38.954545 | 62 | 0.659277 | [
"MIT"
] | SkillsFundingAgency/das-employercommitments-v2 | src/SFA.DAS.EmployerCommitmentsV2.Web/Models/Cohort/MessageViewModel.cs | 859 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Threading.Tasks;
using dotMorten.Xamarin.Forms;
using KinaUnaXamarin.Helpers;
using KinaUnaXamarin.Models;
using KinaUnaXamarin.Models.KinaUna;
using KinaUnaXamarin.Services;
using KinaUnaXamarin.ViewModels.Details;
using Plugin.Media;
using Plugin.Multilingual;
using TimeZoneConverter;
using Xamarin.Essentials;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace KinaUnaXamarin.Views.Details
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class FriendDetailPage
{
private readonly FriendDetailViewModel _viewModel;
private UserInfo _userInfo;
private string _accessToken;
private int _viewChild = Constants.DefaultChildId;
private bool _online = true;
private string _filePath;
const string ResourceId = "KinaUnaXamarin.Resources.Translations";
static readonly Lazy<ResourceManager> resmgr = new Lazy<ResourceManager>(() => new ResourceManager(ResourceId, typeof(TranslateExtension).GetTypeInfo().Assembly));
public FriendDetailPage(Friend friendItem)
{
_viewModel = new FriendDetailViewModel();
InitializeComponent();
_viewModel.CurrentFriendId = friendItem.FriendId;
_viewModel.AccessLevel = friendItem.AccessLevel;
_viewModel.Description = friendItem.Description;
_viewModel.FriendSince = friendItem.FriendSince;
_viewModel.FriendType = friendItem.Type;
_viewModel.Context = friendItem.Context;
_viewModel.Name = friendItem.Name;
_viewModel.Notes = friendItem.Notes;
_viewModel.Tags = friendItem.Tags;
FriendImage.Source = friendItem.PictureLink;
BindingContext = _viewModel;
}
protected override async void OnAppearing()
{
base.OnAppearing();
Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;
var networkAccess = Connectivity.NetworkAccess;
bool internetAccess = networkAccess == NetworkAccess.Internet;
if (internetAccess)
{
OfflineStackLayout.IsVisible = false;
}
else
{
OfflineStackLayout.IsVisible = true;
}
await CheckAccount();
await Reload();
}
protected override void OnDisappearing()
{
base.OnDisappearing();
Connectivity.ConnectivityChanged -= Connectivity_ConnectivityChanged;
}
private async void Connectivity_ConnectivityChanged(object sender, ConnectivityChangedEventArgs e)
{
var networkAccess = e.NetworkAccess;
bool internetAccess = networkAccess == NetworkAccess.Internet;
if (internetAccess != _online)
{
_online = internetAccess;
await Reload();
}
}
private async Task CheckAccount()
{
string userEmail = await UserService.GetUserEmail();
_accessToken = await UserService.GetAuthAccessToken();
bool accessTokenCurrent = false;
if (_accessToken != "")
{
accessTokenCurrent = await UserService.IsAccessTokenCurrent();
if (!accessTokenCurrent)
{
bool loginSuccess = await UserService.LoginIdsAsync();
if (loginSuccess)
{
_accessToken = await UserService.GetAuthAccessToken();
accessTokenCurrent = true;
}
await Reload();
}
}
if (String.IsNullOrEmpty(_accessToken) || !accessTokenCurrent)
{
_viewModel.IsLoggedIn = false;
_viewModel.LoggedOut = true;
_accessToken = "";
_userInfo = OfflineDefaultData.DefaultUserInfo;
}
else
{
_viewModel.IsLoggedIn = true;
_viewModel.LoggedOut = false;
_userInfo = await UserService.GetUserInfo(userEmail);
}
string userviewchild = await SecureStorage.GetAsync(Constants.UserViewChildKey);
bool viewchildParsed = int.TryParse(userviewchild, out _viewChild);
if (!viewchildParsed)
{
_viewChild = _userInfo.ViewChild;
}
if (_viewChild == 0)
{
if (_userInfo.ViewChild != 0)
{
_viewChild = _userInfo.ViewChild;
}
else
{
_viewChild = Constants.DefaultChildId;
}
}
if (String.IsNullOrEmpty(_userInfo.Timezone))
{
_userInfo.Timezone = Constants.DefaultTimeZone;
}
try
{
TimeZoneInfo.FindSystemTimeZoneById(_userInfo.Timezone);
}
catch (Exception)
{
_userInfo.Timezone = TZConvert.WindowsToIana(_userInfo.Timezone);
}
Progeny progeny = await ProgenyService.GetProgeny(_viewChild);
try
{
TimeZoneInfo.FindSystemTimeZoneById(progeny.TimeZone);
}
catch (Exception)
{
progeny.TimeZone = TZConvert.WindowsToIana(progeny.TimeZone);
}
_viewModel.Progeny = progeny;
_viewModel.UserAccessLevel = await ProgenyService.GetAccessLevel(_viewChild);
if (_viewModel.UserAccessLevel == 0)
{
_viewModel.CanUserEditItems = true;
}
}
private async Task Reload()
{
_viewModel.IsBusy = true;
await CheckAccount();
_viewModel.CurrentFriend =
await ProgenyService.GetFriend(_viewModel.CurrentFriendId, _accessToken);
_viewModel.AccessLevel = _viewModel.CurrentFriend.AccessLevel;
_viewModel.CurrentFriend.Progeny = _viewModel.Progeny = await ProgenyService.GetProgeny(_viewModel.CurrentFriend.ProgenyId);
if (_viewModel.CurrentFriend.FriendSince.HasValue)
{
_viewModel.DateYear = _viewModel.CurrentFriend.FriendSince.Value.Year;
_viewModel.DateMonth = _viewModel.CurrentFriend.FriendSince.Value.Month;
_viewModel.DateDay = _viewModel.CurrentFriend.FriendSince.Value.Day;
}
_viewModel.UserAccessLevel = await ProgenyService.GetAccessLevel(_viewModel.CurrentFriend.ProgenyId);
if (_viewModel.UserAccessLevel == 0)
{
_viewModel.CanUserEditItems = true;
}
else
{
_viewModel.CanUserEditItems = false;
}
_viewModel.CurrentFriendId = _viewModel.CurrentFriend.FriendId;
_viewModel.AccessLevel = _viewModel.CurrentFriend.AccessLevel;
_viewModel.Name = _viewModel.CurrentFriend.Name;
_viewModel.FriendSince = _viewModel.CurrentFriend.FriendSince;
_viewModel.FriendType = _viewModel.CurrentFriend.Type;
_viewModel.Context = _viewModel.CurrentFriend.Context;
_viewModel.Notes = _viewModel.CurrentFriend.Notes;
_viewModel.Tags = _viewModel.CurrentFriend.Tags;
_viewModel.Notes = _viewModel.CurrentFriend.Notes;
FriendImage.Source = _viewModel.CurrentFriend.PictureLink;
var networkInfo = Connectivity.NetworkAccess;
if (networkInfo == NetworkAccess.Internet)
{
// Connection to internet is available
_online = true;
OfflineStackLayout.IsVisible = false;
}
else
{
_online = false;
OfflineStackLayout.IsVisible = true;
}
_viewModel.IsBusy = false;
}
private async void EditButton_OnClicked(object sender, EventArgs e)
{
if (_viewModel.EditMode)
{
_viewModel.EditMode = false;
_viewModel.IsBusy = true;
_viewModel.IsSaving = true;
DateTime frnDate = new DateTime(_viewModel.DateYear, _viewModel.DateMonth, _viewModel.DateDay);
_viewModel.CurrentFriend.FriendSince = frnDate;
_viewModel.CurrentFriend.Name = _viewModel.Name;
_viewModel.CurrentFriend.Type = FriendTypePicker?.SelectedIndex ?? 0;
_viewModel.CurrentFriend.Context = ContextEntry?.Text ?? "";
_viewModel.CurrentFriend.Notes = _viewModel.Notes;
_viewModel.CurrentFriend.Tags = TagsEntry?.Text ?? "";
_viewModel.CurrentFriend.AccessLevel = _viewModel.AccessLevel;
if (string.IsNullOrEmpty(_filePath) || !File.Exists(_filePath))
{
_viewModel.CurrentFriend.PictureLink = "[KeepExistingLink]";
}
else
{
// Upload photo file, get a reference to the image.
string pictureLink = await ProgenyService.UploadFriendPicture(_filePath);
if (pictureLink == "")
{
_viewModel.IsBusy = false;
// Todo: Show error
_viewModel.CurrentFriend.PictureLink = "[KeepExistingLink]";
return;
}
_viewModel.CurrentFriend.PictureLink = pictureLink;
}
// Save changes.
Friend resulFriend = await ProgenyService.UpdateFriend(_viewModel.CurrentFriend);
_viewModel.IsBusy = false;
_viewModel.IsSaving = false;
EditButton.Text = IconFont.CalendarEdit;
if (resulFriend != null) // Todo: Error message if update fails.
{
MessageLabel.Text = "Friend Updated"; // Todo: Translate
MessageLabel.BackgroundColor = Color.DarkGreen;
MessageLabel.IsVisible = true;
await Reload();
}
}
else
{
EditButton.Text = IconFont.ContentSave;
_viewModel.EditMode = true;
_viewModel.TagsAutoSuggestList = await ProgenyService.GetTagsAutoSuggestList(_viewModel.CurrentFriend.ProgenyId, 0);
_viewModel.ContextAutoSuggestList = await ProgenyService.GetContextAutoSuggestList(_viewModel.CurrentFriend.ProgenyId, 0);
}
}
private async void SelectImageButton_OnClicked(object sender, EventArgs e)
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsPickPhotoSupported)
{
return;
}
var file = await CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
{
RotateImage = false,
SaveMetaData = true
});
if (file == null)
{
return;
}
_filePath = file.Path;
FriendImage.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
file.Dispose();
return stream;
});
}
private async void CancelButton_OnClicked(object sender, EventArgs e)
{
EditButton.Text = IconFont.AccountEdit;
_viewModel.EditMode = false;
await Reload();
}
private void FriendDatePicker_OnDateSelected(object sender, DateChangedEventArgs e)
{
_viewModel.DateYear = FriendDatePicker.Date.Year;
_viewModel.DateMonth = FriendDatePicker.Date.Month;
_viewModel.DateDay = FriendDatePicker.Date.Day;
}
private async void DeleteButton_OnClickedButton_OnClicked(object sender, EventArgs e)
{
var ci = CrossMultilingual.Current.CurrentCultureInfo;
string confirmTitle = resmgr.Value.GetString("DeleteFriend", ci);
string confirmMessage = resmgr.Value.GetString("DeleteFriendMessage", ci) + " ? ";
string yes = resmgr.Value.GetString("Yes", ci);
string no = resmgr.Value.GetString("No", ci);
bool confirmDelete = await DisplayAlert(confirmTitle, confirmMessage, yes, no);
if (confirmDelete)
{
_viewModel.IsBusy = true;
_viewModel.EditMode = false;
Friend deletedFriend = await ProgenyService.DeleteFriend(_viewModel.CurrentFriend);
if (deletedFriend.FriendId == 0)
{
_viewModel.EditMode = false;
// Todo: Show success message
}
else
{
_viewModel.EditMode = true;
// Todo: Show failed message
}
_viewModel.IsBusy = false;
}
}
private void TagsEditor_OnTextChanged(object sender, AutoSuggestBoxTextChangedEventArgs e)
{
// Only get results when it was a user typing,
// otherwise assume the value got filled in by TextMemberPath
// or the handler for SuggestionChosen.
if (e.Reason == AutoSuggestionBoxTextChangeReason.UserInput)
{
AutoSuggestBox autoSuggestBox = sender as AutoSuggestBox;
if (autoSuggestBox != null && autoSuggestBox.Text.Length > 0)
{
string lastTag = autoSuggestBox.Text.Split(',').LastOrDefault();
if (!string.IsNullOrEmpty(lastTag) && lastTag.Length > 0)
{
List<string> filteredTags = new List<string>();
foreach (string tagString in _viewModel.TagsAutoSuggestList)
{
if (tagString.Trim().ToUpper().Contains(lastTag.Trim().ToUpper()))
{
filteredTags.Add(tagString);
}
}
//Set the ItemsSource to be your filtered dataset
autoSuggestBox.ItemsSource = filteredTags;
}
else
{
autoSuggestBox.ItemsSource = null;
}
}
else
{
if (autoSuggestBox != null)
{
autoSuggestBox.ItemsSource = null;
}
}
}
}
private void TagsEditor_OnQuerySubmitted(object sender, AutoSuggestBoxQuerySubmittedEventArgs e)
{
if (e.ChosenSuggestion != null)
{
AutoSuggestBox autoSuggestBox = sender as AutoSuggestBox;
if (autoSuggestBox != null)
{
// User selected an item from the suggestion list, take an action on it here.
List<string> existingTags = TagsEntry.Text.Split(',').ToList();
existingTags.Remove(existingTags.Last());
string newText = "";
if (existingTags.Any())
{
foreach (string tagString in existingTags)
{
newText = newText + tagString + ", ";
}
}
newText = newText + e.ChosenSuggestion + ", ";
autoSuggestBox.Text = newText;
autoSuggestBox.ItemsSource = null;
}
}
else
{
// User hit Enter from the search box. Use e.QueryText to determine what to do.
}
}
private void TagsEditor_OnSuggestionChosen(object sender, AutoSuggestBoxSuggestionChosenEventArgs e)
{
AutoSuggestBox autoSuggestBox = sender as AutoSuggestBox;
// Set sender.Text. You can use e.SelectedItem to build your text string.
if (autoSuggestBox != null)
{
//List<string> existingTags = TagsEditor.Text.Split(',').ToList();
//existingTags.Remove(existingTags.Last());
//autoSuggestBox.Text = "";
//foreach (string tagString in existingTags)
//{
// autoSuggestBox.Text = autoSuggestBox.Text + ", " + tagString;
//}
//autoSuggestBox.Text = autoSuggestBox.Text + e.SelectedItem.ToString();
}
}
private void ContextEntry_OnTextChanged(object sender, AutoSuggestBoxTextChangedEventArgs e)
{
// Only get results when it was a user typing,
// otherwise assume the value got filled in by TextMemberPath
// or the handler for SuggestionChosen.
if (e.Reason == AutoSuggestionBoxTextChangeReason.UserInput)
{
AutoSuggestBox autoSuggestBox = sender as AutoSuggestBox;
if (autoSuggestBox != null && autoSuggestBox.Text.Length > 0)
{
List<string> filteredContexts = new List<string>();
foreach (string contextString in _viewModel.ContextAutoSuggestList)
{
if (contextString.ToUpper().Contains(autoSuggestBox.Text.Trim().ToUpper()))
{
filteredContexts.Add(contextString);
}
}
//Set the ItemsSource to be your filtered dataset
autoSuggestBox.ItemsSource = filteredContexts;
}
else
{
if (autoSuggestBox != null)
{
autoSuggestBox.ItemsSource = null;
}
}
}
}
private void ContextEntry_OnQuerySubmitted(object sender, AutoSuggestBoxQuerySubmittedEventArgs e)
{
if (e.ChosenSuggestion != null)
{
AutoSuggestBox autoSuggestBox = sender as AutoSuggestBox;
if (autoSuggestBox != null)
{
// User selected an item from the suggestion list, take an action on it here.
autoSuggestBox.Text = e.ChosenSuggestion.ToString();
autoSuggestBox.ItemsSource = null;
}
}
else
{
// User hit Enter from the search box. Use e.QueryText to determine what to do.
}
}
private void ContextEntry_OnSuggestionChosen(object sender, AutoSuggestBoxSuggestionChosenEventArgs e)
{
AutoSuggestBox autoSuggestBox = sender as AutoSuggestBox;
// Set sender.Text. You can use e.SelectedItem to build your text string.
if (autoSuggestBox != null)
{
autoSuggestBox.Text = e.SelectedItem.ToString();
}
}
private async void TapGestureRecognizer_OnTapped(object sender, EventArgs e)
{
await Shell.Current.Navigation.PopModalAsync();
}
}
} | 39.119141 | 171 | 0.543762 | [
"MIT"
] | KinaUna/KinaUnaXamarin | KinaUnaXamarin/KinaUnaXamarin/Views/Details/FriendDetailPage.xaml.cs | 20,031 | C# |
using Newtonsoft.Json;
namespace Mastodon.Model
{
public class AppRegistration
{
[JsonProperty("id")] public long Id { get; set; }
[JsonProperty("redirect_uri")] public string RedirectUri { get; set; }
[JsonProperty("client_id")] public string ClientId { get; set; }
[JsonProperty("client_secret")] public string ClientSecret { get; set; }
[JsonIgnore] public string Instance { get; set; }
[JsonIgnore] public Scope Scope { get; set; }
}
} | 26.631579 | 80 | 0.636364 | [
"MIT"
] | Tlaster/Mastodon-Api | Mastodon/Model/AppRegistration.cs | 508 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.ChangeAnalysis.Models.Api20210401
{
using Microsoft.Azure.PowerShell.Cmdlets.ChangeAnalysis.Runtime.PowerShell;
/// <summary>
/// A PowerShell PSTypeConverter to support converting to an instance of <see cref="PropertyChange" />
/// </summary>
public partial class PropertyChangeTypeConverter : global::System.Management.Automation.PSTypeConverter
{
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>.
/// </returns>
public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue);
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="PropertyChange"
/// /> type.</param>
/// <returns>
/// <c>true</c> if the instance could be converted to a <see cref="PropertyChange" /> type, otherwise <c>false</c>
/// </returns>
public static bool CanConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return true;
}
global::System.Type type = sourceValue.GetType();
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
// we say yest to PSObjects
return true;
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
// we say yest to Hashtables/dictionaries
return true;
}
try
{
if (null != sourceValue.ToJsonString())
{
return true;
}
}
catch
{
// Not one of our objects
}
try
{
string text = sourceValue.ToString()?.Trim();
return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ChangeAnalysis.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ChangeAnalysis.Runtime.Json.JsonType.Object;
}
catch
{
// Doesn't look like it can be treated as JSON
}
return false;
}
/// <summary>
/// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>
/// </returns>
public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false;
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>
/// an instance of <see cref="PropertyChange" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the value to convert into an instance of <see cref="PropertyChange" />.</param>
/// <returns>
/// an instance of <see cref="PropertyChange" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.ChangeAnalysis.Models.Api20210401.IPropertyChange ConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return null;
}
global::System.Type type = sourceValue.GetType();
if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ChangeAnalysis.Models.Api20210401.IPropertyChange).IsAssignableFrom(type))
{
return sourceValue;
}
try
{
return PropertyChange.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());;
}
catch
{
// Unable to use JSON pattern
}
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
return PropertyChange.DeserializeFromPSObject(sourceValue);
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
return PropertyChange.DeserializeFromDictionary(sourceValue);
}
return null;
}
/// <summary>NotImplemented -- this will return <c>null</c></summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>will always return <c>null</c>.</returns>
public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null;
}
} | 51.450704 | 259 | 0.582672 | [
"MIT"
] | Agazoth/azure-powershell | src/ChangeAnalysis/generated/api/Models/Api20210401/PropertyChange.TypeConverter.cs | 7,165 | C# |
using System;
using System.Linq;
using Mono.Cecil;
using SR = System.Reflection;
namespace Insider
{
public sealed partial class Weaver : IDisposable
{
/// <summary>
/// Trigger <see cref="MessageLogged"/>, and stop weaving if
/// <paramref name="importance"/> is <see cref="MessageImportance.Error"/>.
/// </summary>
private void LogMessage(object sender, string msg, MessageImportance importance)
{
bool willThrow = importance == MessageImportance.Error
|| (importance == MessageImportance.Warning && TreatWarningsAsErrors);
MessageLogged?.Invoke(new MessageLoggedEventArgs(msg, importance, willThrow, BeingProcessed, sender.GetType()));
if (willThrow)
throw new WeavingException(msg, BeingProcessed, sender.GetType());
}
/// <summary>
/// Returns whether or not <paramref name="typeDef"/> is derived
/// from <typeparamref name="T"/>.
/// </summary>
private bool Extends<T>(TypeDefinition typeDef)
{
if (typeDef == null)
return false;
if (typeof(T).IsInterface)
{
if (typeDef.Interfaces.Any(x => x.InterfaceType.Is(typeof(T))))
return true;
return typeDef.BaseType != null
&& Extends<T>(typeDef.BaseType.AsTypeDefinition());
}
else
{
return typeDef.BaseType != null
&& (typeDef.BaseType.Is(typeof(T)) || Extends<T>(typeDef.BaseType.AsTypeDefinition()));
}
}
/// <summary>
/// Get the setting named <paramref name="key"/>, cast
/// it to <typeparamref name="T"/> if possible,
/// and return it.
/// <para>
/// If any of the above steps fails, <paramref name="defaultValue"/>
/// will be returned.
/// </para>
/// </summary>
private T GetSetting<T>(string key, T defaultValue = default(T))
{
object value;
if (Settings.TryGetValue(key, out value) && value is T)
return (T)value;
return defaultValue;
}
}
}
| 33.776119 | 124 | 0.543084 | [
"MIT"
] | 6A/insider | Insider/Weaver.Utils.cs | 2,265 | C# |
namespace TMOComposerConfig
{
partial class Form1
{
/// <summary>
/// 必要なデザイナ変数です。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 使用中のリソースをすべてクリーンアップします。
/// </summary>
/// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows フォーム デザイナで生成されたコード
/// <summary>
/// デザイナ サポートに必要なメソッドです。このメソッドの内容を
/// コード エディタで変更しないでください。
/// </summary>
private void InitializeComponent()
{
this.propertyGrid1 = new System.Windows.Forms.PropertyGrid();
this.btnSave = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// propertyGrid1
//
this.propertyGrid1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.propertyGrid1.Location = new System.Drawing.Point(12, 12);
this.propertyGrid1.Name = "propertyGrid1";
this.propertyGrid1.Size = new System.Drawing.Size(260, 210);
this.propertyGrid1.TabIndex = 0;
//
// btnSave
//
this.btnSave.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnSave.Location = new System.Drawing.Point(197, 228);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(75, 23);
this.btnSave.TabIndex = 1;
this.btnSave.Text = "&Save";
this.btnSave.UseVisualStyleBackColor = true;
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 263);
this.Controls.Add(this.btnSave);
this.Controls.Add(this.propertyGrid1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.PropertyGrid propertyGrid1;
private System.Windows.Forms.Button btnSave;
}
}
| 37.236842 | 161 | 0.570318 | [
"MIT"
] | 3dcustom/tsoview | TMOComposerConfig/Form1.Designer.cs | 3,090 | 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;
using Azure.ResourceManager.Network.Models;
namespace Azure.ResourceManager.Network
{
/// <summary> A Class representing a VirtualRouterPeering along with the instance operations that can be performed on it. </summary>
public partial class VirtualRouterPeering : ArmResource
{
/// <summary> Generate the resource identifier of a <see cref="VirtualRouterPeering"/> instance. </summary>
public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string virtualRouterName, string peeringName)
{
var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualRouters/{virtualRouterName}/peerings/{peeringName}";
return new ResourceIdentifier(resourceId);
}
private readonly ClientDiagnostics _virtualRouterPeeringClientDiagnostics;
private readonly VirtualRouterPeeringsRestOperations _virtualRouterPeeringRestClient;
private readonly VirtualRouterPeeringData _data;
/// <summary> Initializes a new instance of the <see cref="VirtualRouterPeering"/> class for mocking. </summary>
protected VirtualRouterPeering()
{
}
/// <summary> Initializes a new instance of the <see cref = "VirtualRouterPeering"/> class. </summary>
/// <param name="armClient"> The client parameters to use in these operations. </param>
/// <param name="data"> The resource that is the target of operations. </param>
internal VirtualRouterPeering(ArmClient armClient, VirtualRouterPeeringData data) : this(armClient, new ResourceIdentifier(data.Id))
{
HasData = true;
_data = data;
}
/// <summary> Initializes a new instance of the <see cref="VirtualRouterPeering"/> class. </summary>
/// <param name="armClient"> 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 VirtualRouterPeering(ArmClient armClient, ResourceIdentifier id) : base(armClient, id)
{
_virtualRouterPeeringClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Network", ResourceType.Namespace, DiagnosticOptions);
ArmClient.TryGetApiVersion(ResourceType, out string virtualRouterPeeringApiVersion);
_virtualRouterPeeringRestClient = new VirtualRouterPeeringsRestOperations(_virtualRouterPeeringClientDiagnostics, Pipeline, DiagnosticOptions.ApplicationId, BaseUri, virtualRouterPeeringApiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Gets the resource type for the operations. </summary>
public static readonly ResourceType ResourceType = "Microsoft.Network/virtualRouters/peerings";
/// <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 VirtualRouterPeeringData 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 the specified Virtual Router Peering. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async virtual Task<Response<VirtualRouterPeering>> GetAsync(CancellationToken cancellationToken = default)
{
using var scope = _virtualRouterPeeringClientDiagnostics.CreateScope("VirtualRouterPeering.Get");
scope.Start();
try
{
var response = await _virtualRouterPeeringRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw await _virtualRouterPeeringClientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false);
return Response.FromValue(new VirtualRouterPeering(ArmClient, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets the specified Virtual Router Peering. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<VirtualRouterPeering> Get(CancellationToken cancellationToken = default)
{
using var scope = _virtualRouterPeeringClientDiagnostics.CreateScope("VirtualRouterPeering.Get");
scope.Start();
try
{
var response = _virtualRouterPeeringRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken);
if (response.Value == null)
throw _virtualRouterPeeringClientDiagnostics.CreateRequestFailedException(response.GetRawResponse());
return Response.FromValue(new VirtualRouterPeering(ArmClient, 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)
{
using var scope = _virtualRouterPeeringClientDiagnostics.CreateScope("VirtualRouterPeering.GetAvailableLocations");
scope.Start();
try
{
return await ListAvailableLocationsAsync(ResourceType, cancellationToken).ConfigureAwait(false);
}
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 virtual IEnumerable<AzureLocation> GetAvailableLocations(CancellationToken cancellationToken = default)
{
using var scope = _virtualRouterPeeringClientDiagnostics.CreateScope("VirtualRouterPeering.GetAvailableLocations");
scope.Start();
try
{
return ListAvailableLocations(ResourceType, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Deletes the specified peering from a Virtual Router. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async virtual Task<VirtualRouterPeeringDeleteOperation> DeleteAsync(bool waitForCompletion, CancellationToken cancellationToken = default)
{
using var scope = _virtualRouterPeeringClientDiagnostics.CreateScope("VirtualRouterPeering.Delete");
scope.Start();
try
{
var response = await _virtualRouterPeeringRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
var operation = new VirtualRouterPeeringDeleteOperation(_virtualRouterPeeringClientDiagnostics, Pipeline, _virtualRouterPeeringRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name).Request, response);
if (waitForCompletion)
await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Deletes the specified peering from a Virtual Router. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual VirtualRouterPeeringDeleteOperation Delete(bool waitForCompletion, CancellationToken cancellationToken = default)
{
using var scope = _virtualRouterPeeringClientDiagnostics.CreateScope("VirtualRouterPeering.Delete");
scope.Start();
try
{
var response = _virtualRouterPeeringRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken);
var operation = new VirtualRouterPeeringDeleteOperation(_virtualRouterPeeringClientDiagnostics, Pipeline, _virtualRouterPeeringRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name).Request, response);
if (waitForCompletion)
operation.WaitForCompletionResponse(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
| 52.375 | 259 | 0.668074 | [
"MIT"
] | git-thomasdolan/azure-sdk-for-net | sdk/network/Azure.ResourceManager.Network/src/Generated/VirtualRouterPeering.cs | 10,894 | C# |
using System;
namespace StringTask4
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Kirjoita jotain: ");
string input = Console.ReadLine();
string inputTmp = input.ToUpper();
inputTmp = inputTmp.Replace(" ", "");
for (int i = 0; i < inputTmp.Length; i++)
{
if (inputTmp[i] != inputTmp[inputTmp.Length - 1 - i])
{
Console.WriteLine($"{input} ei ole palindromi!");
break;
}
else if(i == inputTmp.Length-1)
{
Console.WriteLine($"{input} on palindromi");
}
}
}
}
}
| 26.448276 | 69 | 0.426336 | [
"MIT"
] | akitiainen/programming-basics | string-tasks/StringTask4/StringTask4/Program.cs | 769 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Bot Framework: http://botframework.com
//
// Bot Builder SDK GitHub:
// https://github.com/Microsoft/BotBuilder
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// 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 Microsoft.Bot.Builder.Internals.Fibers;
using Microsoft.Bot.Builder.Scorables;
using Microsoft.Bot.Builder.Scorables.Internals;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Bot.Builder.Tests
{
[TestClass]
public sealed class ActionsTests : ScorableTestBase
{
public static readonly string Item = "hello";
public static readonly double Score = 1.0;
public static readonly CancellationToken Token = new CancellationTokenSource().Token;
[TestMethod]
public async Task Scorable_Where()
{
foreach (var hasScore in new[] { false, true })
{
foreach (var whereScore in new[] { false, true })
{
// arrange
IResolver resolver = new ArrayResolver(NullResolver.Instance, Item);
var mock = Mock(resolver, Score, Token, hasScore);
var test = mock.Object.Where((string item, double score) =>
{
Assert.AreEqual(Item, item);
Assert.AreEqual(Score, score);
return whereScore;
});
// act
bool actualPost = await test.TryPostAsync(resolver, Token);
// assert
bool expectedPost = hasScore && whereScore;
Assert.AreEqual(expectedPost, actualPost);
Verify(mock, resolver, Token, Once(true), Once(true), Many(hasScore), Once(expectedPost));
}
}
}
[TestMethod]
public async Task Scorable_Where_Task()
{
foreach (var hasScore in new[] { false, true })
{
foreach (var whereScore in new[] { false, true })
{
// arrange
IResolver resolver = new ArrayResolver(NullResolver.Instance, Item);
var mock = Mock(resolver, Score, Token, hasScore);
var test = mock.Object.Where(async (string item, double score) =>
{
Assert.AreEqual(Item, item);
Assert.AreEqual(Score, score);
return whereScore;
});
// act
bool actualPost = await test.TryPostAsync(resolver, Token);
// assert
bool expectedPost = hasScore && whereScore;
Assert.AreEqual(expectedPost, actualPost);
Verify(mock, resolver, Token, Once(true), Once(true), Many(hasScore), Once(expectedPost));
}
}
}
}
}
| 40.586538 | 110 | 0.593461 | [
"MIT"
] | AskYous/botbuilder | CSharp/Tests/Microsoft.Bot.Builder.Tests/ActionsTests.cs | 4,223 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace QuieroPizza.Web
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| 25.25 | 100 | 0.566007 | [
"MIT"
] | AbnerBejarano/quieropizza | QuieroPizza/QuieroPizza.Web/App_Start/RouteConfig.cs | 608 | C# |
// dnlib: See LICENSE.txt for more info
using System;
using System.Diagnostics.SymbolStore;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using dnlib.DotNet.Writer;
namespace dnlib.DotNet.Pdb.Dss {
sealed class SymbolWriter : ISymbolWriter2 {
readonly ISymUnmanagedWriter2 writer;
readonly string pdbFileName;
readonly Stream pdbStream;
bool closeCalled;
/// <summary>
/// Constructor
/// </summary>
/// <param name="writer">Writer</param>
/// <param name="pdbFileName">PDB file name</param>
public SymbolWriter(ISymUnmanagedWriter2 writer, string pdbFileName) {
if (writer == null)
throw new ArgumentNullException("writer");
if (pdbFileName == null)
throw new ArgumentNullException("pdbFileName");
this.writer = writer;
this.pdbFileName = pdbFileName;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="writer">Writer</param>
/// <param name="pdbFileName">PDB file name</param>
/// <param name="pdbStream">PDB output stream</param>
public SymbolWriter(ISymUnmanagedWriter2 writer, string pdbFileName, Stream pdbStream) {
if (writer == null)
throw new ArgumentNullException("writer");
if (pdbStream == null)
throw new ArgumentNullException("pdbStream");
this.writer = writer;
this.pdbStream = pdbStream;
this.pdbFileName = pdbFileName;
}
public void Close() {
if (closeCalled)
return;
closeCalled = true;
writer.Close();
}
public void CloseMethod() {
writer.CloseMethod();
}
public void CloseNamespace() {
writer.CloseNamespace();
}
public void CloseScope(int endOffset) {
writer.CloseScope((uint)endOffset);
}
public ISymbolDocumentWriter DefineDocument(string url, Guid language, Guid languageVendor, Guid documentType) {
ISymUnmanagedDocumentWriter unDocWriter;
writer.DefineDocument(url, ref language, ref languageVendor, ref documentType, out unDocWriter);
return unDocWriter == null ? null : new SymbolDocumentWriter(unDocWriter);
}
public void DefineField(SymbolToken parent, string name, System.Reflection.FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3) {
writer.DefineField((uint)parent.GetToken(), name, (uint)attributes, (uint)signature.Length, signature, (uint)addrKind, (uint)addr1, (uint)addr2, (uint)addr3);
}
public void DefineGlobalVariable(string name, System.Reflection.FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3) {
writer.DefineGlobalVariable(name, (uint)attributes, (uint)signature.Length, signature, (uint)addrKind, (uint)addr1, (uint)addr2, (uint)addr3);
}
public void DefineLocalVariable(string name, System.Reflection.FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3, int startOffset, int endOffset) {
writer.DefineLocalVariable(name, (uint)attributes, (uint)signature.Length, signature, (uint)addrKind, (uint)addr1, (uint)addr2, (uint)addr3, (uint)startOffset, (uint)endOffset);
}
public void DefineParameter(string name, ParameterAttributes attributes, int sequence, SymAddressKind addrKind, int addr1, int addr2, int addr3) {
writer.DefineParameter(name, (uint)attributes, (uint)sequence, (uint)addrKind, (uint)addr1, (uint)addr2, (uint)addr3);
}
public void DefineSequencePoints(ISymbolDocumentWriter document, int[] offsets, int[] lines, int[] columns, int[] endLines, int[] endColumns) {
var doc = document as SymbolDocumentWriter;
if (doc == null)
throw new ArgumentException("document isn't a non-null SymbolDocumentWriter instance");
if (offsets == null || lines == null || columns == null ||
endLines == null || endColumns == null ||
offsets.Length != lines.Length ||
offsets.Length != columns.Length ||
offsets.Length != endLines.Length ||
offsets.Length != endColumns.Length)
throw new ArgumentException("Invalid arrays");
writer.DefineSequencePoints(doc.SymUnmanagedDocumentWriter, (uint)offsets.Length, offsets, lines, columns, endLines, endColumns);
}
public void DefineSequencePoints(ISymbolDocumentWriter document, uint arraySize, int[] offsets, int[] lines, int[] columns, int[] endLines, int[] endColumns) {
var doc = document as SymbolDocumentWriter;
if (doc == null)
throw new ArgumentException("document isn't a non-null SymbolDocumentWriter instance");
writer.DefineSequencePoints(doc.SymUnmanagedDocumentWriter, arraySize, offsets, lines, columns, endLines, endColumns);
}
public void Initialize(IntPtr emitter, string filename, bool fFullBuild) {
writer.Initialize(emitter, filename, null, fFullBuild);
}
public void OpenMethod(SymbolToken method) {
writer.OpenMethod((uint)method.GetToken());
}
public void OpenNamespace(string name) {
writer.OpenNamespace(name);
}
public int OpenScope(int startOffset) {
uint result;
writer.OpenScope((uint)startOffset, out result);
return (int)result;
}
public void SetMethodSourceRange(ISymbolDocumentWriter startDoc, int startLine, int startColumn, ISymbolDocumentWriter endDoc, int endLine, int endColumn) {
var sdoc = startDoc as SymbolDocumentWriter;
if (sdoc == null)
throw new ArgumentException("startDoc isn't a non-null SymbolDocumentWriter instance");
var edoc = endDoc as SymbolDocumentWriter;
if (edoc == null)
throw new ArgumentException("endDoc isn't a non-null SymbolDocumentWriter instance");
writer.SetMethodSourceRange(sdoc.SymUnmanagedDocumentWriter, (uint)startLine, (uint)startColumn, edoc.SymUnmanagedDocumentWriter, (uint)endLine, (uint)endColumn);
}
public void SetScopeRange(int scopeID, int startOffset, int endOffset) {
writer.SetScopeRange((uint)scopeID, (uint)startOffset, (uint)endOffset);
}
public void SetSymAttribute(SymbolToken parent, string name, byte[] data) {
writer.SetSymAttribute((uint)parent.GetToken(), name, (uint)data.Length, data);
}
public void SetUnderlyingWriter(IntPtr underlyingWriter) {
throw new NotSupportedException();
}
public void SetUserEntryPoint(SymbolToken entryMethod) {
writer.SetUserEntryPoint((uint)entryMethod.GetToken());
}
public void UsingNamespace(string fullName) {
writer.UsingNamespace(fullName);
}
public byte[] GetDebugInfo(out IMAGE_DEBUG_DIRECTORY pIDD) {
uint size;
writer.GetDebugInfo(out pIDD, 0, out size, null);
var buffer = new byte[size];
writer.GetDebugInfo(out pIDD, size, out size, buffer);
return buffer;
}
public void DefineLocalVariable2(string name, uint attributes, uint sigToken, uint addrKind, uint addr1, uint addr2, uint addr3, uint startOffset, uint endOffset) {
writer.DefineLocalVariable2(name, attributes, sigToken, addrKind, addr1, addr2, addr3, startOffset, endOffset);
}
public void Initialize(MetaData metaData) {
if (pdbStream != null)
writer.Initialize(new MDEmitter(metaData), pdbFileName, new StreamIStream(pdbStream), true);
else if (!string.IsNullOrEmpty(pdbFileName))
writer.Initialize(new MDEmitter(metaData), pdbFileName, null, true);
else
throw new InvalidOperationException();
}
public void Dispose() {
Marshal.FinalReleaseComObject(writer);
}
}
}
| 39.748634 | 202 | 0.740858 | [
"MIT"
] | CodeShark-Dev/dnlib | src/DotNet/Pdb/Dss/SymbolWriter.cs | 7,276 | 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 eventbridge-2015-10-07.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.EventBridge.Model
{
/// <summary>
/// A <code>RetryPolicy</code> object that includes information about the retry policy
/// settings.
/// </summary>
public partial class RetryPolicy
{
private int? _maximumEventAgeInSeconds;
private int? _maximumRetryAttempts;
/// <summary>
/// Gets and sets the property MaximumEventAgeInSeconds.
/// <para>
/// The maximum amount of time, in seconds, to continue to make retry attempts.
/// </para>
/// </summary>
[AWSProperty(Min=60, Max=86400)]
public int MaximumEventAgeInSeconds
{
get { return this._maximumEventAgeInSeconds.GetValueOrDefault(); }
set { this._maximumEventAgeInSeconds = value; }
}
// Check to see if MaximumEventAgeInSeconds property is set
internal bool IsSetMaximumEventAgeInSeconds()
{
return this._maximumEventAgeInSeconds.HasValue;
}
/// <summary>
/// Gets and sets the property MaximumRetryAttempts.
/// <para>
/// The maximum number of retry attempts to make before the request fails. Retry attempts
/// continue until either the maximum number of attempts is made or until the duration
/// of the <code>MaximumEventAgeInSeconds</code> is met.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=185)]
public int MaximumRetryAttempts
{
get { return this._maximumRetryAttempts.GetValueOrDefault(); }
set { this._maximumRetryAttempts = value; }
}
// Check to see if MaximumRetryAttempts property is set
internal bool IsSetMaximumRetryAttempts()
{
return this._maximumRetryAttempts.HasValue;
}
}
} | 33.62963 | 109 | 0.656021 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/EventBridge/Generated/Model/RetryPolicy.cs | 2,724 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\um\d2d1.h(1009,9)
using System.Runtime.InteropServices;
namespace DirectN
{
/// <summary>
/// Allows additional parameters for factory creation.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public partial struct D2D1_FACTORY_OPTIONS
{
/// <summary>
/// Requests a certain level of debugging information from the debug layer. This parameter is ignored if the debug layer DLL is not present.
/// </summary>
public D2D1_DEBUG_LEVEL debugLevel;
}
}
| 33.055556 | 149 | 0.660504 | [
"MIT"
] | Steph55/DirectN | DirectN/DirectN/Generated/D2D1_FACTORY_OPTIONS.cs | 597 | C# |
// -----------------------------------------------------------------------
// <copyright file="CodegenProxyExtensions.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root
// for license information.
// </copyright>
// -----------------------------------------------------------------------
using System.Runtime.CompilerServices;
namespace Mlos.Core
{
/// <summary>
/// Verification extension methods for ICodegenProxy.
/// </summary>
public static class CodegenProxyExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool VerifyVariableData<T>(this PropertyProxyArray<T> array, uint elementCount, ulong objectOffset, ulong totalDataSize, ref ulong expectedDataOffset)
where T : ICodegenProxy, new()
{
ulong codegenTypeSize = default(T).CodegenTypeSize();
for (uint i = 0; i < elementCount; i++)
{
if (!((ICodegenProxy)array[(int)i]).VerifyVariableData(objectOffset + (i * codegenTypeSize), totalDataSize, ref expectedDataOffset))
{
return false;
}
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool VerifyVariableData<T>(this T proxy, int frameLength)
where T : ICodegenProxy, new()
{
ulong expectedDataOffset = proxy.CodegenTypeSize();
ulong totalDataSize = (ulong)frameLength - expectedDataOffset;
bool isValid = ((ICodegenProxy)proxy).VerifyVariableData(0, totalDataSize, ref expectedDataOffset);
isValid &= (FrameHeader.TypeSize + (int)expectedDataOffset) <= frameLength;
return isValid;
}
}
}
| 40.125 | 173 | 0.577882 | [
"MIT"
] | GindaChen/MLOS | source/Mlos.NetCore/CodegenProxyExtensions.cs | 1,926 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The interface IWorkbookFunctionsRandBetweenRequestBuilder.
/// </summary>
public partial interface IWorkbookFunctionsRandBetweenRequestBuilder
{
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
IWorkbookFunctionsRandBetweenRequest Request(IEnumerable<Option> options = null);
}
}
| 37.259259 | 153 | 0.575547 | [
"MIT"
] | MIchaelMainer/GraphAPI | src/Microsoft.Graph/Requests/Generated/IWorkbookFunctionsRandBetweenRequestBuilder.cs | 1,006 | C# |
using System.Collections.Generic;
using System.Drawing;
namespace Games
{
/// <summary>
/// Граница/обводка чего-либо
/// </summary>
public class Border : IDrawableElement
{
public IDrawable[] ElementContent => GetContent();
List<Line> borderLines = new List<Line>();
public Border(char c, Point lt, Point rt, Point lb, Point rb)
{
FromPoints(c, lt, rt, lb, rb);
}
public Border(char c, int width, int height, Padding p)
{
/*
Создать ключевые точки с учетом отступов
*/
// Convert to location index
width -= 1;
height -= 1;
var lt = new Point(0, 0); // left top
var rt = new Point(width, 0); // right top
var lb = new Point(0, height); // left bottom
var rb = new Point(width, height); // right bottom
ApplyPaddings(p, ref lt, ref rt, ref lb, ref rb);
FromPoints(c, lt, rt, lb, rb);
}
/// <summary>
/// Как работают отступы:
/// - Создается контейнер нужного размера, например если граница 8x4,
/// то создается контейнер 8 на 4.
///
/// - Если отступ 1 сверху, то верхняя граница смещается:
/// ********
/// * * -> ********
/// * * -> * *
/// ******** ********
///
/// - Если отступ сверху 1 и слева 3:
/// ********
/// * * -> *****
/// * * -> * *
/// ******** *****
///
/// - Отступ справа 4:
/// ******** ****
/// * * -> * *
/// * * -> * *
/// ******** ****
/// </summary>
private void ApplyPaddings(Padding p, ref Point lt, ref Point rt, ref Point lb, ref Point rb)
{
lt.X += p.Left;
rt.X -= p.Right;
lb.X += p.Left;
rb.X -= p.Right;
lt.Y += p.Top;
rt.Y += p.Top;
lb.Y -= p.Bottom;
rb.Y -= p.Bottom;
}
private void FromPoints(char c, Point lt, Point rt, Point lb, Point rb)
{
Line top = new Line(c, lt, rt);
Line left = new Line(c, lt, lb);
Line right = new Line(c, rt, rb);
Line button = new Line(c, lb, rb);
borderLines.Add(top);
borderLines.Add(left);
borderLines.Add(right);
borderLines.Add(button);
}
private IDrawable[] GetContent()
{
List<DrawableChar> r = new List<DrawableChar>();
foreach (Line line in borderLines)
foreach (DrawableChar c in line.ElementContent)
r.Add(c);
return r.ToArray();
}
}
} | 29.958763 | 101 | 0.423262 | [
"BSD-2-Clause"
] | diademoff/games-cli | games-cli/Drawer/Border.cs | 3,129 | 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("Jogo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Jogo")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("b4cbf4c8-aab5-45e3-bd93-cfb91c633e7e")]
// 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.297297 | 85 | 0.723359 | [
"Apache-2.0"
] | alessandrojean/LOP-2013 | classes/2013.07.24/examples/evento-keydown/Jogo/Properties/AssemblyInfo.cs | 1,420 | C# |
using System;
using NiL.JS.Core;
using NiL.JS.BaseLibrary;
using NiL.JS.Statements;
using System.Collections.Generic;
namespace NiL.JS.Expressions
{
#if !(PORTABLE || NETCORE)
[Serializable]
#endif
internal sealed class ForceAssignmentOperator : Assignment
{
public ForceAssignmentOperator(Expression first, Expression second)
: base(first, second)
{
}
public override JSValue Evaluate(Context context)
{
JSValue temp;
JSValue field = first.EvaluateForWrite(context);
if (field._valueType == JSValueType.Property)
{
return setProperty(context, field);
}
else
{
if ((field._attributes & JSValueAttributesInternal.ReadOnly) != 0 && context._strict)
throwRoError();
}
temp = second.Evaluate(context);
var oldAttributes = field._attributes;
field._attributes &= ~JSValueAttributesInternal.ReadOnly;
field.Assign(temp);
field._attributes = oldAttributes;
return temp;
}
}
#if !(PORTABLE || NETCORE)
[Serializable]
#endif
public class Assignment : Expression
{
private Arguments setterArgs;
private bool saveResult;
protected internal override bool ContextIndependent
{
get
{
return false;
}
}
internal override bool ResultInTempContainer
{
get { return false; }
}
protected internal override bool LValueModifier
{
get
{
return true;
}
}
public Assignment(Expression first, Expression second)
: base(first, second, false)
{
}
public override JSValue Evaluate(Context context)
{
JSValue temp;
JSValue field = first.EvaluateForWrite(context);
if (field._valueType == JSValueType.Property)
{
return setProperty(context, field);
}
else
{
if ((field._attributes & JSValueAttributesInternal.ReadOnly) != 0 && context._strict)
throwRoError();
}
temp = second.Evaluate(context);
field.Assign(temp);
return temp;
}
protected void throwRoError()
{
ExceptionHelper.Throw(new TypeError("Can not assign to readonly property \"" + first + "\""));
}
protected JSValue setProperty(Context context, JSValue field)
{
JSValue temp;
lock (this)
{
if (setterArgs == null)
setterArgs = new Arguments();
var fieldSource = context._objectSource;
temp = second.Evaluate(context);
if (saveResult)
{
if (tempContainer == null)
tempContainer = new JSValue();
tempContainer.Assign(temp);
temp = tempContainer;
tempContainer = null;
}
setterArgs.Reset();
setterArgs.length = 1;
setterArgs[0] = temp;
var setter = (field._oValue as Core.GsPropertyPair).setter;
if (setter != null)
setter.Call(fieldSource, setterArgs);
else if (context._strict)
ExceptionHelper.Throw(new TypeError("Can not assign to readonly property \"" + first + "\""));
if (saveResult)
tempContainer = temp;
return temp;
}
}
public override bool Build(ref CodeNode _this, int expressionDepth, Dictionary<string, VariableDescriptor> variables, CodeContext codeContext, CompilerMessageCallback message, FunctionInfo stats, Options opts)
{
#if GIVENAMEFUNCTION
if (first is VariableReference && second is FunctionExpression)
{
var fs = second as FunctionExpression;
if (fs.name == null)
fs.name = (first as VariableReference).Name;
}
#endif
base.Build(ref _this, expressionDepth, variables, codeContext, message, stats, opts);
var f = first as VariableReference ?? ((first is AssignmentOperatorCache) ? (first as AssignmentOperatorCache).Source as VariableReference : null);
if (f != null)
{
var assigns = (f.Descriptor.assignments ?? (f.Descriptor.assignments = new List<Expression>()));
if (assigns.IndexOf(this) == -1)
assigns.Add(this);
if (second is Constant)
{
var pt = second.ResultType;
if (f._descriptor.lastPredictedType == PredictedType.Unknown)
f._descriptor.lastPredictedType = pt;
}
}
var gme = first as Property;
if (gme != null)
_this = new SetProperty(gme.first, gme.second, second) { Position = Position, Length = Length };
if ((codeContext & (CodeContext.InExpression | CodeContext.InEval)) != 0)
saveResult = true;
return false;
}
public override void Optimize(ref CodeNode _this, FunctionDefinition owner, CompilerMessageCallback message, Options opts, FunctionInfo stats)
{
baseOptimize(ref _this, owner, message, opts, stats);
var vr = first as VariableReference;
if (vr != null)
{
if (vr._descriptor.IsDefined)
{
var stype = second.ResultType;
if (vr._descriptor.lastPredictedType == PredictedType.Unknown)
vr._descriptor.lastPredictedType = stype;
else if (vr._descriptor.lastPredictedType != stype)
{
if (Tools.IsEqual(vr._descriptor.lastPredictedType, stype, PredictedType.Group))
vr._descriptor.lastPredictedType = stype & PredictedType.Group;
else
{
if (message != null && stype >= PredictedType.Undefined && vr._descriptor.lastPredictedType >= PredictedType.Undefined)
message(MessageLevel.Warning, new CodeCoordinates(0, Position, Length), "Variable \"" + vr.Name + "\" has ambiguous type. It can be make impossible some optimizations and cause errors.");
vr._descriptor.lastPredictedType = PredictedType.Ambiguous;
}
}
}
else if (message != null)
message(MessageLevel.CriticalWarning, new CodeCoordinates(0, Position, Length), "Assign to undefined variable \"" + vr.Name + "\". It will declare a global variable.");
}
var gve = first as GetVariable;
if (gve != null && gve._descriptor.IsDefined && (_codeContext & CodeContext.InWith) == 0)
{
if (owner != null // не будем это применять в корневом узле. Только в функциях. Иначе это может задумываться как настройка контекста для последующего использования в Eval
&& !gve._descriptor.captured
&& (opts & Options.SuppressUselessExpressionsElimination) == 0
&& !stats.ContainsEval
&& !stats.ContainsWith) // можем упустить присваивание
{
if ((owner._body._strict || gve._descriptor.owner != owner || !owner._functionInfo.ContainsArguments) // аргументы это одна сущность с двумя именами
&& (_codeContext & CodeContext.InLoop) == 0)
{
bool last = true;
for (var i = 0; last && i < gve._descriptor.references.Count; i++)
{
last &= gve._descriptor.references[i].Eliminated || gve._descriptor.references[i].Position <= Position;
}
if (last)
{
if (second.ContextIndependent)
{
_this.Eliminated = true;
_this = Empty.Instance;
}
else
{
_this = second;
this.second = null;
this.Eliminated = true;
this.second = _this as Expression;
}
}
}
}
/*if (_this == this && second.ResultInTempContainer) // это присваивание, не последнее, без with
{
_this = new AssignmentOverReplace(first, second)
{
Position = Position,
Length = Length,
_codeContext = _codeContext
};
}*/
}
}
public override T Visit<T>(Visitor<T> visitor)
{
return visitor.Visit(this);
}
public override string ToString()
{
string f = first.ToString();
if (f[0] == '(')
f = f.Substring(1, f.Length - 2);
string t = second.ToString();
if (t[0] == '(')
t = t.Substring(1, t.Length - 2);
return "(" + f + " = " + t + ")";
}
}
}
| 38.428571 | 219 | 0.496333 | [
"BSD-3-Clause"
] | uQr/NiL.JS | NiL.JS/Expressions/Assignment.cs | 10,168 | C# |
using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using Harmony12;
using UnityEngine;
using UnityModManagerNet;
/// <summary>
/// 开始新游戏锁定和自定义特质MOD
/// </summary>
namespace LKX_NewGameActor
{
/// <summary>
/// 设置文件
/// </summary>
public class Settings : UnityModManager.ModSettings
{
/// <summary>
/// 是否锁定特性点数
/// </summary>
public bool lockAbilityNum;
/// <summary>
/// 选择特性类型
/// </summary>
public int featureType;
/// <summary>
/// 初始伙伴是否共同拥有特性
/// </summary>
public bool friend;
/// <summary>
/// 自定义特性文件路径
/// </summary>
public string file;
/// <summary>
/// 是否开启聪明过人,将占用Ability的id 1001
/// </summary>
public bool talentActor;
/// <summary>
/// 成长类型0为关闭,1为随机,2为均衡,3为早熟,4为晚熟
/// </summary>
public int developmentActor;
/// <summary>
/// 传家宝id列表
/// </summary>
public List<int> newItemsId = new List<int>();
/// <summary>
/// 选择类型
/// </summary>
public int itemsType;
/// <summary>
/// 是否义父所制
/// </summary>
public bool isStepfatherCreate;
/// <summary>
/// 同伴是否拥有
/// </summary>
public bool friendItemCreate;
/// <summary>
/// 传家宝数量
/// </summary>
public uint itemsCount;
/// <summary>
/// 保存设置
/// </summary>
/// <param name="modEntry"></param>
public override void Save(UnityModManager.ModEntry modEntry)
{
Save(this, modEntry);
}
}
public class Main
{
/// <summary>
/// umm日志
/// </summary>
public static UnityModManager.ModEntry.ModLogger logger;
/// <summary>
/// mod设置
/// </summary>
public static Settings settings;
public static Dictionary<int, string> tempItemsId = new Dictionary<int, string>();
/// <summary>
/// 获取mod根目录
/// </summary>
public static string path;
/// <summary>
/// 是否开启mod
/// </summary>
public static bool enabled;
/// <summary>
/// 载入mod。
/// </summary>
/// <param name="modEntry">mod管理器对象</param>
/// <returns></returns>
public static bool Load(UnityModManager.ModEntry modEntry)
{
Main.logger = modEntry.Logger;
Main.settings = Settings.Load<Settings>(modEntry);
Main.path = Path.Combine(modEntry.Path, "Feature");
if (Main.settings.file == null) Main.settings.file = "";
HarmonyInstance.Create(modEntry.Info.Id).PatchAll(Assembly.GetExecutingAssembly());
modEntry.OnToggle = Main.OnToggle;
modEntry.OnGUI = Main.OnGUI;
modEntry.OnSaveGUI = Main.OnSaveGUI;
return true;
}
/// <summary>
/// 确定是否激活mod
/// </summary>
/// <param name="modEntry">umm</param>
/// <param name="value">是否激活mod</param>
public static bool OnToggle(UnityModManager.ModEntry modEntry, bool value)
{
Main.enabled = value;
return true;
}
/// <summary>
/// 展示mod的设置
/// </summary>
/// <param name="modEntry">umm</param>
static void OnGUI(UnityModManager.ModEntry modEntry)
{
GUIStyle redLabelStyle = new GUIStyle();
redLabelStyle.normal.textColor = new Color(159f / 256f, 20f / 256f, 29f / 256f);
GUILayout.Label("如果status亮红灯代表失效!", redLabelStyle);
Main.settings.lockAbilityNum = GUILayout.Toggle(Main.settings.lockAbilityNum, "锁定新建人物时的特性点");
Main.settings.talentActor = GUILayout.Toggle(Main.settings.talentActor, "开启新建人物高悟性选项(新建人物特性里自己找找)。");
GUILayout.Label("选择人物成长,随机是MOD随机选择,关闭是系统自行选择,会同时修改技艺和武艺的成长但不会增加其数值。");
Main.settings.developmentActor = GUILayout.SelectionGrid(Main.settings.developmentActor, new string[] { "关闭", "随机", "均衡", "早熟", "晚成" }, 5);
Main.settings.featureType = GUILayout.SelectionGrid(Main.settings.featureType, new string[]{ "关闭", "全3级特性", "自定义" }, 3);
if (Main.settings.featureType != 0) Main.settings.friend = GUILayout.Toggle(Main.settings.friend, "是否给初始伙伴分配这些特性");
if (Main.settings.featureType == 1) GUILayout.Label("全3级特性会使游戏可玩性降低", redLabelStyle);
if (Main.settings.featureType == 2)
{
GUILayout.BeginHorizontal();
GUILayout.Label("自定义特性文件名:", GUILayout.Width(130));
string featureFilename = "";
featureFilename = GUILayout.TextArea(Main.settings.file);
if (GUI.changed) Main.settings.file = featureFilename;
GUILayout.EndHorizontal();
if ((Main.settings.file != null || Main.settings.file != "") && File.Exists(@Path.Combine(Main.path, Main.settings.file))) {
GUILayout.Label("文件存在!");
} else {
GUILayout.Label("文件不存在,请检查文件是否存放在" + Main.path + "目录中");
}
}
GUILayout.Label("传家宝选择,关闭是系统自带。传家宝直接mod内选择后添加,与特质选择不相关。");
Main.settings.itemsType = GUILayout.SelectionGrid(Main.settings.itemsType, new string[] { "关闭", "全部", "自定义" }, 3);
if (Main.settings.itemsType == 2)
{
List<int> tempList = new List<int>();
GUILayout.BeginHorizontal("Box", new GUILayoutOption[0]);
int countNum = (Main.tempItemsId.Count / 5) + 1;
int i = 0;
foreach (KeyValuePair<int, string> itemKV in Main.tempItemsId)
{
if (i == 0) GUILayout.BeginVertical("Box", new GUILayoutOption[0]);
if (GUILayout.Toggle(Main.settings.newItemsId.Contains(itemKV.Key), itemKV.Value)) {
tempList.Add(itemKV.Key);
} else {
tempList.Remove(itemKV.Key);
}
if (i == Main.tempItemsId.Count - 1) {
GUILayout.EndVertical();
break;
}
if (i % 5 == 0 && i != 0) {
GUILayout.EndVertical();
GUILayout.BeginVertical("Box", new GUILayoutOption[0]);
}
i++;
}
GUILayout.EndHorizontal();
if (GUI.changed) Main.settings.newItemsId = tempList;
}
if (Main.settings.itemsType != 0)
{
GUILayout.BeginHorizontal("Box", new GUILayoutOption[0]);
Main.settings.isStepfatherCreate = GUILayout.Toggle(Main.settings.isStepfatherCreate, "是否义父所制");
Main.settings.friendItemCreate = GUILayout.Toggle(Main.settings.friendItemCreate, "同伴也有同样传家宝");
GUILayout.EndHorizontal();
GUILayout.Label("义父所制会覆盖原有道具效果。");
GUILayout.Label("传家宝数量:" + Main.settings.itemsCount.ToString());
Main.settings.itemsCount = (uint) GUILayout.HorizontalScrollbar(Main.settings.itemsCount, 1, 1, 10);
}
}
/// <summary>
/// 保存mod的设置
/// </summary>
/// <param name="modEntry">umm</param>
static void OnSaveGUI(UnityModManager.ModEntry modEntry)
{
Main.settings.Save(modEntry);
}
}
/// <summary>
///
/// </summary>
[HarmonyPatch(typeof(Loading), "LoadBaseDate")]
public static class GetTempItemsId_For_Loading_LoadGameBaseDateStart
{
static void Postfix()
{
if (Main.enabled)
{
List<string> keys = new List<string>(GetSprites.instance.baseGameDate["Item_Date"].Trim().Split(','));
int indexTypeNum = keys.IndexOf("5");
int indexLevelNum = keys.IndexOf("8");
foreach (string items in GetSprites.instance.baseGameDate["Item_Date"].Trim().Split(new string[] { "\r\n" }, StringSplitOptions.None))
{
string[] theItemParams = items.Trim().Split(',');
if (theItemParams[indexLevelNum] == "9" && theItemParams[indexTypeNum] == "13")
Main.tempItemsId[int.Parse(theItemParams[0])] = theItemParams[2];
}
}
}
}
/// <summary>
/// 新建人物的特性点数锁定为10
/// </summary>
[HarmonyPatch(typeof(NewGame), "GetAbilityP")]
public static class LockAbilityNum_For_NewGame_GetAbilityP
{
static void Postfix(ref int __result)
{
if (Main.enabled && Main.settings.lockAbilityNum) __result = 10;
return;
}
}
[HarmonyPatch(typeof(NewGame), "Awake")]
public static class AddTalent_For_NewGame_ToNewGame
{
static void Prefix()
{
if (Main.enabled && Main.settings.talentActor)
{
Dictionary<int, Dictionary<int, string>> abilityDate = DateFile.instance.abilityDate;
if (abilityDate.ContainsKey(1001)) return;
abilityDate.Add(1001, new Dictionary<int, string>());
abilityDate[1001].Add(0, "见经识经");
abilityDate[1001].Add(1, "0");
abilityDate[1001].Add(2, "1");
abilityDate[1001].Add(3, "0");
abilityDate[1001].Add(99, "见经识经,见书识书,你从小就非常聪明,具有非常高的悟性!(来自开始新游戏锁定和自定义特质MOD)");
}
}
}
/// <summary>
/// 开始新游戏创建人物后执行
/// </summary>
[HarmonyPatch(typeof(NewGame), "SetNewGameDate")]
public static class FeatureType_For_NewGame_SetNewGameDate
{
/// <summary>
/// 这个方法是固定的,更多方法和说明去看Harmony的wiki
/// @see https://github.com/pardeike/Harmony/wiki/Patching
/// </summary>
/// <param name="___chooseAbility">NewGame的私有变量,三个下划线取得。</param>
static void Postfix(ref List<int> ___chooseAbility)
{
if (!Main.enabled) return;
//处理特性
if (Main.settings.featureType != 0)
{
string file = Main.settings.featureType == 1 ? "" : Path.Combine(Main.path, Main.settings.file);
//chooseAbility是开始游戏选择的特性,key = 6中就是
if (Main.settings.friend && ___chooseAbility.Count > 0 && ___chooseAbility.Contains(6)) ProcessingFeatureDate(10003, file);
ProcessingFeatureDate(10001, file);
}
//处理自己添加的Ability
if (___chooseAbility.Contains(1001))
{
ProcessingAbilityDate(10001);
if (___chooseAbility.Contains(6)) ProcessingAbilityDate(10003);
DateFile.instance.abilityDate.Remove(1001);
}
//处理成长
if (Main.settings.developmentActor != 0)
{
ProcessingDevelopmentDate(10001);
if (___chooseAbility.Contains(6)) ProcessingDevelopmentDate(10003);
}
//处理传家宝
if (Main.settings.itemsType != 0)
{
ProcessingItemsDate(10001);
if (___chooseAbility.Contains(6) && Main.settings.friendItemCreate) ProcessingItemsDate(10003);
}
return;
}
/// <summary>
/// 处理传家宝
/// </summary>
/// <param name="actorId">游戏人物的ID</param>
static void ProcessingItemsDate(int actorId)
{
if (Main.settings.itemsType == 1)
{
//全选的
foreach (int itemId in Main.tempItemsId.Keys)
{
int forNum = Main.settings.itemsCount > 0 || Main.settings.itemsCount < 10 ? int.Parse(Main.settings.itemsCount.ToString()) : 1;
for (int i = 0; i < forNum; i++)
{
int itemMake = DateFile.instance.MakeNewItem(itemId, 0, 0, 100, 20);
DateFile.instance.GetItem(actorId, itemMake, int.Parse(Main.settings.itemsCount.ToString()), false, -1, 0);
DateFile.instance.ChangItemDate(itemMake, 92, 900, false);
DateFile.instance.ChangItemDate(itemMake, 93, 1800, false);
if (Main.settings.isStepfatherCreate)
{
int itemDurable = int.Parse(DateFile.instance.GetItemDate(int.Parse(DateFile.instance.GetItemDate(itemMake, 999, true)), 902, true)) * 2;
DateFile.instance.itemsDate[itemMake][901] = itemDurable.ToString();
DateFile.instance.itemsDate[itemMake][902] = itemDurable.ToString();
DateFile.instance.itemsDate[itemMake][504] = "50001";
}
}
}
}
else
{
//自定义的
foreach (int itemId in Main.settings.newItemsId)
{
int forNum = Main.settings.itemsCount > 0 || Main.settings.itemsCount < 10 ? int.Parse(Main.settings.itemsCount.ToString()) : 1;
for (int i = 0; i < forNum; i++)
{
int itemMake = DateFile.instance.MakeNewItem(itemId, 0, 0, 100, 20);
DateFile.instance.GetItem(actorId, itemMake, int.Parse(Main.settings.itemsCount.ToString()), false, -1, 0);
DateFile.instance.ChangItemDate(itemMake, 92, 900, false);
DateFile.instance.ChangItemDate(itemMake, 93, 1800, false);
if (Main.settings.isStepfatherCreate)
{
int itemDurable = int.Parse(DateFile.instance.GetItemDate(int.Parse(DateFile.instance.GetItemDate(itemMake, 999, true)), 902, true)) * 2;
DateFile.instance.itemsDate[itemMake][901] = itemDurable.ToString();
DateFile.instance.itemsDate[itemMake][902] = itemDurable.ToString();
DateFile.instance.itemsDate[itemMake][504] = "50001";
}
}
}
}
}
/// <summary>
/// 成长类型指定
/// </summary>
/// <param name="actorId">游戏人物的ID</param>
static void ProcessingDevelopmentDate(int actorId)
{
Dictionary<int, string> actor;
if (DateFile.instance.actorsDate.TryGetValue(actorId, out actor))
{
int randDevelopment = Main.settings.developmentActor;
if (Main.settings.developmentActor == 1) randDevelopment = UnityEngine.Random.Range(2, 4);
actor[551] = randDevelopment.ToString();
actor[651] = randDevelopment.ToString();
}
}
/// <summary>
/// 悟性100
/// </summary>
/// <param name="actorId">游戏人物的ID</param>
static void ProcessingAbilityDate(int actorId)
{
Dictionary<int, string> actor;
if (DateFile.instance.actorsDate.TryGetValue(actorId, out actor))
{
actor[65] = "100";
}
}
/// <summary>
/// 添加特性的操作
/// </summary>
/// <param name="actorId">游戏人物的ID,10001是初代主角,10003如果有伙伴就是伙伴ID否则的话就是其他人物</param>
/// <param name="file">自定义特性文件路径</param>
static void ProcessingFeatureDate(int actorId, string file = "")
{
Dictionary<int, string> actor, array = new Dictionary<int, string>();
array = file == "" ? GetAllFeature() : GetFileValue(file);
if (DateFile.instance.actorsDate.TryGetValue(actorId, out actor))
{
string[] features = actor[101].Split('|');
foreach (string feature in features)
{
int key = int.Parse(feature.Trim());
if (array.ContainsKey(key)) array.Remove(key);
}
}
array.Remove(4003);
array.Remove(10011);
foreach (int item in array.Keys)
{
actor[101] += "|" + item.ToString();
}
DateFile.instance.actorsFeatureCache.Remove(actorId);
}
/// <summary>
/// 获得自定义特性文件
/// </summary>
/// <param name="file">文件路径默认为该mod文件夹目录下的Feature目录里</param>
/// <returns></returns>
static Dictionary<int, string> GetFileValue(string file)
{
Dictionary<int, string> array = new Dictionary<int, string>();
if (!File.Exists(file)) return array;
StreamReader sr = File.OpenText(file);
string content;
while ((content = sr.ReadLine()) != null)
{
int key = int.Parse(content.Trim());
if (!array.ContainsKey(key)) array.Add(key, "");
}
sr.Close();
return array;
}
/// <summary>
/// 获得系统内的3级特性,如添加过特性文件且为3级特性同样会获得。
/// </summary>
/// <returns></returns>
static Dictionary<int, string> GetAllFeature()
{
Dictionary<int, string> array = new Dictionary<int, string>();
foreach (KeyValuePair<int, Dictionary<int, string>> item in DateFile.instance.actorFeaturesDate)
{
if (item.Value[4] == "3") array[item.Key] = "";
}
return array;
}
}
} | 35.517857 | 165 | 0.521982 | [
"MIT"
] | ignaz-chou/Taiwu_mods | LKX_NewGameActor/Class1.cs | 19,273 | C# |
namespace Application.Sharing.Models
{
public class SharedEmailsListDTO
{
public System.Guid PhotoId { get; set; }
public string UserEmail { get; set; }
}
}
| 18.333333 | 42 | 0.721212 | [
"MIT"
] | iamprovidence/Lama | src/backend/LamaAPI/Application/Sharing/Models/SharedEmailsListDTO.cs | 167 | C# |
/*
* Copyright (c) 2014, Nick Gravelyn.
*
* 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 UnityToolbag
{
// Used to mark an 'int' field as a sorting layer so it will use the SortingLayerDrawer to display in the Inspector window.
public class SortingLayerAttribute : PropertyAttribute
{
}
}
| 35.69697 | 127 | 0.730051 | [
"Apache-2.0"
] | InCuboGames/pants-off | Assets/Scripts/HUD/SortingLayerAttribute.cs | 1,180 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace Ordering.api
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 25.666667 | 71 | 0.554731 | [
"Apache-2.0"
] | spartan73rmy/NetCoreMicroservices | Ordering.api/Program.cs | 539 | C# |
/*
* Copyright 2017 Systemic Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Sif.Framework.Model.Infrastructure;
using System;
using System.Collections.Generic;
using Environment = Sif.Framework.Model.Infrastructure.Environment;
namespace Sif.Framework.Persistence.NHibernate
{
/// <summary>
/// Unit test for EnvironmentRepository.
/// </summary>
[TestClass]
public class EnvironmentRepositoryTest
{
private IEnvironmentRepository environmentRepository;
/// <summary>
/// Use ClassInitialize to run code before running the first test in the class.
/// </summary>
/// <param name="testContext">Context information for the unit test.</param>
[ClassInitialize()]
public static void ClassInitialize(TestContext testContext)
{
DataFactory.CreateDatabase();
}
/// <summary>
/// Use ClassCleanup to run code after all tests in a class have run.
/// </summary>
[ClassCleanup()]
public static void ClassCleanup()
{
}
/// <summary>
/// Use TestInitialize to run code before running each test.
/// </summary>
[TestInitialize()]
public void TestInitialize()
{
environmentRepository = new EnvironmentRepository();
}
/// <summary>
/// Use TestCleanup to run code after each test has run.
/// </summary>
[TestCleanup()]
public void MyTestCleanup()
{
}
/// <summary>
/// Save a new Environment and then retreieve it.
/// </summary>
[TestMethod]
public void SaveAndRetrieve()
{
// Save a new Environment and then retrieve it using it's identifier.
Environment saved = DataFactory.CreateEnvironmentRequest();
Guid environmentId = environmentRepository.Save(saved);
Environment retrieved = environmentRepository.Retrieve(environmentId);
// Assert that the retrieved Environment matches the saved Environment.
Assert.AreEqual(saved.Type, retrieved.Type);
Assert.AreEqual(saved.AuthenticationMethod, retrieved.AuthenticationMethod);
Assert.AreEqual(saved.ConsumerName, retrieved.ConsumerName);
Assert.AreEqual(saved.ApplicationInfo.ApplicationKey, retrieved.ApplicationInfo.ApplicationKey);
Assert.AreEqual(saved.ApplicationInfo.SupportedInfrastructureVersion, retrieved.ApplicationInfo.SupportedInfrastructureVersion);
Assert.AreEqual(saved.ApplicationInfo.DataModelNamespace, retrieved.ApplicationInfo.DataModelNamespace);
}
/// <summary>
/// Save a new Environment and then retreieve it using an example Environment instance.
/// </summary>
[TestMethod]
public void SaveAndRetrieveByExample()
{
// Save a new Environment.
Environment saved = DataFactory.CreateEnvironmentRequest();
environmentRepository.Save(saved);
// Create an example Environment instance for use in the retrieve call.
ApplicationInfo applicationInfo = new ApplicationInfo { ApplicationKey = "UnitTesting" };
Environment example = new Environment
{
ApplicationInfo = applicationInfo,
InstanceId = saved.InstanceId,
SessionToken = saved.SessionToken,
SolutionId = saved.SolutionId,
UserToken = saved.UserToken
};
// Retrieve Environments based on the example Environment instance.
IEnumerable<Environment> environments = environmentRepository.Retrieve(example);
// Assert that the retrieved Environments match properties of the example Environment instance.
foreach (Environment retrieved in environments)
{
Assert.AreEqual(saved.ApplicationInfo.ApplicationKey, retrieved.ApplicationInfo.ApplicationKey);
Assert.AreEqual(saved.InstanceId, retrieved.InstanceId);
Assert.AreEqual(saved.SessionToken, retrieved.SessionToken);
Assert.AreEqual(saved.Id, retrieved.Id);
Assert.AreEqual(saved.SolutionId, retrieved.SolutionId);
Assert.AreEqual(saved.UserToken, retrieved.UserToken);
}
}
/// <summary>
/// Save a new Environment and then retreieve it using its session token.
/// </summary>
[TestMethod]
public void SaveAndRetrieveBySessionToken()
{
// Save a new Environment and then retrieve it based on it's session token.
Environment saved = DataFactory.CreateEnvironmentRequest();
environmentRepository.Save(saved);
Environment retrieved = environmentRepository.RetrieveBySessionToken(saved.SessionToken);
// Assert that the retrieved Environment matches the saved Environment.
Assert.AreEqual(saved.ApplicationInfo.ApplicationKey, retrieved.ApplicationInfo.ApplicationKey);
Assert.AreEqual(saved.InstanceId, retrieved.InstanceId);
Assert.AreEqual(saved.SessionToken, retrieved.SessionToken);
Assert.AreEqual(saved.Id, retrieved.Id);
Assert.AreEqual(saved.SolutionId, retrieved.SolutionId);
Assert.AreEqual(saved.UserToken, retrieved.UserToken);
}
}
}
| 39.967105 | 140 | 0.654486 | [
"Apache-2.0"
] | Access4Learning/sif3-framework-dotnet | Code/Sif3Framework/Sif.Framework.Tests/Persistence/NHibernate/EnvironmentRepositoryTest.cs | 6,077 | C# |
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace TNCServicesPlatform.StorageAPI.Controllers
{
[Route("api/storage/")]
public class StorageController_AzureStorageAPIController : Controller
{
[HttpPost]
[Route("{type}/_upload")]
public async Task<IActionResult> UploadFileToAzureBlob([FromBody] JObject item, [FromRoute] string type, [FromQuery] string source = "")
{
return this.Ok($"Uploaded {type} from {source}, content {item}");
}
}
}
| 29.809524 | 144 | 0.694888 | [
"Apache-2.0"
] | cutePanda123/TNCServicesPlatform | TNCServicesPlatform/TNCServicesPlatform.StorageAPI/Controllers/StorageController.AzureStorageAPI.cs | 628 | C# |
namespace AspNetCoreTemplate.Web
{
using System.Reflection;
using AspNetCoreTemplate.Data;
using AspNetCoreTemplate.Data.Common;
using AspNetCoreTemplate.Data.Common.Repositories;
using AspNetCoreTemplate.Data.Models;
using AspNetCoreTemplate.Data.Repositories;
using AspNetCoreTemplate.Data.Seeding;
using AspNetCoreTemplate.Services.Data;
using AspNetCoreTemplate.Services.Mapping;
using AspNetCoreTemplate.Services.Messaging;
using AspNetCoreTemplate.Web.ViewModels;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
public class Startup
{
private readonly IConfiguration configuration;
public Startup(IConfiguration configuration)
{
this.configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Framework services
// TODO: Add pooling when this bug is fixed: https://github.com/aspnet/EntityFrameworkCore/issues/9741
services.AddDbContext<ApplicationDbContext>(
options => options.UseSqlServer(this.configuration.GetConnectionString("DefaultConnection")));
services
.AddIdentity<ApplicationUser, ApplicationRole>(options =>
{
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequiredLength = 6;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddUserStore<ApplicationUserStore>()
.AddRoleStore<ApplicationRoleStore>()
.AddDefaultTokenProviders()
.AddDefaultUI(UIFramework.Bootstrap4);
services
.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddRazorPagesOptions(options =>
{
options.AllowAreas = true;
options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
});
services
.ConfigureApplicationCookie(options =>
{
options.LoginPath = "/Identity/Account/Login";
options.LogoutPath = "/Identity/Account/Logout";
options.AccessDeniedPath = "/Identity/Account/AccessDenied";
});
services
.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.Lax;
options.ConsentCookie.Name = ".AspNetCore.ConsentCookie";
});
services.AddSingleton(this.configuration);
// Identity stores
services.AddTransient<IUserStore<ApplicationUser>, ApplicationUserStore>();
services.AddTransient<IRoleStore<ApplicationRole>, ApplicationRoleStore>();
// Data repositories
services.AddScoped(typeof(IDeletableEntityRepository<>), typeof(EfDeletableEntityRepository<>));
services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));
services.AddScoped<IDbQueryRunner, DbQueryRunner>();
// Application services
services.AddTransient<IEmailSender, NullMessageSender>();
services.AddTransient<ISmsSender, NullMessageSender>();
services.AddTransient<ISettingsService, SettingsService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
AutoMapperConfig.RegisterMappings(typeof(ErrorViewModel).GetTypeInfo().Assembly);
// Seed data on application startup
using (var serviceScope = app.ApplicationServices.CreateScope())
{
var dbContext = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
if (env.IsDevelopment())
{
dbContext.Database.Migrate();
}
new ApplicationDbContextSeeder().SeedAsync(dbContext, serviceScope.ServiceProvider).GetAwaiter().GetResult();
}
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute("areaRoute", "{area:exists}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| 41.013699 | 125 | 0.61523 | [
"MIT"
] | Abhinavchamallamudi/ASP.NET-MVC-Template | ASP.NET Core/Web/AspNetCoreTemplate.Web/Startup.cs | 5,990 | C# |
using System.Linq;
using System.Collections.Generic;
namespace Mapzen.VectorData
{
public class GeometryContainer
{
public GeometryType Type = GeometryType.Unknown;
public List<Point> Points;
public List<List<Point>> LineStrings;
public List<List<List<Point>>> Polygons;
public GeometryContainer(Feature feature)
{
Type = feature.Type;
feature.HandleGeometry(new Copier(this));
}
protected class Copier : IGeometryHandler
{
GeometryContainer container;
List<Point> receiver;
public Copier(GeometryContainer container)
{
this.container = container;
}
public void OnPoint(Point point)
{
if (receiver == null)
{
container.Points = new List<Point>();
receiver = container.Points;
}
receiver.Add(point);
}
public void OnBeginLineString()
{
if (container.LineStrings == null)
{
container.LineStrings = new List<List<Point>>();
}
container.LineStrings.Add(new List<Point>());
receiver = container.LineStrings.Last();
}
public void OnEndLineString()
{
}
public void OnBeginLinearRing()
{
var polygon = container.Polygons.Last();
polygon.Add(new List<Point>());
receiver = polygon.Last();
}
public void OnEndLinearRing()
{
}
public void OnBeginPolygon()
{
if (container.Polygons == null)
{
container.Polygons = new List<List<List<Point>>>();
}
container.Polygons.Add(new List<List<Point>>());
}
public void OnEndPolygon()
{
}
}
}
}
| 26.45 | 71 | 0.472117 | [
"MIT"
] | BergWerkGIS/tangram-unity | Assets/Mapzen/VectorData/GeometryContainer.cs | 2,118 | C# |
using System;
using System.IO;
using System.Reflection;
namespace Example
{
public static class EmbeddedResourceReader
{
public static Stream LoadResourceStream(Assembly assembly, string resourceName)
{
if (assembly is null)
{
throw new ArgumentNullException(nameof(assembly));
}
if (resourceName is null)
{
throw new ArgumentNullException(nameof(resourceName));
}
resourceName = resourceName.Replace("/", ".");
return assembly.GetManifestResourceStream(resourceName);
}
}
}
| 24.692308 | 87 | 0.588785 | [
"MIT"
] | ScriptBox99/spectreconsole-errata | examples/Shared/EmbeddedResourceReader.cs | 642 | C# |
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Hackney.Core.DynamoDb;
using Hackney.Core.Testing.DynamoDb;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Net.Http;
namespace PatchesAndAreasApi.Tests
{
public class MockWebApplicationFactory<TStartup>
: WebApplicationFactory<TStartup> where TStartup : class
{
private readonly List<TableDef> _tables = new List<TableDef>
{
new TableDef {
Name = "PatchesAndAreas",
KeyName = "id",
KeyType = ScalarAttributeType.S,
GlobalSecondaryIndexes = new List<GlobalSecondaryIndex>(new[]
{
new GlobalSecondaryIndex
{
IndexName = "PatchByParentId",
KeySchema = new List<KeySchemaElement>(new[]
{
new KeySchemaElement("parentId", KeyType.HASH)
}),
ProvisionedThroughput = new ProvisionedThroughput
{
ReadCapacityUnits = 10,
WriteCapacityUnits = 10
},
Projection = new Projection { ProjectionType = ProjectionType.ALL }
}
})
}
};
public HttpClient Client { get; private set; }
public IDynamoDbFixture DynamoDbFixture { get; private set; }
public MockWebApplicationFactory()
{
EnsureEnvVarConfigured("DynamoDb_LocalMode", "true");
EnsureEnvVarConfigured("DynamoDb_LocalServiceUrl", "http://localhost:8000");
Client = CreateClient();
}
private bool _disposed;
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
if (null != DynamoDbFixture)
(DynamoDbFixture as DynamoDbFixture).Dispose();
if (null != Client)
Client.Dispose();
base.Dispose(true);
_disposed = true;
}
}
private static void EnsureEnvVarConfigured(string name, string defaultValue)
{
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable(name)))
Environment.SetEnvironmentVariable(name, defaultValue);
}
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureAppConfiguration(b => b.AddEnvironmentVariables())
.UseStartup<Startup>();
builder.ConfigureServices(services =>
{
services.ConfigureDynamoDB();
services.ConfigureDynamoDbFixture();
var serviceProvider = services.BuildServiceProvider();
DynamoDbFixture = serviceProvider.GetRequiredService<IDynamoDbFixture>();
DynamoDbFixture.EnsureTablesExist(_tables);
});
}
}
}
| 34.305263 | 91 | 0.562442 | [
"MIT"
] | LBHackney-IT/patches-and-areas-api | PatchesAndAreasApi.Tests/MockWebApplicationFactory.cs | 3,259 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.ElasticLoadBalancing
{
/// <summary>
/// Provides an Elastic Load Balancer resource, also known as a "Classic
/// Load Balancer" after the release of
/// [Application/Network Load Balancers](https://www.terraform.io/docs/providers/aws/r/lb.html).
///
/// > **NOTE on ELB Instances and ELB Attachments:** This provider currently
/// provides both a standalone ELB Attachment resource
/// (describing an instance attached to an ELB), and an ELB resource with
/// `instances` defined in-line. At this time you cannot use an ELB with in-line
/// instances in conjunction with a ELB Attachment resources. Doing so will cause a
/// conflict and will overwrite attachments.
///
///
/// ## Note on ECDSA Key Algorithm
///
/// If the ARN of the `ssl_certificate_id` that is pointed to references a
/// certificate that was signed by an ECDSA key, note that ELB only supports the
/// P256 and P384 curves. Using a certificate signed by a key using a different
/// curve could produce the error `ERR_SSL_VERSION_OR_CIPHER_MISMATCH` in your
/// browser.
///
/// > This content is derived from https://github.com/terraform-providers/terraform-provider-aws/blob/master/website/docs/r/elb.html.markdown.
/// </summary>
public partial class LoadBalancer : Pulumi.CustomResource
{
/// <summary>
/// An Access Logs block. Access Logs documented below.
/// </summary>
[Output("accessLogs")]
public Output<Outputs.LoadBalancerAccessLogs?> AccessLogs { get; private set; } = null!;
/// <summary>
/// The ARN of the ELB
/// </summary>
[Output("arn")]
public Output<string> Arn { get; private set; } = null!;
/// <summary>
/// The AZ's to serve traffic in.
/// </summary>
[Output("availabilityZones")]
public Output<ImmutableArray<string>> AvailabilityZones { get; private set; } = null!;
/// <summary>
/// Boolean to enable connection draining. Default: `false`
/// </summary>
[Output("connectionDraining")]
public Output<bool?> ConnectionDraining { get; private set; } = null!;
/// <summary>
/// The time in seconds to allow for connections to drain. Default: `300`
/// </summary>
[Output("connectionDrainingTimeout")]
public Output<int?> ConnectionDrainingTimeout { get; private set; } = null!;
/// <summary>
/// Enable cross-zone load balancing. Default: `true`
/// </summary>
[Output("crossZoneLoadBalancing")]
public Output<bool?> CrossZoneLoadBalancing { get; private set; } = null!;
/// <summary>
/// The DNS name of the ELB
/// </summary>
[Output("dnsName")]
public Output<string> DnsName { get; private set; } = null!;
/// <summary>
/// A health_check block. Health Check documented below.
/// </summary>
[Output("healthCheck")]
public Output<Outputs.LoadBalancerHealthCheck> HealthCheck { get; private set; } = null!;
/// <summary>
/// The time in seconds that the connection is allowed to be idle. Default: `60`
/// </summary>
[Output("idleTimeout")]
public Output<int?> IdleTimeout { get; private set; } = null!;
/// <summary>
/// A list of instance ids to place in the ELB pool.
/// </summary>
[Output("instances")]
public Output<ImmutableArray<string>> Instances { get; private set; } = null!;
/// <summary>
/// If true, ELB will be an internal ELB.
/// </summary>
[Output("internal")]
public Output<bool> Internal { get; private set; } = null!;
/// <summary>
/// A list of listener blocks. Listeners documented below.
/// </summary>
[Output("listeners")]
public Output<ImmutableArray<Outputs.LoadBalancerListeners>> Listeners { get; private set; } = null!;
/// <summary>
/// The name of the ELB. By default generated by this provider.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// Creates a unique name beginning with the specified
/// prefix. Conflicts with `name`.
/// </summary>
[Output("namePrefix")]
public Output<string?> NamePrefix { get; private set; } = null!;
/// <summary>
/// A list of security group IDs to assign to the ELB.
/// Only valid if creating an ELB within a VPC
/// </summary>
[Output("securityGroups")]
public Output<ImmutableArray<string>> SecurityGroups { get; private set; } = null!;
/// <summary>
/// The name of the security group that you can use as
/// part of your inbound rules for your load balancer's back-end application
/// instances. Use this for Classic or Default VPC only.
/// </summary>
[Output("sourceSecurityGroup")]
public Output<string> SourceSecurityGroup { get; private set; } = null!;
/// <summary>
/// The ID of the security group that you can use as
/// part of your inbound rules for your load balancer's back-end application
/// instances. Only available on ELBs launched in a VPC.
/// </summary>
[Output("sourceSecurityGroupId")]
public Output<string> SourceSecurityGroupId { get; private set; } = null!;
/// <summary>
/// A list of subnet IDs to attach to the ELB.
/// </summary>
[Output("subnets")]
public Output<ImmutableArray<string>> Subnets { get; private set; } = null!;
/// <summary>
/// A mapping of tags to assign to the resource.
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, object>?> Tags { get; private set; } = null!;
/// <summary>
/// The canonical hosted zone ID of the ELB (to be used in a Route 53 Alias record)
/// </summary>
[Output("zoneId")]
public Output<string> ZoneId { get; private set; } = null!;
/// <summary>
/// Create a LoadBalancer resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public LoadBalancer(string name, LoadBalancerArgs args, CustomResourceOptions? options = null)
: base("aws:elasticloadbalancing/loadBalancer:LoadBalancer", name, args ?? ResourceArgs.Empty, MakeResourceOptions(options, ""))
{
}
private LoadBalancer(string name, Input<string> id, LoadBalancerState? state = null, CustomResourceOptions? options = null)
: base("aws:elasticloadbalancing/loadBalancer:LoadBalancer", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing LoadBalancer resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static LoadBalancer Get(string name, Input<string> id, LoadBalancerState? state = null, CustomResourceOptions? options = null)
{
return new LoadBalancer(name, id, state, options);
}
}
public sealed class LoadBalancerArgs : Pulumi.ResourceArgs
{
/// <summary>
/// An Access Logs block. Access Logs documented below.
/// </summary>
[Input("accessLogs")]
public Input<Inputs.LoadBalancerAccessLogsArgs>? AccessLogs { get; set; }
[Input("availabilityZones")]
private InputList<string>? _availabilityZones;
/// <summary>
/// The AZ's to serve traffic in.
/// </summary>
public InputList<string> AvailabilityZones
{
get => _availabilityZones ?? (_availabilityZones = new InputList<string>());
set => _availabilityZones = value;
}
/// <summary>
/// Boolean to enable connection draining. Default: `false`
/// </summary>
[Input("connectionDraining")]
public Input<bool>? ConnectionDraining { get; set; }
/// <summary>
/// The time in seconds to allow for connections to drain. Default: `300`
/// </summary>
[Input("connectionDrainingTimeout")]
public Input<int>? ConnectionDrainingTimeout { get; set; }
/// <summary>
/// Enable cross-zone load balancing. Default: `true`
/// </summary>
[Input("crossZoneLoadBalancing")]
public Input<bool>? CrossZoneLoadBalancing { get; set; }
/// <summary>
/// A health_check block. Health Check documented below.
/// </summary>
[Input("healthCheck")]
public Input<Inputs.LoadBalancerHealthCheckArgs>? HealthCheck { get; set; }
/// <summary>
/// The time in seconds that the connection is allowed to be idle. Default: `60`
/// </summary>
[Input("idleTimeout")]
public Input<int>? IdleTimeout { get; set; }
[Input("instances")]
private InputList<string>? _instances;
/// <summary>
/// A list of instance ids to place in the ELB pool.
/// </summary>
public InputList<string> Instances
{
get => _instances ?? (_instances = new InputList<string>());
set => _instances = value;
}
/// <summary>
/// If true, ELB will be an internal ELB.
/// </summary>
[Input("internal")]
public Input<bool>? Internal { get; set; }
[Input("listeners", required: true)]
private InputList<Inputs.LoadBalancerListenersArgs>? _listeners;
/// <summary>
/// A list of listener blocks. Listeners documented below.
/// </summary>
public InputList<Inputs.LoadBalancerListenersArgs> Listeners
{
get => _listeners ?? (_listeners = new InputList<Inputs.LoadBalancerListenersArgs>());
set => _listeners = value;
}
/// <summary>
/// The name of the ELB. By default generated by this provider.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// Creates a unique name beginning with the specified
/// prefix. Conflicts with `name`.
/// </summary>
[Input("namePrefix")]
public Input<string>? NamePrefix { get; set; }
[Input("securityGroups")]
private InputList<string>? _securityGroups;
/// <summary>
/// A list of security group IDs to assign to the ELB.
/// Only valid if creating an ELB within a VPC
/// </summary>
public InputList<string> SecurityGroups
{
get => _securityGroups ?? (_securityGroups = new InputList<string>());
set => _securityGroups = value;
}
/// <summary>
/// The name of the security group that you can use as
/// part of your inbound rules for your load balancer's back-end application
/// instances. Use this for Classic or Default VPC only.
/// </summary>
[Input("sourceSecurityGroup")]
public Input<string>? SourceSecurityGroup { get; set; }
[Input("subnets")]
private InputList<string>? _subnets;
/// <summary>
/// A list of subnet IDs to attach to the ELB.
/// </summary>
public InputList<string> Subnets
{
get => _subnets ?? (_subnets = new InputList<string>());
set => _subnets = value;
}
[Input("tags")]
private InputMap<object>? _tags;
/// <summary>
/// A mapping of tags to assign to the resource.
/// </summary>
public InputMap<object> Tags
{
get => _tags ?? (_tags = new InputMap<object>());
set => _tags = value;
}
public LoadBalancerArgs()
{
}
}
public sealed class LoadBalancerState : Pulumi.ResourceArgs
{
/// <summary>
/// An Access Logs block. Access Logs documented below.
/// </summary>
[Input("accessLogs")]
public Input<Inputs.LoadBalancerAccessLogsGetArgs>? AccessLogs { get; set; }
/// <summary>
/// The ARN of the ELB
/// </summary>
[Input("arn")]
public Input<string>? Arn { get; set; }
[Input("availabilityZones")]
private InputList<string>? _availabilityZones;
/// <summary>
/// The AZ's to serve traffic in.
/// </summary>
public InputList<string> AvailabilityZones
{
get => _availabilityZones ?? (_availabilityZones = new InputList<string>());
set => _availabilityZones = value;
}
/// <summary>
/// Boolean to enable connection draining. Default: `false`
/// </summary>
[Input("connectionDraining")]
public Input<bool>? ConnectionDraining { get; set; }
/// <summary>
/// The time in seconds to allow for connections to drain. Default: `300`
/// </summary>
[Input("connectionDrainingTimeout")]
public Input<int>? ConnectionDrainingTimeout { get; set; }
/// <summary>
/// Enable cross-zone load balancing. Default: `true`
/// </summary>
[Input("crossZoneLoadBalancing")]
public Input<bool>? CrossZoneLoadBalancing { get; set; }
/// <summary>
/// The DNS name of the ELB
/// </summary>
[Input("dnsName")]
public Input<string>? DnsName { get; set; }
/// <summary>
/// A health_check block. Health Check documented below.
/// </summary>
[Input("healthCheck")]
public Input<Inputs.LoadBalancerHealthCheckGetArgs>? HealthCheck { get; set; }
/// <summary>
/// The time in seconds that the connection is allowed to be idle. Default: `60`
/// </summary>
[Input("idleTimeout")]
public Input<int>? IdleTimeout { get; set; }
[Input("instances")]
private InputList<string>? _instances;
/// <summary>
/// A list of instance ids to place in the ELB pool.
/// </summary>
public InputList<string> Instances
{
get => _instances ?? (_instances = new InputList<string>());
set => _instances = value;
}
/// <summary>
/// If true, ELB will be an internal ELB.
/// </summary>
[Input("internal")]
public Input<bool>? Internal { get; set; }
[Input("listeners")]
private InputList<Inputs.LoadBalancerListenersGetArgs>? _listeners;
/// <summary>
/// A list of listener blocks. Listeners documented below.
/// </summary>
public InputList<Inputs.LoadBalancerListenersGetArgs> Listeners
{
get => _listeners ?? (_listeners = new InputList<Inputs.LoadBalancerListenersGetArgs>());
set => _listeners = value;
}
/// <summary>
/// The name of the ELB. By default generated by this provider.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// Creates a unique name beginning with the specified
/// prefix. Conflicts with `name`.
/// </summary>
[Input("namePrefix")]
public Input<string>? NamePrefix { get; set; }
[Input("securityGroups")]
private InputList<string>? _securityGroups;
/// <summary>
/// A list of security group IDs to assign to the ELB.
/// Only valid if creating an ELB within a VPC
/// </summary>
public InputList<string> SecurityGroups
{
get => _securityGroups ?? (_securityGroups = new InputList<string>());
set => _securityGroups = value;
}
/// <summary>
/// The name of the security group that you can use as
/// part of your inbound rules for your load balancer's back-end application
/// instances. Use this for Classic or Default VPC only.
/// </summary>
[Input("sourceSecurityGroup")]
public Input<string>? SourceSecurityGroup { get; set; }
/// <summary>
/// The ID of the security group that you can use as
/// part of your inbound rules for your load balancer's back-end application
/// instances. Only available on ELBs launched in a VPC.
/// </summary>
[Input("sourceSecurityGroupId")]
public Input<string>? SourceSecurityGroupId { get; set; }
[Input("subnets")]
private InputList<string>? _subnets;
/// <summary>
/// A list of subnet IDs to attach to the ELB.
/// </summary>
public InputList<string> Subnets
{
get => _subnets ?? (_subnets = new InputList<string>());
set => _subnets = value;
}
[Input("tags")]
private InputMap<object>? _tags;
/// <summary>
/// A mapping of tags to assign to the resource.
/// </summary>
public InputMap<object> Tags
{
get => _tags ?? (_tags = new InputMap<object>());
set => _tags = value;
}
/// <summary>
/// The canonical hosted zone ID of the ELB (to be used in a Route 53 Alias record)
/// </summary>
[Input("zoneId")]
public Input<string>? ZoneId { get; set; }
public LoadBalancerState()
{
}
}
namespace Inputs
{
public sealed class LoadBalancerAccessLogsArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The S3 bucket name to store the logs in.
/// </summary>
[Input("bucket", required: true)]
public Input<string> Bucket { get; set; } = null!;
/// <summary>
/// The S3 bucket prefix. Logs are stored in the root if not configured.
/// </summary>
[Input("bucketPrefix")]
public Input<string>? BucketPrefix { get; set; }
/// <summary>
/// Boolean to enable / disable `access_logs`. Default is `true`
/// </summary>
[Input("enabled")]
public Input<bool>? Enabled { get; set; }
/// <summary>
/// The publishing interval in minutes. Default: 60 minutes.
/// </summary>
[Input("interval")]
public Input<int>? Interval { get; set; }
public LoadBalancerAccessLogsArgs()
{
}
}
public sealed class LoadBalancerAccessLogsGetArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The S3 bucket name to store the logs in.
/// </summary>
[Input("bucket", required: true)]
public Input<string> Bucket { get; set; } = null!;
/// <summary>
/// The S3 bucket prefix. Logs are stored in the root if not configured.
/// </summary>
[Input("bucketPrefix")]
public Input<string>? BucketPrefix { get; set; }
/// <summary>
/// Boolean to enable / disable `access_logs`. Default is `true`
/// </summary>
[Input("enabled")]
public Input<bool>? Enabled { get; set; }
/// <summary>
/// The publishing interval in minutes. Default: 60 minutes.
/// </summary>
[Input("interval")]
public Input<int>? Interval { get; set; }
public LoadBalancerAccessLogsGetArgs()
{
}
}
public sealed class LoadBalancerHealthCheckArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The number of checks before the instance is declared healthy.
/// </summary>
[Input("healthyThreshold", required: true)]
public Input<int> HealthyThreshold { get; set; } = null!;
/// <summary>
/// The interval between checks.
/// </summary>
[Input("interval", required: true)]
public Input<int> Interval { get; set; } = null!;
/// <summary>
/// The target of the check. Valid pattern is "${PROTOCOL}:${PORT}${PATH}", where PROTOCOL
/// values are:
/// * `HTTP`, `HTTPS` - PORT and PATH are required
/// * `TCP`, `SSL` - PORT is required, PATH is not supported
/// </summary>
[Input("target", required: true)]
public Input<string> Target { get; set; } = null!;
/// <summary>
/// The length of time before the check times out.
/// </summary>
[Input("timeout", required: true)]
public Input<int> Timeout { get; set; } = null!;
/// <summary>
/// The number of checks before the instance is declared unhealthy.
/// </summary>
[Input("unhealthyThreshold", required: true)]
public Input<int> UnhealthyThreshold { get; set; } = null!;
public LoadBalancerHealthCheckArgs()
{
}
}
public sealed class LoadBalancerHealthCheckGetArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The number of checks before the instance is declared healthy.
/// </summary>
[Input("healthyThreshold", required: true)]
public Input<int> HealthyThreshold { get; set; } = null!;
/// <summary>
/// The interval between checks.
/// </summary>
[Input("interval", required: true)]
public Input<int> Interval { get; set; } = null!;
/// <summary>
/// The target of the check. Valid pattern is "${PROTOCOL}:${PORT}${PATH}", where PROTOCOL
/// values are:
/// * `HTTP`, `HTTPS` - PORT and PATH are required
/// * `TCP`, `SSL` - PORT is required, PATH is not supported
/// </summary>
[Input("target", required: true)]
public Input<string> Target { get; set; } = null!;
/// <summary>
/// The length of time before the check times out.
/// </summary>
[Input("timeout", required: true)]
public Input<int> Timeout { get; set; } = null!;
/// <summary>
/// The number of checks before the instance is declared unhealthy.
/// </summary>
[Input("unhealthyThreshold", required: true)]
public Input<int> UnhealthyThreshold { get; set; } = null!;
public LoadBalancerHealthCheckGetArgs()
{
}
}
public sealed class LoadBalancerListenersArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The port on the instance to route to
/// </summary>
[Input("instancePort", required: true)]
public Input<int> InstancePort { get; set; } = null!;
/// <summary>
/// The protocol to use to the instance. Valid
/// values are `HTTP`, `HTTPS`, `TCP`, or `SSL`
/// </summary>
[Input("instanceProtocol", required: true)]
public Input<string> InstanceProtocol { get; set; } = null!;
/// <summary>
/// The port to listen on for the load balancer
/// </summary>
[Input("lbPort", required: true)]
public Input<int> LbPort { get; set; } = null!;
/// <summary>
/// The protocol to listen on. Valid values are `HTTP`,
/// `HTTPS`, `TCP`, or `SSL`
/// </summary>
[Input("lbProtocol", required: true)]
public Input<string> LbProtocol { get; set; } = null!;
/// <summary>
/// The ARN of an SSL certificate you have
/// uploaded to AWS IAM. **Note ECDSA-specific restrictions below. Only valid when `lb_protocol` is either HTTPS or SSL**
/// </summary>
[Input("sslCertificateId")]
public Input<string>? SslCertificateId { get; set; }
public LoadBalancerListenersArgs()
{
}
}
public sealed class LoadBalancerListenersGetArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The port on the instance to route to
/// </summary>
[Input("instancePort", required: true)]
public Input<int> InstancePort { get; set; } = null!;
/// <summary>
/// The protocol to use to the instance. Valid
/// values are `HTTP`, `HTTPS`, `TCP`, or `SSL`
/// </summary>
[Input("instanceProtocol", required: true)]
public Input<string> InstanceProtocol { get; set; } = null!;
/// <summary>
/// The port to listen on for the load balancer
/// </summary>
[Input("lbPort", required: true)]
public Input<int> LbPort { get; set; } = null!;
/// <summary>
/// The protocol to listen on. Valid values are `HTTP`,
/// `HTTPS`, `TCP`, or `SSL`
/// </summary>
[Input("lbProtocol", required: true)]
public Input<string> LbProtocol { get; set; } = null!;
/// <summary>
/// The ARN of an SSL certificate you have
/// uploaded to AWS IAM. **Note ECDSA-specific restrictions below. Only valid when `lb_protocol` is either HTTPS or SSL**
/// </summary>
[Input("sslCertificateId")]
public Input<string>? SslCertificateId { get; set; }
public LoadBalancerListenersGetArgs()
{
}
}
}
namespace Outputs
{
[OutputType]
public sealed class LoadBalancerAccessLogs
{
/// <summary>
/// The S3 bucket name to store the logs in.
/// </summary>
public readonly string Bucket;
/// <summary>
/// The S3 bucket prefix. Logs are stored in the root if not configured.
/// </summary>
public readonly string? BucketPrefix;
/// <summary>
/// Boolean to enable / disable `access_logs`. Default is `true`
/// </summary>
public readonly bool? Enabled;
/// <summary>
/// The publishing interval in minutes. Default: 60 minutes.
/// </summary>
public readonly int? Interval;
[OutputConstructor]
private LoadBalancerAccessLogs(
string bucket,
string? bucketPrefix,
bool? enabled,
int? interval)
{
Bucket = bucket;
BucketPrefix = bucketPrefix;
Enabled = enabled;
Interval = interval;
}
}
[OutputType]
public sealed class LoadBalancerHealthCheck
{
/// <summary>
/// The number of checks before the instance is declared healthy.
/// </summary>
public readonly int HealthyThreshold;
/// <summary>
/// The interval between checks.
/// </summary>
public readonly int Interval;
/// <summary>
/// The target of the check. Valid pattern is "${PROTOCOL}:${PORT}${PATH}", where PROTOCOL
/// values are:
/// * `HTTP`, `HTTPS` - PORT and PATH are required
/// * `TCP`, `SSL` - PORT is required, PATH is not supported
/// </summary>
public readonly string Target;
/// <summary>
/// The length of time before the check times out.
/// </summary>
public readonly int Timeout;
/// <summary>
/// The number of checks before the instance is declared unhealthy.
/// </summary>
public readonly int UnhealthyThreshold;
[OutputConstructor]
private LoadBalancerHealthCheck(
int healthyThreshold,
int interval,
string target,
int timeout,
int unhealthyThreshold)
{
HealthyThreshold = healthyThreshold;
Interval = interval;
Target = target;
Timeout = timeout;
UnhealthyThreshold = unhealthyThreshold;
}
}
[OutputType]
public sealed class LoadBalancerListeners
{
/// <summary>
/// The port on the instance to route to
/// </summary>
public readonly int InstancePort;
/// <summary>
/// The protocol to use to the instance. Valid
/// values are `HTTP`, `HTTPS`, `TCP`, or `SSL`
/// </summary>
public readonly string InstanceProtocol;
/// <summary>
/// The port to listen on for the load balancer
/// </summary>
public readonly int LbPort;
/// <summary>
/// The protocol to listen on. Valid values are `HTTP`,
/// `HTTPS`, `TCP`, or `SSL`
/// </summary>
public readonly string LbProtocol;
/// <summary>
/// The ARN of an SSL certificate you have
/// uploaded to AWS IAM. **Note ECDSA-specific restrictions below. Only valid when `lb_protocol` is either HTTPS or SSL**
/// </summary>
public readonly string? SslCertificateId;
[OutputConstructor]
private LoadBalancerListeners(
int instancePort,
string instanceProtocol,
int lbPort,
string lbProtocol,
string? sslCertificateId)
{
InstancePort = instancePort;
InstanceProtocol = instanceProtocol;
LbPort = lbPort;
LbProtocol = lbProtocol;
SslCertificateId = sslCertificateId;
}
}
}
}
| 35.491369 | 149 | 0.56851 | [
"ECL-2.0",
"Apache-2.0"
] | Dominik-K/pulumi-aws | sdk/dotnet/Elasticloadbalancing/LoadBalancer.cs | 30,842 | C# |
using System;
namespace PowerForensics.Formats
{
#region HexDumpClass
public class HexDump
{
#region Properties
public readonly string Offset;
public readonly string _00_01_02_03_04_05_06_07_08_09_0A_0B_0C_0D_0E_0F;
public readonly string Ascii;
#endregion Properties
#region Constructors
internal HexDump(string offset, string hex, string ascii)
{
Offset = offset;
_00_01_02_03_04_05_06_07_08_09_0A_0B_0C_0D_0E_0F = hex;
Ascii = ascii;
}
#endregion Constructors
#region StaticMethods
public static HexDump[] Get(byte[] bytes)
{
int i = 0;
HexDump[] dump = new HexDump[(bytes.Length / 16) + 1];
while (i < bytes.Length)
{
string hex = null;
string ascii = null;
string offset = String.Format("0x{0:X8}", i);
for (int j = 0; j < 16; j++)
{
if ((i + j) >= bytes.Length)
{
break;
}
hex += ' ';
hex += String.Format("{0:X2}", bytes[i+j]);
if (bytes[i + j] >= 0x20 && bytes[i + j] < 0x7F)
{
ascii += Convert.ToChar(bytes[i + j]);
}
else
{
ascii += '.';
}
}
dump[i / 16] = new HexDump(offset, hex, ascii);
i += 16;
}
return dump;
}
#endregion StaticMethods
}
#endregion HexDumpClass
}
| 25.855072 | 80 | 0.426009 | [
"Apache-2.0"
] | darkoperator/PowerForensics_Source | Invoke-IR.PowerForensics/PowerForensics/Formats/HexDump.cs | 1,786 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101
{
using static Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Extensions;
/// <summary>An error response from the azure resource mover service.</summary>
public partial class MoveResourceError
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IMoveResourceError.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IMoveResourceError.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IMoveResourceError FromJson(Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonObject json ? new MoveResourceError(json) : null;
}
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonObject into a new instance of <see cref="MoveResourceError" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonObject instance to deserialize from.</param>
internal MoveResourceError(Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
{_property = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonObject>("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.MoveResourceErrorBody.FromJson(__jsonProperties) : Property;}
AfterFromJson(json);
}
/// <summary>
/// Serializes this instance of <see cref="MoveResourceError" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="MoveResourceError" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonNode" />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add );
AfterToJson(ref container);
return container;
}
}
} | 67.752475 | 290 | 0.68961 | [
"MIT"
] | Amrinder-Singh29/azure-powershell | src/ResourceMover/generated/api/Models/Api202101/MoveResourceError.json.cs | 6,743 | C# |
// OData .NET Libraries
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.OData.Client
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
#endregion Namespaces
/// <summary>
/// Use this class to analyze a member assignment and figure out the
/// target path for a member-init on an entity type.
/// </summary>
/// <remarks>
/// This class will also detect cases in which the assignment
/// expression refers to cases which we shouldn't handle during
/// materialization, such as references to multiple entity types
/// as sources (or refering to no source at all).
/// </remarks>
internal class MemberAssignmentAnalysis : ALinqExpressionVisitor
{
#region Fields
/// <summary>Empty expression array; immutable.</summary>
internal static readonly Expression[] EmptyExpressionArray = new Expression[0];
/// <summary>Entity in scope for the lambda that's providing the parameter.</summary>
private readonly Expression entity;
/// <summary>A non-null value when incompatible paths were found for an entity initializer.</summary>
private Exception incompatibleAssignmentsException;
/// <summary>Whether multiple paths were found for this analysis.</summary>
private bool multiplePathsFound;
/// <summary>Path traversed from the entry field.</summary>
private List<Expression> pathFromEntity;
#endregion Fields
#region Constructor.
/// <summary>Initializes a new <see cref="MemberAssignmentAnalysis"/> instance.</summary>
/// <param name="entity">Entity in scope for the lambda that's providing the parameter.</param>
private MemberAssignmentAnalysis(Expression entity)
{
Debug.Assert(entity != null, "entity != null");
this.entity = entity;
this.pathFromEntity = new List<Expression>();
}
#endregion Constructor.
#region Properties
/// <summary>A non-null value when incompatible paths were found for an entity initializer.</summary>
internal Exception IncompatibleAssignmentsException
{
get { return this.incompatibleAssignmentsException; }
}
/// <summary>Whether multiple paths were found during analysis.</summary>
internal bool MultiplePathsFound
{
get { return this.multiplePathsFound; }
}
#endregion Properites.
#region Methods
/// <summary>Analyzes an assignment from a member-init expression.</summary>
/// <param name="entityInScope">Entity in scope for the lambda that's providing the parameter.</param>
/// <param name="assignmentExpression">The expression to analyze.</param>
/// <returns>The analysis results.</returns>
internal static MemberAssignmentAnalysis Analyze(Expression entityInScope, Expression assignmentExpression)
{
Debug.Assert(entityInScope != null, "entityInScope != null");
Debug.Assert(assignmentExpression != null, "assignmentExpression != null");
MemberAssignmentAnalysis result = new MemberAssignmentAnalysis(entityInScope);
result.Visit(assignmentExpression);
return result;
}
/// <summary>
/// Checks whether the this and a <paramref name="previous"/>
/// paths for assignments are compatible.
/// </summary>
/// <param name="targetType">Type being initialized.</param>
/// <param name="previous">Previously seen member accesses (null if this is the first).</param>
/// <returns>An exception to be thrown if assignments are not compatible; null otherwise.</returns>
/// <remarks>
/// This method does not set the IncompatibleAssignmentsException property on either
/// analysis instance.
/// </remarks>
internal Exception CheckCompatibleAssignments(Type targetType, ref MemberAssignmentAnalysis previous)
{
if (previous == null)
{
previous = this;
return null;
}
Expression[] previousExpressions = previous.GetExpressionsToTargetEntity();
Expression[] candidateExpressions = this.GetExpressionsToTargetEntity();
return CheckCompatibleAssignments(targetType, previousExpressions, candidateExpressions);
}
/// <summary>Visits the specified <paramref name="expression"/>.</summary>
/// <param name="expression">Expression to visit.</param>
/// <returns>The visited expression.</returns>
/// <remarks>This method is overriden to short-circuit analysis once an error is found.</remarks>
internal override Expression Visit(Expression expression)
{
if (this.multiplePathsFound || this.incompatibleAssignmentsException != null)
{
return expression;
}
return base.Visit(expression);
}
/// <summary>Visits a conditional expression.</summary>
/// <param name="c">Expression to visit.</param>
/// <returns>The same expression.</returns>
/// <remarks>
/// There are three expressions of interest: the Test, the IfTrue
/// branch, and the IfFalse branch. If this is a NullCheck expression,
/// then we can traverse the non-null branch, which will be the
/// correct path of the resulting value.
/// </remarks>
internal override Expression VisitConditional(ConditionalExpression c)
{
Expression result;
var nullCheck = ResourceBinder.PatternRules.MatchNullCheck(this.entity, c);
if (nullCheck.Match)
{
this.Visit(nullCheck.AssignExpression);
result = c;
}
else
{
result = base.VisitConditional(c);
}
return result;
}
/// <summary>Parameter visit method.</summary>
/// <param name="p">Parameter to visit.</param>
/// <returns>The same expression.</returns>
internal override Expression VisitParameter(ParameterExpression p)
{
if (p == this.entity)
{
if (this.pathFromEntity.Count != 0)
{
this.multiplePathsFound = true;
}
else
{
this.pathFromEntity.Add(p);
}
}
return p;
}
/// <summary>
/// NewExpression visit method
/// </summary>
/// <param name="nex">The NewExpression to visit</param>
/// <returns>The visited NewExpression</returns>
internal override NewExpression VisitNew(NewExpression nex)
{
if (nex.Members == null)
{
return base.VisitNew(nex);
}
else
{
// Member init for an anonymous type.
MemberAssignmentAnalysis previousNested = null;
foreach (var arg in nex.Arguments)
{
if (!this.CheckCompatibleAssigmentExpression(arg, nex.Type, ref previousNested))
{
break;
}
}
return nex;
}
}
/// <summary>Visits a nested member init.</summary>
/// <param name="init">Expression to visit.</param>
/// <returns>The same expression.</returns>
internal override Expression VisitMemberInit(MemberInitExpression init)
{
Expression result = init;
MemberAssignmentAnalysis previousNested = null;
foreach (var binding in init.Bindings)
{
MemberAssignment assignment = binding as MemberAssignment;
if (assignment == null)
{
continue;
}
if (!this.CheckCompatibleAssigmentExpression(assignment.Expression, init.Type, ref previousNested))
{
break;
}
}
return result;
}
/// <summary>Visits a member access expression.</summary>
/// <param name="m">Access to visit.</param>
/// <returns>The same expression.</returns>
internal override Expression VisitMemberAccess(MemberExpression m)
{
Expression result = base.VisitMemberAccess(m);
// Remove any unnecessary type conversions before checking to see if this expression is in the path.
// For this purpose we should consider an expression to be equal to that same expression with an unnecessary conversion.
// E.g. (p as Person) is the same as just p
Type convertedType;
Expression strippedExp = ResourceBinder.StripTo<Expression>(m.Expression, out convertedType);
if (this.pathFromEntity.Contains(strippedExp))
{
this.pathFromEntity.Add(m);
}
return result;
}
/// <summary>Visits a method call expression.</summary>
/// <param name="call">Method call to visit.</param>
/// <returns>The same call.</returns>
internal override Expression VisitMethodCall(MethodCallExpression call)
{
// When we .Select(), the source of the enumeration is what we contribute
// eg: p => p.Cities.Select(c => c) ::= Select(p.Cities, c => c);
if (ReflectionUtil.IsSequenceMethod(call.Method, SequenceMethod.Select))
{
this.Visit(call.Arguments[0]);
return call;
}
return base.VisitMethodCall(call);
}
/// <summary>Gets the expressions that go beyond the last entity.</summary>
/// <returns>An array of member expressions coming after the last entity.</returns>
/// <remarks>Currently a single member access is supported.</remarks>
internal Expression[] GetExpressionsBeyondTargetEntity()
{
Debug.Assert(!this.multiplePathsFound, "this.multiplePathsFound -- otherwise GetExpressionsToTargetEntity won't return reliable (consistent) results");
if (this.pathFromEntity.Count <= 1)
{
return EmptyExpressionArray;
}
Expression[] result = new Expression[1];
result[0] = this.pathFromEntity[this.pathFromEntity.Count - 1];
return result;
}
/// <summary>Gets the expressions that "walk down" to the last entity, ignoring the last expression.</summary>
/// <returns>An array of member expressions down to, but excluding, the last entity.</returns>
internal Expression[] GetExpressionsToTargetEntity()
{
return this.GetExpressionsToTargetEntity(true);
}
/// <summary>Gets the expressions that "walk down" to the last entity.</summary>
/// <param name="ignoreLastExpression">whether to ignore the last expression or not.</param>
/// <returns>An array of member expressions down to the last entity.</returns>
internal Expression[] GetExpressionsToTargetEntity(bool ignoreLastExpression)
{
Debug.Assert(!this.multiplePathsFound, "this.multiplePathsFound -- otherwise GetExpressionsToTargetEntity won't return reliable (consistent) results");
int numOfExpressionsToIgnore = ignoreLastExpression ? 1 : 0;
if (this.pathFromEntity.Count <= numOfExpressionsToIgnore)
{
return EmptyExpressionArray;
}
Expression[] result = new Expression[this.pathFromEntity.Count - numOfExpressionsToIgnore];
for (int i = 0; i < result.Length; i++)
{
result[i] = this.pathFromEntity[i];
}
return result;
}
/// <summary>
/// Checks whether the <paramref name="previous"/> and <paramref name="candidate"/>
/// paths for assignments are compatible.
/// </summary>
/// <param name="targetType">Type being initialized.</param>
/// <param name="previous">Previously seen member accesses.</param>
/// <param name="candidate">Member assignments under evaluate.</param>
/// <returns>An exception to be thrown if assignments are not compatible; null otherwise.</returns>
private static Exception CheckCompatibleAssignments(Type targetType, Expression[] previous, Expression[] candidate)
{
Debug.Assert(targetType != null, "targetType != null");
Debug.Assert(previous != null, "previous != null");
Debug.Assert(candidate != null, "candidate != null");
if (previous.Length != candidate.Length)
{
throw CheckCompatibleAssignmentsFail(targetType, previous, candidate);
}
for (int i = 0; i < previous.Length; i++)
{
Expression p = previous[i];
Expression c = candidate[i];
if (p.NodeType != c.NodeType)
{
throw CheckCompatibleAssignmentsFail(targetType, previous, candidate);
}
if (p == c)
{
continue;
}
if (p.NodeType != ExpressionType.MemberAccess)
{
return CheckCompatibleAssignmentsFail(targetType, previous, candidate);
}
if (((MemberExpression)p).Member.Name != ((MemberExpression)c).Member.Name)
{
return CheckCompatibleAssignmentsFail(targetType, previous, candidate);
}
}
return null;
}
/// <summary>Creates an exception to be used when CheckCompatibleAssignment fails.</summary>
/// <param name="targetType">Type being initialized.</param>
/// <param name="previous">Previously seen member accesses.</param>
/// <param name="candidate">Member assignments under evaluate.</param>
/// <returns>A new exception with diagnostic information.</returns>
private static Exception CheckCompatibleAssignmentsFail(Type targetType, Expression[] previous, Expression[] candidate)
{
Debug.Assert(targetType != null, "targetType != null");
Debug.Assert(previous != null, "previous != null");
Debug.Assert(candidate != null, "candidate != null");
string message = Strings.ALinq_ProjectionMemberAssignmentMismatch(targetType.FullName, previous.LastOrDefault(), candidate.LastOrDefault());
return new NotSupportedException(message);
}
/// <summary>
/// If there is a MemberInitExpression 'new Person { ID = p.ID, Friend = new Person { ID = p.Friend.ID }}'
/// or a NewExpression 'new { ID = p.ID, Friend = new { ID = p.Friend.ID }}',
/// this method validates against the RHS of the member assigment, the expression "p.ID" for example.
/// </summary>
/// <param name="expressionToAssign">The expression to validate.</param>
/// <param name="initType">Type of the MemberInit or the New expression.</param>
/// <param name="previousNested">The outter nested initializer of the current initializer we are checking.</param>
/// <returns>true if the expression to assign is fine; false otherwise.</returns>
private bool CheckCompatibleAssigmentExpression(Expression expressionToAssign, Type initType, ref MemberAssignmentAnalysis previousNested)
{
MemberAssignmentAnalysis nested = MemberAssignmentAnalysis.Analyze(this.entity, expressionToAssign);
if (nested.MultiplePathsFound)
{
this.multiplePathsFound = true;
return false;
}
// When we're visitng a nested entity initializer, we're exactly one level above that.
Exception incompatibleException = nested.CheckCompatibleAssignments(initType, ref previousNested);
if (incompatibleException != null)
{
this.incompatibleAssignmentsException = incompatibleException;
return false;
}
if (this.pathFromEntity.Count == 0)
{
this.pathFromEntity.AddRange(nested.GetExpressionsToTargetEntity());
}
return true;
}
#endregion Methods
}
}
| 41.477435 | 163 | 0.602966 | [
"Apache-2.0"
] | manukahn/odata.net | src/Client/Build.Silverlight/Microsoft/OData/Client/MemberAssignmentAnalysis.cs | 17,462 | C# |
namespace RPGCore.Inventories
{
public class ClingyCondition : ItemCondition
{
public ClingyCondition ()
{
}
public override bool IsValid (ItemSurrogate item)
{
return item != null;
}
}
}
| 12.352941 | 51 | 0.680952 | [
"Apache-2.0"
] | li5414/RPGCore | RPGCore/Assets/RPGCore/Scripts/Inventory/Item Slot/Conditions/ClingyCondition.cs | 212 | C# |
// SPDX-License-Identifier: MIT
// Copyright © 2021 Oscar Björhn, Petter Löfgren and contributors
namespace Daf.Core.Adf.JsonStructure
{
public interface IJsonInterface
{
public string Name { get; set; }
}
}
| 19.545455 | 65 | 0.739535 | [
"MIT"
] | data-automation-framework/daf-core-adf | Daf.Core.Adf/JsonStructure/JsonInterface.cs | 220 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Entity.Framework;
namespace Entity.Components
{
public class VEHICLE_USER : Entity.Framework.EntityBase
{
private string _pK_ID;
private string _vEHICLEUSER;
public string VEHICLEUSER
{
get { return _vEHICLEUSER; }
set { _vEHICLEUSER = value; }
}
public string PK_ID
{
get { return _pK_ID; }
set { _pK_ID = value; }
}
#region Methods
public VEHICLE_USER()
: base(string.Empty)
{
}
#endregion
}
}
| 16.972222 | 59 | 0.584288 | [
"MIT"
] | UnIQSaQYA/FleetManagementSystem | transportationArchitecture/Entity/Components/VEHICLE_USER.cs | 613 | C# |
namespace BasicHttpServer.Server.HTTP
{
public enum StatusCode
{
OK = 200,
Found = 302,
BadRequest = 400,
Unauthorized = 401,
NotFound= 404
}
}
| 16.416667 | 38 | 0.538071 | [
"MIT"
] | MirelaMileva/SoftUni-CSharp-Web-Basics-January2022 | SUHttpServer/SUHttpServer.HttpServer/HTTP/StatusCode.cs | 199 | C# |
using UnityEngine;
namespace UniSimpleProfiler.Internal
{
/// <summary>
/// FPS を計測する構造体
/// </summary>
public class FPSCounter
{
//====================================================================================
// 定数
//====================================================================================
private const float INTERVAL = 0.5f;
//====================================================================================
// 変数
//====================================================================================
private float m_accum ;
private int m_frames ;
private float m_timeleft ;
private float m_fps ;
//====================================================================================
// プロパティ
//====================================================================================
public float Fps => m_fps;
//====================================================================================
// 関数
//====================================================================================
/// <summary>
/// 更新する時に呼び出します
/// </summary>
public void Update()
{
m_timeleft -= Time.deltaTime;
m_accum += Time.timeScale / Time.deltaTime;
m_frames++;
if ( 0 < m_timeleft ) return;
m_fps = m_accum / m_frames;
m_timeleft = INTERVAL;
m_accum = 0;
m_frames = 0;
}
}
} | 28.520833 | 88 | 0.299489 | [
"MIT"
] | baba-s/uni-simple-profiler | app/Assets/UniSimpleProfiler/Scripts/FPSCounter.cs | 1,433 | C# |
// we might want to read from files idk lol ¯\_(ツ)_/¯
namespace FestivalManager.Core.IO
{
using FestivalManager.Core.IO.Contracts;
using System.IO;
public class FileReader: IReader
{
private readonly StreamReader reader;
public FileReader(string contents)
{
this.reader = new StreamReader(new FileStream(contents, FileMode.Open, FileAccess.Read & FileAccess.Write));
}
public string ReadLine() => this.reader.ReadLine();
}
} | 26.222222 | 112 | 0.697034 | [
"MIT"
] | Ivelin153/SoftUni | C# Fundamentals/FestivalManager/Core/IO/FileReader.cs | 478 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Dapper.Contrib.Extensions;
using invert_api.Infrastructure;
using invert_api.Models;
using invert_api.Models.Response;
using Microsoft.Extensions.Configuration;
namespace invert_api.Repositories
{
public class InsertMessageRepository
{
private readonly string _connectionString;
public InsertMessageRepository(IConfiguration configuration)
{
_connectionString = configuration.GetConnectionString("Database");
}
public async Task<Response<long>> UploadMessageAsync(MESSAGE message)
{
int result = 0;
using (var context = DbContextFactory.GetContext(_connectionString))
{
try
{
result = await context.InsertAsync(message);
}
catch(Exception ex)
{
return new Response<long>(ex.Message);
}
}
if (result < 0)
{
return new Response<long>("Insert Message Failed.");
}
return new Response<long>(result);
}
public async Task<Response> UploadTargetedListAsync(IEnumerable<TARGET_MESSAGE> targets)
{
long result = 0;
using (var context = DbContextFactory.GetContext(_connectionString))
{
result = await context.InsertAsync(targets);
}
if (result > 0)
{
return new Response("Insert Message Failed.");
}
return new Response();
}
}
} | 27.770492 | 96 | 0.565525 | [
"MIT"
] | behoyh/invert-api | src/Repositories/InsertMessageRepository.cs | 1,696 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class AsKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAtRoot_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalStatement_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalVariableDeclaration_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterExpr()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = goo $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDottedName()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = goo.Current $$"));
}
[WorkItem(543041, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543041")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterVarInForLoop()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"for (var $$"));
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeFirstStringHole()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var x = ""\{0}$$\{1}\{2}"""));
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBetweenStringHoles()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var x = ""\{0}\{1}$$\{2}"""));
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterStringHoles()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var x = ""\{0}\{1}\{2}$$"""));
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLastStringHole()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var x = ""\{0}\{1}\{2}"" $$"));
}
[WorkItem(1736, "https://github.com/dotnet/roslyn/issues/1736")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotWithinNumericLiteral()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var x = .$$0;"));
}
[WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAsync()
{
await VerifyAbsenceAsync(
@"
using System;
class C
{
void Goo()
{
Bar(async $$
}
void Bar(Func<int, string> f)
{
}
}");
}
[WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterMethodReference()
{
await VerifyAbsenceAsync(
@"
using System;
class C {
void M() {
var v = Console.WriteLine $$");
}
[WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAnonymousMethod()
{
await VerifyAbsenceAsync(
@"
using System;
class C {
void M() {
Action a = delegate { } $$");
}
[WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterLambda1()
{
await VerifyAbsenceAsync(
@"
using System;
class C {
void M() {
Action b = (() => 0) $$");
}
[WorkItem(8319, "https://github.com/dotnet/roslyn/issues/8319")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterLambda2()
{
await VerifyAbsenceAsync(
@"
using System;
class C {
void M() {
Action b = () => {} $$");
}
}
}
| 30.6 | 92 | 0.628624 | [
"MIT"
] | 06needhamt/roslyn | src/EditorFeatures/CSharpTest2/Recommendations/AsKeywordRecommenderTests.cs | 5,969 | C# |
namespace Relm.UI.States
{
public enum TextBoxPiece
{
Left,
Center,
Right
}
} | 12.666667 | 28 | 0.508772 | [
"MIT"
] | slyprid/Relm | Relm/Relm/UI/States/TextBoxPiece.cs | 116 | C# |
using System;
namespace Windows.UI.Xaml.Controls
{
public partial class ContentDialogButtonClickEventArgs
{
private readonly Action<ContentDialogButtonClickEventArgs> _deferralAction;
internal ContentDialogButtonClickEventArgs(Action<ContentDialogButtonClickEventArgs> deferralAction)
{
_deferralAction = deferralAction;
}
public bool Cancel { get; set; }
internal ContentDialogButtonClickDeferral Deferral { get; private set; }
public global::Windows.UI.Xaml.Controls.ContentDialogButtonClickDeferral GetDeferral()
=> Deferral = new ContentDialogButtonClickDeferral(() => _deferralAction(this));
}
}
| 30 | 102 | 0.801587 | [
"Apache-2.0"
] | 06needhamt/uno | src/Uno.UI/UI/Xaml/Controls/ContentDialog/ContentDialogButtonClickEventArgs.cs | 630 | C# |
#if !SILVERLIGHT
using System;
using System.Collections;
namespace ServiceStack.Messaging
{
public class InMemoryTransientMessageService
: TransientMessageServiceBase
{
internal InMemoryTransientMessageFactory Factory { get; set; }
public InMemoryTransientMessageService()
: this(null)
{
}
public InMemoryTransientMessageService(InMemoryTransientMessageFactory factory)
{
this.Factory = factory ?? new InMemoryTransientMessageFactory(this);
this.Factory.MqFactory.MessageReceived += factory_MessageReceived;
}
void factory_MessageReceived(object sender, EventArgs e)
{
//var Factory = (MessageQueueClientFactory) sender;
this.Start();
}
public override IMessageFactory MessageFactory
{
get { return Factory; }
}
public MessageQueueClientFactory MessageQueueFactory
{
get { return Factory.MqFactory; }
}
}
}
#endif | 22.925 | 82 | 0.729553 | [
"BSD-3-Clause"
] | niemyjski/ServiceStack | src/ServiceStack.Common/Messaging/InMemoryTransientMessageService.cs | 917 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Logic.V20160601
{
/// <summary>
/// The integration account map.
/// </summary>
[AzureNativeResourceType("azure-native:logic/v20160601:Map")]
public partial class Map : Pulumi.CustomResource
{
/// <summary>
/// The changed time.
/// </summary>
[Output("changedTime")]
public Output<string> ChangedTime { get; private set; } = null!;
/// <summary>
/// The content.
/// </summary>
[Output("content")]
public Output<string?> Content { get; private set; } = null!;
/// <summary>
/// The content link.
/// </summary>
[Output("contentLink")]
public Output<Outputs.ContentLinkResponse> ContentLink { get; private set; } = null!;
/// <summary>
/// The content type.
/// </summary>
[Output("contentType")]
public Output<string?> ContentType { get; private set; } = null!;
/// <summary>
/// The created time.
/// </summary>
[Output("createdTime")]
public Output<string> CreatedTime { get; private set; } = null!;
/// <summary>
/// The resource location.
/// </summary>
[Output("location")]
public Output<string?> Location { get; private set; } = null!;
/// <summary>
/// The map type.
/// </summary>
[Output("mapType")]
public Output<string> MapType { get; private set; } = null!;
/// <summary>
/// The metadata.
/// </summary>
[Output("metadata")]
public Output<object?> Metadata { get; private set; } = null!;
/// <summary>
/// Gets the resource name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The parameters schema of integration account map.
/// </summary>
[Output("parametersSchema")]
public Output<Outputs.IntegrationAccountMapPropertiesResponseParametersSchema?> ParametersSchema { get; private set; } = null!;
/// <summary>
/// The resource tags.
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// Gets the resource type.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a Map resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public Map(string name, MapArgs args, CustomResourceOptions? options = null)
: base("azure-native:logic/v20160601:Map", name, args ?? new MapArgs(), MakeResourceOptions(options, ""))
{
}
private Map(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:logic/v20160601:Map", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:logic/v20160601:Map"},
new Pulumi.Alias { Type = "azure-native:logic:Map"},
new Pulumi.Alias { Type = "azure-nextgen:logic:Map"},
new Pulumi.Alias { Type = "azure-native:logic/latest:Map"},
new Pulumi.Alias { Type = "azure-nextgen:logic/latest:Map"},
new Pulumi.Alias { Type = "azure-native:logic/v20150801preview:Map"},
new Pulumi.Alias { Type = "azure-nextgen:logic/v20150801preview:Map"},
new Pulumi.Alias { Type = "azure-native:logic/v20180701preview:Map"},
new Pulumi.Alias { Type = "azure-nextgen:logic/v20180701preview:Map"},
new Pulumi.Alias { Type = "azure-native:logic/v20190501:Map"},
new Pulumi.Alias { Type = "azure-nextgen:logic/v20190501:Map"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing Map resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static Map Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new Map(name, id, options);
}
}
public sealed class MapArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The content.
/// </summary>
[Input("content")]
public Input<string>? Content { get; set; }
/// <summary>
/// The content type.
/// </summary>
[Input("contentType")]
public Input<string>? ContentType { get; set; }
/// <summary>
/// The integration account name.
/// </summary>
[Input("integrationAccountName", required: true)]
public Input<string> IntegrationAccountName { get; set; } = null!;
/// <summary>
/// The resource location.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// The integration account map name.
/// </summary>
[Input("mapName")]
public Input<string>? MapName { get; set; }
/// <summary>
/// The map type.
/// </summary>
[Input("mapType", required: true)]
public Input<Pulumi.AzureNative.Logic.V20160601.MapType> MapType { get; set; } = null!;
/// <summary>
/// The metadata.
/// </summary>
[Input("metadata")]
public Input<object>? Metadata { get; set; }
/// <summary>
/// The parameters schema of integration account map.
/// </summary>
[Input("parametersSchema")]
public Input<Inputs.IntegrationAccountMapPropertiesParametersSchemaArgs>? ParametersSchema { get; set; }
/// <summary>
/// The resource group name.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// The resource tags.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
public MapArgs()
{
}
}
}
| 35.863636 | 135 | 0.554753 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Logic/V20160601/Map.cs | 7,890 | C# |
using System;
using System.Linq;
namespace _04.CountOccurrencesofLargerNumbersinArray
{
public class Program
{
public static void Main()
{
double[] numbers = Console.ReadLine().Split(' ').Select(double.Parse).ToArray();
double number = double.Parse(Console.ReadLine());
int biggerThanNumberCount = 0;
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] > number)
{
biggerThanNumberCount += 1;
}
}
Console.WriteLine(biggerThanNumberCount);
}
}
}
| 24.730769 | 92 | 0.51633 | [
"MIT"
] | vankatalp360/Programming-Fundamentals-2017 | Simple Arrays - Exercises/04.CountOccurrencesofLargerNumbersinArray/04.CountOccurrencesofLargerNumbersinArray.cs | 645 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Microsoft.Framework.Configuration.CommandLine.Test")]
[assembly: AssemblyMetadata("Serviceable", "True")] | 46.25 | 111 | 0.794595 | [
"Apache-2.0"
] | tugberkugurlu/Configuration | src/Microsoft.Framework.Configuration.CommandLine/Properties/AssemblyInfo.cs | 372 | 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("03. Phonebook")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("03. Phonebook")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("696cbfbe-5694-43c6-bf41-e3b5bedc5d59")]
// 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.675676 | 84 | 0.745337 | [
"Apache-2.0"
] | vencislav-viktorov/VS-Console-App | Tech Module Extended/6.Arrays - More Exercises/03. Phonebook/Properties/AssemblyInfo.cs | 1,397 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace SessionManager
{
public static class SharpSession
{
/// <summary>
/// Session dictionary key:String , Value:Dynamic
/// </summary>
public static Dictionary<string, dynamic> Session { get; set; }
public static int SessionId { get; set; }
public static string SessionName { get; set; }
#region SessionMethods
/// <summary>
/// Creates a new session and adds a new sessionID
/// </summary>
public static void SessionStart()
{
Session = new Dictionary<string, dynamic>();
SessionId = new Random().Next();
}
/// <summary>
/// Destory session
/// </summary>
public static void SessionDestroy()
{
Session = null;
}
/// <summary>
/// Re initialize session
/// </summary>
public static void SessionUnset()
{
Session = new Dictionary<string, dynamic>();
}
/// <summary>
/// Sets null to all keys
/// </summary>
public static void SessionReset()
{
var keys = Session.Keys.ToList();
foreach (var key in keys) Session[key] = null;
}
/// <summary>
/// Returns a new session id
/// </summary>
/// <returns>integer</returns>
public static int CreateId()
{
return new Random().Next();
}
/// <summary>
/// Creats and sets a new sessionID
/// </summary>
public static void RegenerateId()
{
SessionId = new Random().Next();
}
#endregion
#region FeatureMethods
/// <summary>
/// This Will Return the T type data
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public static T Get<T>(string key)
{
return (T) Session[key];
}
public static void Set<T>(string key, T value)
{
Session[key] = value;
}
#endregion
}
} | 24 | 71 | 0.490351 | [
"BSD-3-Clause"
] | iQuantile-LLC/SharpSession | SessionManager/SharpSession.cs | 2,282 | C# |
using OceanChip.Common.Extensions;
using System.Collections.Generic;
using System.Linq;
namespace OceanChip.Queue.Clients.Consumers
{
public class ProcessQueue
{
private readonly object _lockObj = new object();
private readonly SortedDictionary<long, ConsumingMessage> _messageDict = new SortedDictionary<long, ConsumingMessage>();
private long _consumedQueueOffset = -1L;
private long _previousConsumeQueueOffset = -1L;
private long _maxQueueOffset = -1L;
private int _messageCount = 0;
public void Reset()
{
lock (_lockObj)
{
_messageDict.Clear();
_consumedQueueOffset = -1;
_previousConsumeQueueOffset = -1;
_maxQueueOffset = -1;
_messageCount = 0;
}
}
public bool TryUpdatePreviousConsumeQueueOffset(long current)
{
if(current !=_previousConsumeQueueOffset)
{
_previousConsumeQueueOffset = current;
return true;
}
return false;
}
public void MarkAllConsumeingMessageIgnored()
{
lock (_lockObj)
{
var existingConsumingMessages = _messageDict.Values.ToList();
foreach(var consumingMessage in existingConsumingMessages)
{
consumingMessage.IsIgnored = true;
}
}
}
public void AddMessages(IEnumerable<ConsumingMessage> messages)
{
lock (_lockObj)
{
foreach(var msg in messages)
{
if (_messageDict.ContainsKey(msg.Message.QueueOffset))
continue;
_messageDict[msg.Message.QueueOffset] = msg;
if(_maxQueueOffset==-1 && msg.Message.QueueOffset >= 0)
{
_maxQueueOffset = msg.Message.QueueOffset;
}else if (msg.Message.QueueOffset > _maxQueueOffset)
{
_maxQueueOffset = msg.Message.QueueOffset;
}
_messageCount++;
}
}
}
public void RemoveMessage(ConsumingMessage message)
{
lock (_lockObj)
{
if (_messageDict.Remove(message.Message.QueueOffset))
{
if (_messageDict.Keys.IsNotEmpty())
{
_consumedQueueOffset = _messageDict.Keys.First() - 1;
}
else
{
_consumedQueueOffset = _maxQueueOffset; ;
}
_messageCount--;
}
}
}
public int GetMessageCount()
{
return _messageCount;
}
public long GetConsumedQueueOffset()
{
return _consumedQueueOffset;
}
}
} | 32.93617 | 128 | 0.494832 | [
"Apache-2.0"
] | OceanChip/OQueue | OQueue/Clients/Consumers/ProcessQueue.cs | 3,098 | C# |
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
using NUnit.Framework;
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using ICSharpCode.SharpZipLib.Tests.TestSupport;
namespace ICSharpCode.SharpZipLib.Tests.Zip
{
[TestFixture]
public class ZipEncryptionHandling
{
[Test]
[Category("Encryption")]
[Category("Zip")]
[TestCase(CompressionMethod.Stored)]
[TestCase(CompressionMethod.Deflated)]
public void Aes128Encryption(CompressionMethod compressionMethod)
{
CreateZipWithEncryptedEntries("foo", 128, compressionMethod);
}
[Test]
[Category("Encryption")]
[Category("Zip")]
[TestCase(CompressionMethod.Stored)]
[TestCase(CompressionMethod.Deflated)]
public void Aes256Encryption(CompressionMethod compressionMethod)
{
CreateZipWithEncryptedEntries("foo", 256, compressionMethod);
}
[Test]
[Category("Encryption")]
[Category("Zip")]
[TestCase(CompressionMethod.Stored)]
[TestCase(CompressionMethod.Deflated)]
public void ZipCryptoEncryption(CompressionMethod compressionMethod)
{
CreateZipWithEncryptedEntries("foo", 0, compressionMethod);
}
/// <summary>
/// Test Known zero length encrypted entries with ZipOutputStream.
/// These are entries where the entry size is set to 0 ahead of time, so that PutNextEntry will fill in the header and there will be no patching.
/// Test with Zip64 on and off, as the logic is different for the two.
/// </summary>
[Test]
public void ZipOutputStreamEncryptEmptyEntries(
[Values] UseZip64 useZip64,
[Values(0, 128, 256)] int keySize,
[Values(CompressionMethod.Stored, CompressionMethod.Deflated)] CompressionMethod compressionMethod)
{
using (var ms = new MemoryStream())
{
using (var zipOutputStream = new ZipOutputStream(ms))
{
zipOutputStream.IsStreamOwner = false;
zipOutputStream.Password = "password";
zipOutputStream.UseZip64 = useZip64;
ZipEntry zipEntry = new ZipEntry("emptyEntry")
{
AESKeySize = keySize,
CompressionMethod = compressionMethod,
CompressedSize = 0,
Crc = 0,
Size = 0,
};
zipOutputStream.PutNextEntry(zipEntry);
zipOutputStream.CloseEntry();
}
VerifyZipWith7Zip(ms, "password");
}
}
[Test]
[Category("Encryption")]
[Category("Zip")]
public void ZipFileAesDecryption()
{
var password = "password";
using (var ms = new MemoryStream())
{
WriteEncryptedZipToStream(ms, password, 256);
var zipFile = new ZipFile(ms)
{
Password = password
};
foreach (ZipEntry entry in zipFile)
{
if (!entry.IsFile) continue;
using (var zis = zipFile.GetInputStream(entry))
using (var sr = new StreamReader(zis, Encoding.UTF8))
{
var content = sr.ReadToEnd();
Assert.AreEqual(DummyDataString, content, "Decompressed content does not match input data");
}
}
Assert.That(zipFile.TestArchive(false), Is.True, "Encrypted archive should pass validation.");
}
}
[Test]
[Category("Encryption")]
[Category("Zip")]
public void ZipFileAesRead()
{
var password = "password";
using (var ms = new SingleByteReadingStream())
{
WriteEncryptedZipToStream(ms, password, 256);
ms.Seek(0, SeekOrigin.Begin);
var zipFile = new ZipFile(ms)
{
Password = password
};
foreach (ZipEntry entry in zipFile)
{
if (!entry.IsFile) continue;
using (var zis = zipFile.GetInputStream(entry))
using (var sr = new StreamReader(zis, Encoding.UTF8))
{
var content = sr.ReadToEnd();
Assert.AreEqual(DummyDataString, content, "Decompressed content does not match input data");
}
}
}
}
/// <summary>
/// Test using AES encryption on a file whose contents are Stored rather than deflated
/// </summary>
[Test]
[Category("Encryption")]
[Category("Zip")]
public void ZipFileStoreAes()
{
string password = "password";
using (var memoryStream = new MemoryStream())
{
// Try to create a zip stream
WriteEncryptedZipToStream(memoryStream, password, 256, CompressionMethod.Stored);
// reset
memoryStream.Seek(0, SeekOrigin.Begin);
// try to read it
var zipFile = new ZipFile(memoryStream, leaveOpen: true)
{
Password = password
};
foreach (ZipEntry entry in zipFile)
{
if (!entry.IsFile) continue;
// Should be stored rather than deflated
Assert.That(entry.CompressionMethod, Is.EqualTo(CompressionMethod.Stored), "Entry should be stored");
using (var zis = zipFile.GetInputStream(entry))
using (var sr = new StreamReader(zis, Encoding.UTF8))
{
var content = sr.ReadToEnd();
Assert.That(content, Is.EqualTo(DummyDataString), "Decompressed content does not match input data");
}
}
}
}
/// <summary>
/// Test using AES encryption on a file whose contents are Stored rather than deflated
/// </summary>
[Test]
[Category("Encryption")]
[Category("Zip")]
public void ZipFileStoreAesPartialRead([Values(1, 7, 17)] int readSize)
{
string password = "password";
using (var memoryStream = new MemoryStream())
{
// Try to create a zip stream
WriteEncryptedZipToStream(memoryStream, password, 256, CompressionMethod.Stored);
// reset
memoryStream.Seek(0, SeekOrigin.Begin);
// try to read it
var zipFile = new ZipFile(memoryStream, leaveOpen: true)
{
Password = password
};
foreach (ZipEntry entry in zipFile)
{
if (!entry.IsFile) continue;
// Should be stored rather than deflated
Assert.That(entry.CompressionMethod, Is.EqualTo(CompressionMethod.Stored), "Entry should be stored");
using (var ms = new MemoryStream())
{
using (var zis = zipFile.GetInputStream(entry))
{
byte[] buffer = new byte[readSize];
while (true)
{
int read = zis.Read(buffer, 0, readSize);
if (read == 0)
break;
ms.Write(buffer, 0, read);
}
}
ms.Seek(0, SeekOrigin.Begin);
using (var sr = new StreamReader(ms, Encoding.UTF8))
{
var content = sr.ReadToEnd();
Assert.That(content, Is.EqualTo(DummyDataString), "Decompressed content does not match input data");
}
}
}
}
}
/// <summary>
/// Test adding files to an encrypted zip
/// </summary>
[Test]
[Category("Encryption")]
[Category("Zip")]
public void ZipFileAesAdd()
{
string password = "password";
string testData = "AdditionalData";
int keySize = 256;
using (var memoryStream = new MemoryStream())
{
// Try to create a zip stream
WriteEncryptedZipToStream(memoryStream, password, keySize, CompressionMethod.Deflated);
// reset
memoryStream.Seek(0, SeekOrigin.Begin);
// Update the archive with ZipFile
{
using (var zipFile = new ZipFile(memoryStream, leaveOpen: true) { Password = password })
{
zipFile.BeginUpdate();
zipFile.Add(new StringMemoryDataSource(testData), "AdditionalEntry", CompressionMethod.Deflated);
zipFile.CommitUpdate();
}
}
// Test the updated archive
{
memoryStream.Seek(0, SeekOrigin.Begin);
using (var zipFile = new ZipFile(memoryStream, leaveOpen: true) { Password = password })
{
Assert.That(zipFile.Count, Is.EqualTo(2), "Incorrect entry count in updated archive");
// Disabled because of bug #317
// Assert.That(zipFile.TestArchive(true), Is.True);
// Check the original entry
{
var originalEntry = zipFile.GetEntry("test");
Assert.That(originalEntry.IsCrypted, Is.True);
Assert.That(originalEntry.AESKeySize, Is.EqualTo(keySize));
using (var zis = zipFile.GetInputStream(originalEntry))
using (var sr = new StreamReader(zis, Encoding.UTF8))
{
var content = sr.ReadToEnd();
Assert.That(content, Is.EqualTo(DummyDataString), "Decompressed content does not match input data");
}
}
// Check the additional entry
// This should be encrypted, though currently only with ZipCrypto
{
var additionalEntry = zipFile.GetEntry("AdditionalEntry");
Assert.That(additionalEntry.IsCrypted, Is.True);
using (var zis = zipFile.GetInputStream(additionalEntry))
using (var sr = new StreamReader(zis, Encoding.UTF8))
{
var content = sr.ReadToEnd();
Assert.That(content, Is.EqualTo(testData), "Decompressed content does not match input data");
}
}
}
}
// As an extra test, verify the file with 7-zip
VerifyZipWith7Zip(memoryStream, password);
}
}
/// <summary>
/// Test deleting files from an encrypted zip
/// </summary>
[Test]
[Category("Encryption")]
[Category("Zip")]
public void ZipFileAesDelete()
{
string password = "password";
int keySize = 256;
using (var memoryStream = new MemoryStream())
{
// Try to create a zip stream
WriteEncryptedZipToStream(memoryStream, 3, password, keySize, CompressionMethod.Deflated);
// reset
memoryStream.Seek(0, SeekOrigin.Begin);
// delete one of the entries from the file
{
using (var zipFile = new ZipFile(memoryStream, leaveOpen: true) { Password = password })
{
// Must have 3 entries to start with
Assert.That(zipFile.Count, Is.EqualTo(3), "Must have 3 entries to start with");
var entryToDelete = zipFile.GetEntry("test-1");
Assert.That(entryToDelete, Is.Not.Null, "the entry that we want to delete must exist");
zipFile.BeginUpdate();
zipFile.Delete(entryToDelete);
zipFile.CommitUpdate();
}
}
// Test the updated archive
{
memoryStream.Seek(0, SeekOrigin.Begin);
using (var zipFile = new ZipFile(memoryStream, leaveOpen: true) { Password = password })
{
// We should now only have 2 files
Assert.That(zipFile.Count, Is.EqualTo(2), "Incorrect entry count in updated archive");
// Disabled because of bug #317
// Assert.That(zipFile.TestArchive(true), Is.True);
// Check the first entry
{
var originalEntry = zipFile.GetEntry("test-0");
Assert.That(originalEntry.IsCrypted, Is.True);
Assert.That(originalEntry.AESKeySize, Is.EqualTo(keySize));
using (var zis = zipFile.GetInputStream(originalEntry))
using (var sr = new StreamReader(zis, Encoding.UTF8))
{
var content = sr.ReadToEnd();
Assert.That(content, Is.EqualTo(DummyDataString), "Decompressed content does not match input data");
}
}
// Check the second entry
{
var originalEntry = zipFile.GetEntry("test-2");
Assert.That(originalEntry.IsCrypted, Is.True);
Assert.That(originalEntry.AESKeySize, Is.EqualTo(keySize));
using (var zis = zipFile.GetInputStream(originalEntry))
using (var sr = new StreamReader(zis, Encoding.UTF8))
{
var content = sr.ReadToEnd();
Assert.That(content, Is.EqualTo(DummyDataString), "Decompressed content does not match input data");
}
}
}
}
// As an extra test, verify the file with 7-zip
VerifyZipWith7Zip(memoryStream, password);
}
}
// This is a zip file with one AES encrypted entry, whose password in an empty string.
const string TestFileWithEmptyPassword = @"UEsDBDMACQBjACaj0FAyKbop//////////8EAB8AdGVzdAEAEAA4AAAA
AAAAAFIAAAAAAAAAAZkHAAIAQUUDCABADvo3YqmCtIE+lhw26kjbqkGsLEOk6bVA+FnSpVD4yGP4Mr66Hs14aTtsPUaANX2
Z6qZczEmwoaNQpNBnKl7p9YOG8GSHDfTCUU/AZvT4yGFhUEsHCDIpuilSAAAAAAAAADgAAAAAAAAAUEsBAjMAMwAJAGMAJq
PQUDIpuin//////////wQAHwAAAAAAAAAAAAAAAAAAAHRlc3QBABAAOAAAAAAAAABSAAAAAAAAAAGZBwACAEFFAwgAUEsFBgAAAAABAAEAUQAAAKsAAAAAAA==";
/// <summary>
/// Test reading an AES encrypted entry whose password is an empty string.
/// </summary>
/// <remarks>
/// Test added for https://github.com/icsharpcode/SharpZipLib/issues/471.
/// </remarks>
[Test]
[Category("Zip")]
public void ZipFileAESReadWithEmptyPassword()
{
var fileBytes = Convert.FromBase64String(TestFileWithEmptyPassword);
using (var ms = new MemoryStream(fileBytes))
using (var zipFile = new ZipFile(ms, leaveOpen: true))
{
zipFile.Password = string.Empty;
var entry = zipFile.FindEntry("test", true);
using (var inputStream = zipFile.GetInputStream(entry))
using (var sr = new StreamReader(inputStream, Encoding.UTF8))
{
var content = sr.ReadToEnd();
Assert.That(content, Is.EqualTo("Lorem ipsum dolor sit amet, consectetur adipiscing elit."), "Decompressed content does not match expected data");
}
}
}
/// <summary>
/// ZipInputStream can't decrypt AES encrypted entries, but it should report that to the caller
/// rather than just failing.
/// </summary>
[Test]
[Category("Zip")]
public void ZipinputStreamShouldGracefullyFailWithAESStreams()
{
string password = "password";
using (var memoryStream = new MemoryStream())
{
// Try to create a zip stream
WriteEncryptedZipToStream(memoryStream, password, 256);
// reset
memoryStream.Seek(0, SeekOrigin.Begin);
// Try to read
using (var inputStream = new ZipInputStream(memoryStream))
{
inputStream.Password = password;
var entry = inputStream.GetNextEntry();
Assert.That(entry.AESKeySize, Is.EqualTo(256), "Test entry should be AES256 encrypted.");
// CanDecompressEntry should be false.
Assert.That(inputStream.CanDecompressEntry, Is.False, "CanDecompressEntry should be false for AES encrypted entries");
// Should throw on read.
Assert.Throws<ZipException>(() => inputStream.ReadByte());
}
}
}
private static readonly string[] possible7zPaths = new[] {
// Check in PATH
"7z", "7za",
// Check in default install location
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "7-Zip", "7z.exe"),
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "7-Zip", "7z.exe"),
};
public static bool TryGet7zBinPath(out string path7z)
{
var runTimeLimit = TimeSpan.FromSeconds(3);
foreach (var testPath in possible7zPaths)
{
try
{
var p = Process.Start(new ProcessStartInfo(testPath, "i")
{
RedirectStandardOutput = true,
UseShellExecute = false
});
while (!p.StandardOutput.EndOfStream && (DateTime.Now - p.StartTime) < runTimeLimit)
{
p.StandardOutput.DiscardBufferedData();
}
if (!p.HasExited)
{
p.Close();
Assert.Warn($"Timed out checking for 7z binary in \"{testPath}\"!");
continue;
}
if (p.ExitCode == 0)
{
path7z = testPath;
return true;
}
}
catch (Exception)
{
continue;
}
}
path7z = null;
return false;
}
public void WriteEncryptedZipToStream(Stream stream, string password, int keySize, CompressionMethod compressionMethod = CompressionMethod.Deflated)
{
using (var zs = new ZipOutputStream(stream))
{
zs.IsStreamOwner = false;
zs.SetLevel(9); // 0-9, 9 being the highest level of compression
zs.Password = password; // optional. Null is the same as not setting. Required if using AES.
AddEncrypedEntryToStream(zs, $"test", keySize, compressionMethod);
}
}
public void WriteEncryptedZipToStream(Stream stream, int entryCount, string password, int keySize, CompressionMethod compressionMethod)
{
using (var zs = new ZipOutputStream(stream))
{
zs.IsStreamOwner = false;
zs.SetLevel(9); // 0-9, 9 being the highest level of compression
zs.Password = password; // optional. Null is the same as not setting. Required if using AES.
for (int i = 0; i < entryCount; i++)
{
AddEncrypedEntryToStream(zs, $"test-{i}", keySize, compressionMethod);
}
}
}
private void AddEncrypedEntryToStream(ZipOutputStream zipOutputStream, string entryName, int keySize, CompressionMethod compressionMethod)
{
ZipEntry zipEntry = new ZipEntry(entryName)
{
AESKeySize = keySize,
DateTime = DateTime.Now,
CompressionMethod = compressionMethod
};
zipOutputStream.PutNextEntry(zipEntry);
byte[] dummyData = Encoding.UTF8.GetBytes(DummyDataString);
using (var dummyStream = new MemoryStream(dummyData))
{
dummyStream.CopyTo(zipOutputStream);
}
zipOutputStream.CloseEntry();
}
public void CreateZipWithEncryptedEntries(string password, int keySize, CompressionMethod compressionMethod = CompressionMethod.Deflated)
{
using (var ms = new MemoryStream())
{
WriteEncryptedZipToStream(ms, password, keySize, compressionMethod);
VerifyZipWith7Zip(ms, password);
}
}
/// <summary>
/// Helper function to verify the provided zip stream with 7Zip.
/// </summary>
/// <param name="zipStream">A stream containing the zip archive to test.</param>
/// <param name="password">The password for the archive.</param>
private void VerifyZipWith7Zip(Stream zipStream, string password)
{
if (TryGet7zBinPath(out string path7z))
{
Console.WriteLine($"Using 7z path: \"{path7z}\"");
var fileName = Path.GetTempFileName();
try
{
using (var fs = File.OpenWrite(fileName))
{
zipStream.Seek(0, SeekOrigin.Begin);
zipStream.CopyTo(fs);
}
var p = Process.Start(path7z, $"t -p{password} \"{fileName}\"");
if (!p.WaitForExit(2000))
{
Assert.Warn("Timed out verifying zip file!");
}
Assert.AreEqual(0, p.ExitCode, "Archive verification failed");
}
finally
{
File.Delete(fileName);
}
}
else
{
Assert.Warn("Skipping file verification since 7za is not in path");
}
}
private const string DummyDataString = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Fusce bibendum diam ac nunc rutrum ornare. Maecenas blandit elit ligula, eget suscipit lectus rutrum eu.
Maecenas aliquam, purus mattis pulvinar pharetra, nunc orci maximus justo, sed facilisis massa dui sed lorem.
Vestibulum id iaculis leo. Duis porta ante lorem. Duis condimentum enim nec lorem tristique interdum. Fusce in faucibus libero.";
}
}
| 29.21246 | 151 | 0.672226 | [
"MIT"
] | checkoss/SharpZipLib | test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs | 18,289 | C# |
namespace Humidifier.DMS
{
using System.Collections.Generic;
public class Certificate : Humidifier.Resource
{
public override string AWSTypeName
{
get
{
return @"AWS::DMS::Certificate";
}
}
/// <summary>
/// CertificateIdentifier
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-certificate.html#cfn-dms-certificate-certificateidentifier
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic CertificateIdentifier
{
get;
set;
}
/// <summary>
/// CertificatePem
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-certificate.html#cfn-dms-certificate-certificatepem
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic CertificatePem
{
get;
set;
}
/// <summary>
/// CertificateWallet
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-certificate.html#cfn-dms-certificate-certificatewallet
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic CertificateWallet
{
get;
set;
}
}
} | 28.296296 | 149 | 0.556283 | [
"BSD-2-Clause"
] | jakejscott/Humidifier | src/Humidifier/DMS/Certificate.cs | 1,528 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.OrgPolicy.V2.Snippets
{
using Google.Cloud.OrgPolicy.V2;
using System.Threading.Tasks;
public sealed partial class GeneratedOrgPolicyClientStandaloneSnippets
{
/// <summary>Snippet for GetPolicyAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task GetPolicyAsync()
{
// Create client
OrgPolicyClient orgPolicyClient = await OrgPolicyClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/policies/[POLICY]";
// Make the request
Policy response = await orgPolicyClient.GetPolicyAsync(name);
}
}
}
| 37.15 | 89 | 0.685061 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/cloud/orgpolicy/v2/google-cloud-orgpolicy-v2-csharp/Google.Cloud.OrgPolicy.V2.StandaloneSnippets/OrgPolicyClient.GetPolicyAsyncSnippet.g.cs | 1,486 | C# |
namespace DigitalFamilyCookbook.Data.Domain.Models;
public class Step : BaseDomainModel
{
public string Id { get; set; } = string.Empty;
public int StepId { get; set; }
public string Direction { get; set; } = string.Empty;
public int SortOrder { get; set; }
public int RecipeId { get; set; }
public Recipe Recipe { get; set; } = Recipe.None();
public static Step None() => new Step();
public static Step FromDto(StepDto dto)
{
return new Step
{
Id = dto.Id,
StepId = dto.StepId,
Direction = dto.Direction,
SortOrder = dto.SortOrder,
RecipeId = dto.RecipeId,
Recipe = Recipe.FromDto(dto.Recipe),
DateCreated = dto.DateCreated,
DateUpdated = dto.DateUpdated,
};
}
}
| 24.470588 | 57 | 0.578125 | [
"MIT"
] | kpwags/digital-family-cookbook | backend/src/DigitalFamilyCookbook.Data/Domain/Models/Step.cs | 832 | C# |
using NUnit.Framework;
namespace Atata.Tests
{
public class ShouldTests : UITestFixture
{
private const string Country1Name = "England";
private const string Country2Name = "France";
private const string Country3Name = "Germany";
private const string MissingCountryName = "Missing";
[Test]
public void Should_BeEquivalent()
{
var should = Go.To<TablePage>().
CountryTable.Rows.SelectData(x => x.Country).Should.AtOnce;
should.BeEquivalent(Country1Name, Country2Name, Country3Name);
should.BeEquivalent(Country2Name, Country1Name, Country3Name);
Assert.Throws<AssertionException>(() =>
should.BeEquivalent(Country1Name, Country2Name));
should.Not.BeEquivalent(Country1Name, Country2Name, Country3Name, MissingCountryName);
Assert.Throws<AssertionException>(() =>
should.Not.BeEquivalent(Country3Name, Country1Name, Country2Name));
}
[Test]
public void Should_EqualSequence()
{
var should = Go.To<TablePage>().
CountryTable.Rows.SelectData(x => x.Country).Should.AtOnce;
should.EqualSequence(Country1Name, Country2Name, Country3Name);
Assert.Throws<AssertionException>(() =>
should.EqualSequence(Country1Name, Country3Name, Country2Name));
Assert.Throws<AssertionException>(() =>
should.EqualSequence(Country1Name));
should.Not.EqualSequence(Country1Name, Country2Name, Country3Name, MissingCountryName);
should.Not.EqualSequence(Country3Name, Country1Name, Country2Name);
should.Not.EqualSequence(Country1Name);
Assert.Throws<AssertionException>(() =>
should.Not.EqualSequence(Country1Name, Country2Name, Country3Name));
}
[Test]
public void Should_Contain()
{
var should = Go.To<TablePage>().
CountryTable.Rows.SelectData(x => x.Country).Should.AtOnce;
should.Contain(Country1Name, Country2Name, Country3Name);
should.Contain(Country2Name, Country1Name);
Assert.Throws<AssertionException>(() =>
should.Contain(Country1Name, MissingCountryName));
should.Not.Contain(MissingCountryName);
Assert.Throws<AssertionException>(() =>
should.Not.Contain(Country1Name, MissingCountryName));
Assert.Throws<AssertionException>(() =>
should.Not.Contain(Country3Name, Country1Name, Country2Name));
}
[Test]
public void Should_ContainHavingContent()
{
var should = Go.To<TablePage>().
CountryTable.Rows.SelectData(x => x.Country).Should.AtOnce;
should.ContainHavingContent(TermMatch.Equals, Country1Name, Country2Name, Country3Name);
should.ContainHavingContent(TermMatch.StartsWith, Country2Name, Country1Name);
should.ContainHavingContent(TermMatch.Contains, "a", "e");
Assert.Throws<AssertionException>(() =>
should.ContainHavingContent(TermMatch.Equals, Country1Name, MissingCountryName));
Assert.Throws<AssertionException>(() =>
should.ContainHavingContent(TermMatch.Contains, "a", "v"));
should.Not.ContainHavingContent(TermMatch.Contains, MissingCountryName);
should.Not.ContainHavingContent(TermMatch.Contains, "v", "w");
Assert.Throws<AssertionException>(() =>
should.Not.ContainHavingContent(TermMatch.EndsWith, Country1Name, MissingCountryName));
Assert.Throws<AssertionException>(() =>
should.Not.ContainHavingContent(TermMatch.StartsWith, Country3Name, Country1Name, Country2Name));
Assert.Throws<AssertionException>(() =>
should.Not.ContainHavingContent(TermMatch.Contains, "a", "v"));
}
[Test]
public void Should_Contain_TermMatch()
{
var should = Go.To<TablePage>().
CountryTable.Rows.SelectData(x => x.Country).Should.AtOnce;
should.Contain(TermMatch.Equals, Country1Name, Country2Name, Country3Name);
should.Contain(TermMatch.StartsWith, Country2Name, Country1Name);
should.Contain(TermMatch.Contains, "a", "e");
Assert.Throws<AssertionException>(() =>
should.Contain(TermMatch.Equals, Country1Name, MissingCountryName));
Assert.Throws<AssertionException>(() =>
should.Contain(TermMatch.Contains, "a", "v"));
should.Not.Contain(TermMatch.Contains, MissingCountryName);
should.Not.Contain(TermMatch.Contains, "v", "w");
Assert.Throws<AssertionException>(() =>
should.Not.Contain(TermMatch.EndsWith, Country1Name, MissingCountryName));
Assert.Throws<AssertionException>(() =>
should.Not.Contain(TermMatch.StartsWith, Country3Name, Country1Name, Country2Name));
Assert.Throws<AssertionException>(() =>
should.Not.Contain(TermMatch.Contains, "a", "v"));
}
[Test]
public void Should_Contain_Predicate()
{
var should = Go.To<TablePage>().
CountryTable.Rows.SelectData(x => x.Country).Should.AtOnce;
should.Contain(x => x == Country1Name);
should.Contain(x => x.Value == MissingCountryName || x.Value == Country3Name);
Assert.Throws<AssertionException>(() =>
should.Contain(x => x == MissingCountryName));
should.Not.Contain(x => x == MissingCountryName);
Assert.Throws<AssertionException>(() =>
should.Not.Contain(x => x == Country1Name));
}
[Test]
public void Should_Equal_Delayed()
{
Go.To<WaitingPage>().
WaitAndUpdateValue.Click().
ValueBlock.Should.Equal("New value");
}
[Test]
public void Should_Equal_Delayed_WithParentReset()
{
Go.To<WaitingPage>().
WaitAndUpdateValue.Click().
ValueContainer.ValueBlock.Should.Equal("New value");
}
[Test]
public void Should_Match()
{
var should = Go.To<ContentPage>().
NumberAsText.Should.AtOnce;
should.Match(@"^\d{3}.\d{2}$");
Assert.Throws<AssertionException>(() =>
should.Not.Match(@"^\d{3}.\d{2}$"));
Assert.Throws<AssertionException>(() =>
should.Match(@"^\d{4}.\d{2}$"));
}
[Test]
public void Should_HaveClass()
{
var should = Go.To<TablePage>().
CountryTable.Should.AtOnce;
should.HaveClass("table");
Assert.Throws<AssertionException>(() =>
should.HaveClass("missing"));
should.Not.HaveClass("missing");
Assert.Throws<AssertionException>(() =>
should.Not.HaveClass("table"));
}
}
}
| 38.753927 | 114 | 0.582005 | [
"Apache-2.0"
] | Artemyj/atata | src/Atata.Tests/ShouldTests.cs | 7,404 | C# |
using System.Collections.Generic;
using PizzaBox.Domain.Models;
namespace PizzaBox.Domain.Abstracts
{
public abstract class APizza
{
protected List<AIngredient> _components;
public List<AIngredient> Components
{
get
{
return _components;
}
}
protected decimal _cost;
public decimal Cost
{
get
{
return _cost;
}
}
protected decimal CalculateCost()
{
foreach(var component in _components)
{
_cost += component.Cost;
}
return Cost;
}
public abstract void Make(Store st, Size s, List<Topping> t, out List<AIngredient> componentList, out decimal totalCost);
protected APizza()
{
_components = new List<AIngredient>();
}
}
} | 22.547619 | 129 | 0.504752 | [
"MIT"
] | celestinojones/project0 | PizzaBox.Domain/Abstracts/APizza.cs | 947 | C# |
using System;
using Windows.Foundation;
using Windows.UI.Xaml;
namespace Xamarin.Forms.Platform.UWP
{
public class ShellHeaderRenderer : Windows.UI.Xaml.Controls.ContentControl
{
Shell _shell;
public ShellHeaderRenderer(Shell element)
{
Shell.VerifyShellUWPFlagEnabled(nameof(ShellHeaderRenderer));
SetElement(element);
SizeChanged += OnShellHeaderRendererSizeChanged;
HorizontalContentAlignment = HorizontalAlignment.Stretch;
VerticalContentAlignment = VerticalAlignment.Stretch;
}
void OnShellHeaderRendererSizeChanged(object sender, SizeChangedEventArgs e)
{
if (Element is Layout layout)
layout.ForceLayout();
}
internal VisualElement Element { get; set; }
public void SetElement(Shell shell)
{
if(_shell != null)
_shell.PropertyChanged += OnShellPropertyChanged;
if(shell != null)
{
_shell = shell;
_shell.PropertyChanged += OnShellPropertyChanged;
UpdateHeader();
}
}
void OnShellPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if(e.IsOneOf(Shell.FlyoutHeaderProperty, Shell.FlyoutHeaderTemplateProperty))
UpdateHeader();
}
void UpdateHeader()
{
if (Element != null)
{
if(Content is WrapperControl wrapperControl)
{
wrapperControl.CleanUp();
Content = null;
}
Element = null;
}
object header = null;
if (_shell is IShellController controller)
header = controller.FlyoutHeader;
if (header is View visualElement)
{
Element = visualElement;
Content = new WrapperControl(visualElement);
}
else
{
Content = null;
}
}
}
}
| 21.025641 | 94 | 0.712805 | [
"MIT"
] | nventive/Uno.Xamarin.Forms | Xamarin.Forms.Platform.UAP/Shell/ShellHeaderRenderer.cs | 1,642 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SitecoreDev.Feature.Media.ViewModels
{
public class HeroSliderImageViewModel
{
public HtmlString Image { get; set; }
public bool IsActive { get; set; }
}
} | 21 | 46 | 0.721612 | [
"MIT"
] | claudiu04/SitecoreDev | Feature/Media/SitecoreDev.Feature.Media/ViewModels/HeroSliderImageViewModel.cs | 275 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.OutboundBot.Model.V20191226;
namespace Aliyun.Acs.OutboundBot.Transform.V20191226
{
public class UntagResourcesResponseUnmarshaller
{
public static UntagResourcesResponse Unmarshall(UnmarshallerContext _ctx)
{
UntagResourcesResponse untagResourcesResponse = new UntagResourcesResponse();
untagResourcesResponse.HttpResponse = _ctx.HttpResponse;
untagResourcesResponse.RequestId = _ctx.StringValue("UntagResources.RequestId");
untagResourcesResponse.Success = _ctx.BooleanValue("UntagResources.Success");
untagResourcesResponse.Code = _ctx.StringValue("UntagResources.Code");
untagResourcesResponse.Message = _ctx.StringValue("UntagResources.Message");
untagResourcesResponse.HttpStatusCode = _ctx.IntegerValue("UntagResources.HttpStatusCode");
return untagResourcesResponse;
}
}
}
| 40.204545 | 94 | 0.767665 | [
"Apache-2.0"
] | aliyun/aliyun-openapi-net-sdk | aliyun-net-sdk-outboundbot/OutboundBot/Transform/V20191226/UntagResourcesResponseUnmarshaller.cs | 1,769 | C# |
using System;
namespace Aeon.Emulator
{
[Flags]
public enum FPUStatus
{
Clear = 0,
InvalidOperation = (1 << 0),
Denormalized = (1 << 1),
ZeroDivide = (1 << 2),
Overflow = (1 << 3),
Underflow = (1 << 4),
Precision = (1 << 5),
StackFault = (1 << 6),
InterruptRequest = (1 << 7),
C0 = (1 << 8),
C1 = (1 << 9),
C2 = (1 << 10),
C3 = (1 << 14),
Busy = (1 << 15)
}
}
| 20.416667 | 36 | 0.393878 | [
"Apache-2.0"
] | gregdivis/Aeon | src/Aeon.Emulator/Processor/FPUStatus.cs | 492 | C# |
namespace sg_prj
{
partial class AboutBox
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AboutBox));
this.tableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.logoPictureBox = new System.Windows.Forms.PictureBox();
this.labelProductName = new System.Windows.Forms.Label();
this.labelVersion = new System.Windows.Forms.Label();
this.labelCopyright = new System.Windows.Forms.Label();
this.labelCompanyName = new System.Windows.Forms.Label();
this.textBoxDescription = new System.Windows.Forms.TextBox();
this.okButton = new System.Windows.Forms.Button();
this.tableLayoutPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.logoPictureBox)).BeginInit();
this.SuspendLayout();
//
// tableLayoutPanel
//
this.tableLayoutPanel.ColumnCount = 2;
this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33F));
this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 67F));
this.tableLayoutPanel.Controls.Add(this.logoPictureBox, 0, 0);
this.tableLayoutPanel.Controls.Add(this.labelProductName, 1, 0);
this.tableLayoutPanel.Controls.Add(this.labelVersion, 1, 1);
this.tableLayoutPanel.Controls.Add(this.labelCopyright, 1, 2);
this.tableLayoutPanel.Controls.Add(this.labelCompanyName, 1, 3);
this.tableLayoutPanel.Controls.Add(this.textBoxDescription, 1, 4);
this.tableLayoutPanel.Controls.Add(this.okButton, 1, 5);
this.tableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel.Location = new System.Drawing.Point(9, 9);
this.tableLayoutPanel.Name = "tableLayoutPanel";
this.tableLayoutPanel.RowCount = 6;
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel.Size = new System.Drawing.Size(417, 265);
this.tableLayoutPanel.TabIndex = 0;
//
// logoPictureBox
//
this.logoPictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.logoPictureBox.Image = ((System.Drawing.Image)(resources.GetObject("logoPictureBox.Image")));
this.logoPictureBox.Location = new System.Drawing.Point(3, 3);
this.logoPictureBox.Name = "logoPictureBox";
this.tableLayoutPanel.SetRowSpan(this.logoPictureBox, 6);
this.logoPictureBox.Size = new System.Drawing.Size(131, 259);
this.logoPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.logoPictureBox.TabIndex = 12;
this.logoPictureBox.TabStop = false;
//
// labelProductName
//
this.labelProductName.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelProductName.Location = new System.Drawing.Point(143, 0);
this.labelProductName.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0);
this.labelProductName.MaximumSize = new System.Drawing.Size(0, 17);
this.labelProductName.Name = "labelProductName";
this.labelProductName.Size = new System.Drawing.Size(271, 17);
this.labelProductName.TabIndex = 19;
this.labelProductName.Text = "Shotgun<>Project Plugin";
this.labelProductName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// labelVersion
//
this.labelVersion.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelVersion.Location = new System.Drawing.Point(143, 26);
this.labelVersion.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0);
this.labelVersion.MaximumSize = new System.Drawing.Size(0, 17);
this.labelVersion.Name = "labelVersion";
this.labelVersion.Size = new System.Drawing.Size(271, 17);
this.labelVersion.TabIndex = 0;
this.labelVersion.Text = "Version";
this.labelVersion.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// labelCopyright
//
this.labelCopyright.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelCopyright.Location = new System.Drawing.Point(143, 52);
this.labelCopyright.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0);
this.labelCopyright.MaximumSize = new System.Drawing.Size(0, 17);
this.labelCopyright.Name = "labelCopyright";
this.labelCopyright.Size = new System.Drawing.Size(271, 17);
this.labelCopyright.TabIndex = 21;
this.labelCopyright.Text = "Copyright 2012";
this.labelCopyright.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// labelCompanyName
//
this.labelCompanyName.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelCompanyName.Location = new System.Drawing.Point(143, 78);
this.labelCompanyName.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0);
this.labelCompanyName.MaximumSize = new System.Drawing.Size(0, 17);
this.labelCompanyName.Name = "labelCompanyName";
this.labelCompanyName.Size = new System.Drawing.Size(271, 17);
this.labelCompanyName.TabIndex = 22;
this.labelCompanyName.Text = "YourCompany";
this.labelCompanyName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// textBoxDescription
//
this.textBoxDescription.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBoxDescription.Location = new System.Drawing.Point(143, 107);
this.textBoxDescription.Margin = new System.Windows.Forms.Padding(6, 3, 3, 3);
this.textBoxDescription.Multiline = true;
this.textBoxDescription.Name = "textBoxDescription";
this.textBoxDescription.ReadOnly = true;
this.textBoxDescription.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.textBoxDescription.Size = new System.Drawing.Size(271, 126);
this.textBoxDescription.TabIndex = 23;
this.textBoxDescription.TabStop = false;
this.textBoxDescription.Text = "Description";
//
// okButton
//
this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.okButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.okButton.Location = new System.Drawing.Point(339, 239);
this.okButton.Name = "okButton";
this.okButton.Size = new System.Drawing.Size(75, 23);
this.okButton.TabIndex = 24;
this.okButton.Text = "&OK";
//
// AboutBox
//
this.AcceptButton = this.okButton;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(435, 283);
this.Controls.Add(this.tableLayoutPanel);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "AboutBox";
this.Padding = new System.Windows.Forms.Padding(9);
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "About Shotgun Project Plugin";
this.tableLayoutPanel.ResumeLayout(false);
this.tableLayoutPanel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.logoPictureBox)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel;
private System.Windows.Forms.PictureBox logoPictureBox;
private System.Windows.Forms.Label labelProductName;
private System.Windows.Forms.Label labelVersion;
private System.Windows.Forms.Label labelCopyright;
private System.Windows.Forms.Label labelCompanyName;
private System.Windows.Forms.TextBox textBoxDescription;
private System.Windows.Forms.Button okButton;
}
}
| 56.826087 | 160 | 0.633321 | [
"MIT"
] | LaikaStudios/sgProjectPlugin | Shotgun Project Plugin/Interface/AboutBox.Designer.cs | 10,458 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
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("Microsoft.AppCenter.Push.UWP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("Microsoft.AppCenter.Push.UWP")]
[assembly: AssemblyCopyright("Microsoft Corp. All rights reserved.")]
[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("3.0.1.0")]
[assembly: ComVisible(false)]
[assembly: InternalsVisibleTo("Microsoft.AppCenter.Test.UWP")] | 38.545455 | 84 | 0.753931 | [
"MIT"
] | GerHobbelt/appcenter-sdk-dotnet | SDK/AppCenterPush/Microsoft.AppCenter.Push.UWP/Properties/AssemblyInfo.cs | 1,272 | C# |
//-----------------------------------------------------------------------
// <copyright file="CameraImageBytes.cs" company="Google LLC">
//
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCore
{
using System;
using System.Diagnostics.CodeAnalysis;
using GoogleARCoreInternal;
using UnityEngine;
/// <summary>
/// An ARCore camera image with its data accessible from the CPU in YUV-420-888 format.
/// </summary>
public struct CameraImageBytes : IDisposable
{
private IntPtr _imageHandle;
internal CameraImageBytes(IntPtr imageHandle) : this()
{
_imageHandle = imageHandle;
if (_imageHandle != IntPtr.Zero)
{
IntPtr y, u, v;
y = u = v = IntPtr.Zero;
int bufferLengthIgnore = 0;
const int Y_PLANE = 0;
const int U_PLANE = 1;
const int V_PLANE = 2;
IsAvailable = true;
Width = LifecycleManager.Instance.NativeSession.ImageApi.GetWidth(imageHandle);
Height = LifecycleManager.Instance.NativeSession.ImageApi.GetHeight(imageHandle);
LifecycleManager.Instance.NativeSession.ImageApi.GetPlaneData(imageHandle, Y_PLANE,
ref y, ref bufferLengthIgnore);
LifecycleManager.Instance.NativeSession.ImageApi.GetPlaneData(imageHandle, U_PLANE,
ref u, ref bufferLengthIgnore);
LifecycleManager.Instance.NativeSession.ImageApi.GetPlaneData(imageHandle, V_PLANE,
ref v, ref bufferLengthIgnore);
YRowStride = LifecycleManager.Instance.NativeSession.ImageApi.GetPlaneRowStride(
imageHandle, Y_PLANE);
UVPixelStride = LifecycleManager.Instance.NativeSession.ImageApi
.GetPlanePixelStride(imageHandle, U_PLANE);
UVRowStride = LifecycleManager.Instance.NativeSession.ImageApi.GetPlaneRowStride(
imageHandle, U_PLANE);
Y = y;
U = u;
V = v;
}
else
{
IsAvailable = false;
Width = Height = 0;
Y = U = V = IntPtr.Zero;
YRowStride = UVPixelStride = UVRowStride = 0;
}
}
/// <summary>
/// Gets a value indicating whether the image bytes are available. The struct should not be
/// accessed if this value is <c>false</c>.
/// </summary>
public bool IsAvailable { get; private set; }
/// <summary>
/// Gets the width of the image.
/// </summary>
public int Width { get; private set; }
/// <summary>
/// Gets the height of the image.
/// </summary>
public int Height { get; private set; }
/// <summary>
/// Gets a pointer to the Y buffer with a pixel stride of 1 and a row stride of
/// <c>YRowStride</c>.
/// </summary>
public IntPtr Y { get; private set; }
/// <summary>
/// Gets a pointer to the U buffer with a pixel stride of <c>UVPixelStride</c> and a row
/// stride of <c>UVRowStride</c>.
/// </summary>
public IntPtr U { get; private set; }
/// <summary>
/// Gets a pointer to the V buffer with a pixel stride of <c>UVPixelStride</c> and a row
/// stride of <c>UVRowStride</c>.
/// </summary>
public IntPtr V { get; private set; }
/// <summary>
/// Gets the row stride of the Y plane.
/// </summary>
public int YRowStride { get; private set; }
/// <summary>
/// Gets the pixel stride of the U and V planes.
/// </summary>
public int UVPixelStride { get; private set; }
/// <summary>
/// Gets the row stride of the U and V planes.
/// </summary>
public int UVRowStride { get; private set; }
/// <summary>
/// Releases the camera image and associated resources, and signifies the developer will no
/// longer access those resources.
/// </summary>
public void Release()
{
if (_imageHandle != IntPtr.Zero)
{
LifecycleManager.Instance.NativeSession.ImageApi.Release(_imageHandle);
_imageHandle = IntPtr.Zero;
}
}
/// <summary>
/// Calls release as part of IDisposable pattern supporting 'using' statements.
/// </summary>
[SuppressMemoryAllocationError(IsWarning = true,
Reason = "Requires further investigation.")]
public void Dispose()
{
Release();
}
}
}
| 35.815789 | 99 | 0.557678 | [
"Apache-2.0"
] | ANKITVIRGO23/ARVRTest | Assets/GoogleARCore/SDK/Scripts/CameraImageBytes.cs | 5,444 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Security_Indentity_Sample.Models.AccountViewModels
{
public class LoginWith2faViewModel
{
[Required]
[StringLength(7, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Text)]
[Display(Name = "Authenticator code")]
public string TwoFactorCode { get; set; }
[Display(Name = "Remember this machine")]
public bool RememberMachine { get; set; }
public bool RememberMe { get; set; }
}
}
| 29.608696 | 123 | 0.679883 | [
"Apache-2.0"
] | vincoss/NetCoreSamples | AspNetCore-2.0/src/Security_Indentity_Sample/Models/AccountViewModels/LoginWith2faViewModel.cs | 683 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using LinqToDB;
using LinqToDB.Data;
using LinqToDB.Mapping;
using LinqToDB.SqlQuery;
using NUnit.Framework;
namespace Tests.Linq
{
[TestFixture]
public class TestQueryCache : TestBase
{
[Table]
class SampleClass
{
public int Id { get; set; }
public string StrKey { get; set; }
public string Value { get; set; }
}
[Table]
class SampleClassWithIdentity
{
[Identity]
public int Id { get; set; }
public string Value { get; set; }
}
[Test]
public void BasicOperations([IncludeDataSources(ProviderName.SQLiteMS)] string context, [Values("Value1", "Value2")] string columnName)
{
var ms = CreateMappingSchema(columnName);
using (var db = GetDataContext(context, ms))
using (var table = db.CreateLocalTable<SampleClass>())
using (db.CreateLocalTable<SampleClassWithIdentity>())
{
db.Insert(new SampleClass() { Id = 1, StrKey = "K1", Value = "V1" });
db.Insert(new SampleClass() { Id = 2, StrKey = "K2", Value = "V2" });
db.InsertOrReplace(new SampleClass() { Id = 3, StrKey = "K3", Value = "V3" });
db.InsertWithIdentity(new SampleClassWithIdentity() { Value = "V4" });
db.Delete(new SampleClass() { Id = 1, StrKey = "K1" });
db.Update(new SampleClass() { Id = 2, StrKey = "K2", Value = "VU" });
var found = null != QueryVisitor.Find(table.GetSelectQuery(),
e => e is SqlField f && f.PhysicalName == columnName);
var foundKey = null != QueryVisitor.Find(table.GetSelectQuery(),
e => e is SqlField f && f.PhysicalName == columnName);
Assert.IsTrue(found);
Assert.IsTrue(foundKey);
var result = table.ToArray();
}
}
[Test]
public async Task BasicOperationsAsync([IncludeDataSources(ProviderName.SQLiteMS)] string context, [Values("Value1", "Value2")] string columnName)
{
var ms = CreateMappingSchema(columnName);
using (var db = GetDataContext(context, ms))
using (var table = db.CreateLocalTable<SampleClass>())
using (db.CreateLocalTable<SampleClassWithIdentity>())
{
await db.InsertAsync(new SampleClass() { Id = 1, StrKey = "K1", Value = "V1" });
await db.InsertAsync(new SampleClass() { Id = 2, StrKey = "K2", Value = "V2" });
await db.InsertOrReplaceAsync(new SampleClass() { Id = 3, StrKey = "K3", Value = "V3" });
await db.InsertWithIdentityAsync(new SampleClassWithIdentity() { Value = "V4" });
await db.DeleteAsync(new SampleClass() { Id = 1, StrKey = "K1" });
await db.UpdateAsync(new SampleClass() { Id = 2, StrKey = "K2", Value = "VU" });
var found = null != QueryVisitor.Find(table.GetSelectQuery(),
e => e is SqlField f && f.PhysicalName == columnName);
var foundKey = null != QueryVisitor.Find(table.GetSelectQuery(),
e => e is SqlField f && f.PhysicalName == columnName);
Assert.IsTrue(found);
Assert.IsTrue(foundKey);
var result = await table.ToArrayAsync();
}
}
[Test]
public void TestSchema([IncludeDataSources(ProviderName.SQLiteMS)] string context)
{
void TestMethod(string columnName, string schemaName = null)
{
var ms = CreateMappingSchema(columnName, schemaName);
using (var db = (DataConnection)GetDataContext(context, ms))
using (db.CreateLocalTable<SampleClass>())
{
db.Insert(new SampleClass() { Id = 1, StrKey = "K1", Value = "V1" });
if (!db.LastQuery.Contains(columnName))
throw new Exception("Invalid schema");
}
}
TestMethod("Value1");
TestMethod("Value2");
TestMethod("ValueF1", "FAIL");
Assert.Throws(Is.AssignableTo(typeof(Exception)), () => TestMethod("ValueF2", "FAIL"));
}
private static MappingSchema CreateMappingSchema(string columnName, string schemaName = null)
{
var ms = new MappingSchema(schemaName);
var builder = ms.GetFluentMappingBuilder();
builder.Entity<SampleClass>()
.Property(e => e.Id).IsPrimaryKey()
.Property(e => e.StrKey).IsPrimaryKey().HasColumnName("Key" + columnName).HasLength(50)
.Property(e => e.Value).HasColumnName(columnName).HasLength(50);
builder.Entity<SampleClassWithIdentity>()
.Property(e => e.Id).IsPrimaryKey()
.Property(e => e.Value).HasColumnName(columnName).HasLength(50);
return ms;
}
}
}
| 33.772727 | 149 | 0.63773 | [
"MIT"
] | ammogcoder/linq2db | Tests/Linq/Linq/TestQueryCache.cs | 4,329 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PalmeralGenNHibernate.CEN.Default_;
using PalmeralGenNHibernate.EN.Default_;
namespace LimpiezasPalmeralTest
{
[TestClass]
public class ProductoTest
{
private ProductoCEN productoTest;
[TestInitialize]
public void TestMethod1()
{
productoTest = new ProductoCEN();
}
[TestMethod]
public void Pro_Registrar()
{
string expected = productoTest.Crear("102", "Lejia", "limpiador automatico", 10, "tufoto.com");
productoTest.Eliminar("102");
Assert.AreEqual("102", expected);
}
[TestMethod]
public void Pro_RegistarError()
{
try
{
productoTest.Crear("10", "Lejia", "limpiador automatico", 10, "tufoto.com");
Assert.Fail("Excepcion no lanzada");
}
catch (PalmeralGenNHibernate.Exceptions.DataLayerException ex)
{
string expected = "Error in ProductoCAD.";
Assert.AreEqual(ex.Message, expected);
}
}
[TestMethod]
public void Pro_Consultar()
{
ProductoEN expected = productoTest.ObtenerProducto("10");
string actual = "limpiador automatico";
Assert.AreEqual(actual, expected.Descripcion);
}
[TestMethod]
public void Pro_ConsultarError()
{
try
{
productoTest.ObtenerProducto(null);
Assert.Fail("Excepcion no lanzada");
}
catch (PalmeralGenNHibernate.Exceptions.DataLayerException ex)
{
string expected = "Error in ProductoCAD.";
Assert.AreEqual(ex.Message, expected);
}
}
[TestCleanup]
public void Disconnect()
{
productoTest = null;
}
}
}
| 27.315068 | 107 | 0.54664 | [
"Apache-2.0"
] | pablovargan/winforms-ooh4ria | LimpiezasPalmeralTest/ProductoTest.cs | 1,996 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using PRI.Messaging.Patterns;
using PRI.Messaging.Patterns.Exceptions;
using PRI.Messaging.Patterns.Extensions.Bus;
using PRI.Messaging.Primitives;
using Tests.Mocks;
#pragma warning disable S1104 // Fields should not have public accessibility
#pragma warning disable S1481 // Unused local variables should be removed
namespace Tests
{
[TestFixture]
public class BusTests
{
[Test]
public void BusConsumesMessagesCorrectly()
{
Message1 receivedMessage;
Message1 message1;
using (var bus = new Bus())
{
receivedMessage = null;
bus.AddHandler(new ActionConsumer<Message1>(m=>receivedMessage = m));
message1 = new Message1 {CorrelationId = "1234"};
bus.Handle(message1);
}
Assert.AreSame(message1, receivedMessage);
Assert.IsNotNull(receivedMessage);
Assert.AreEqual(message1.CorrelationId, receivedMessage.CorrelationId);
}
#if PARANOID
[Test]
public void RemovingHandlerBeforeProcessingThrows()
{
var bus = new Bus();
var actionConsumer = new ActionConsumer<Message1>(m => { });
var token = bus.AddHandler(actionConsumer);
Assert.Throws<MessageHandlerRemovedBeforeProcessingMessageException<Message1>>(()=>bus.RemoveHandler(actionConsumer, token));
}
#endif // PARANOID
#if SUPPORT_ASYNC_CONSUMER
[Test]
public void MultipleAsyncHandlersOfSameMessageDoesntThrow()
{
using (var bus = new Bus())
{
bus.AddHandler(new AsyncActionConsumer<Message1>(m => Task.FromResult(0)));
bus.AddHandler(new AsyncActionConsumer<Message1>(m => Task.FromResult(1)));
}
}
#endif
public class TheEvent : IEvent
{
public TheEvent()
{
CorrelationId = Guid.NewGuid().ToString("D");
OccurredDateTime = DateTime.UtcNow;
}
public string CorrelationId { get; set; }
public DateTime OccurredDateTime { get; set; }
}
[Test]
public void EnsureInterfaceHandlerIsInvoked()
{
var bus = new Bus();
Message1 receivedMessage = null;
bus.AddHandler(new ActionConsumer<Message1>(m => receivedMessage = m));
string text = null;
bus.AddHandler(new ActionConsumer<IEvent>(_=> { text = "ding"; }));
var message1 = new Message1 { CorrelationId = "1234" };
bus.Handle(message1);
bus.Handle(new TheEvent());
Assert.AreSame(message1, receivedMessage);
Assert.IsNotNull(receivedMessage);
Assert.AreEqual(message1.CorrelationId, receivedMessage.CorrelationId);
Assert.AreEqual("ding", text);
}
[Test]
public void EnsureWithMultipleMessageTypesInterfaceHandlerIsInvoked()
{
var bus = new Bus();
Message1 receivedMessage1 = null;
bus.AddHandler(new ActionConsumer<Message1>(m => receivedMessage1 = m));
Message2 receivedMessage2 = null;
bus.AddHandler(new ActionConsumer<Message2>(m => receivedMessage2 = m));
string text = null;
bus.AddHandler(new ActionConsumer<IEvent>(_ => { text = "ding"; }));
var message1 = new Message1 { CorrelationId = "1234" };
bus.Handle(message1);
bus.Handle(new TheEvent());
Assert.AreSame(message1, receivedMessage1);
Assert.IsNotNull(receivedMessage1);
Assert.AreEqual(message1.CorrelationId, receivedMessage1.CorrelationId);
Assert.AreEqual("ding", text);
}
public class Message1Specialization : Message1
{
}
[Test]
public void BaseTypeHandlerIsCalledCorrectly()
{
var bus = new Bus();
Message1 receivedMessage1 = null;
bus.AddHandler(new ActionConsumer<Message1>(m => receivedMessage1 = m));
var message1 = new Message1Specialization { CorrelationId = "1234" };
bus.Handle(message1);
Assert.AreSame(message1, receivedMessage1);
}
public class Message1SpecializationSpecialization : Message1Specialization
{
}
[Test]
public void BaseBaseTypeHandlerIsCalledCorrectly()
{
var bus = new Bus();
Message1 receivedMessage1 = null;
bus.AddHandler(new ActionConsumer<Message1>(m => receivedMessage1 = m));
var message1 = new Message1SpecializationSpecialization() { CorrelationId = "1234" };
bus.Handle(message1);
Assert.AreSame(message1, receivedMessage1);
}
[Test]
public void RemoveLastSubscribedHandlerDoesNotThrow()
{
var bus = new Bus();
Message1 receivedMessage1 = null;
var token = bus.AddHandler(new ActionConsumer<Message1>(m => receivedMessage1 = m));
bus.Handle(new Message1());
bus.RemoveHandler(new ActionConsumer<Message1>(m => receivedMessage1 = m), token);
}
[Test]
public void RemoveLastSubscribedHandlerClearsInternalDictionaries()
{
var bus = new Bus();
Message1 receivedMessage1 = null;
var token = bus.AddHandler(new ActionConsumer<Message1>(m => receivedMessage1 = m));
bus.Handle(new Message1());
bus.RemoveHandler(new ActionConsumer<Message1>(m => receivedMessage1 = m), token);
Assert.AreEqual(0, bus._consumerInvokers.Count);
Assert.AreEqual(0, bus._consumerInvokersDictionaries.Count);
}
[Test]
public void InterleavedRemoveHandlerRemovesCorrectHandler()
{
string ordinal = null;
var bus = new Bus();
var actionConsumer1 = new ActionConsumer<Message1>(m => ordinal = "1");
var token1 = bus.AddHandler(actionConsumer1);
var actionConsumer2 = new ActionConsumer<Message1>(m => ordinal = "2");
var token2 = bus.AddHandler(actionConsumer2);
bus.Handle(new Message1());
bus.RemoveHandler(actionConsumer1, token1);
bus.Send(new Message1());
Assert.AreEqual("2", ordinal);
}
[Test]
public void RemoveHandlerWithNullTokenThrows()
{
var bus = new Bus();
Assert.Throws<ArgumentNullException>(() => bus.RemoveHandler(new ActionConsumer<Message1>(m => { }), null));
}
[Test]
public void RemoveHandlerWithTokenThatIsNotTokenTypeThrows()
{
var bus = new Bus();
Assert.Throws<InvalidOperationException>(() => bus.RemoveHandler(new ActionConsumer<Message1>(m => { }), new object()));
}
[Test]
public void RemoveHandlerTwiceSucceeds()
{
var bus = new Bus();
var actionConsumer1 = new ActionConsumer<Message1>(m => { });
var token1 = bus.AddHandler(actionConsumer1);
bus.Send(new Message1());
bus.RemoveHandler(actionConsumer1, token1);
bus.RemoveHandler(actionConsumer1, token1);
}
public abstract class Message : IMessage
{
protected Message(string c)
{
CorrelationId = c;
}
public string CorrelationId { get; set; }
public abstract Task<IEvent> RequestAsync(IBus bus);
}
public abstract class MessageBase<TMessage, TEvent> : Message
where TEvent : IEvent where TMessage : IMessage
{
protected MessageBase() : base(Guid.NewGuid().ToString("D"))
{
}
public override async Task<IEvent> RequestAsync(IBus bus)
{
IEvent result = await bus.RequestAsync<MessageBase<TMessage, TEvent>, TEvent>(this);
return result;
}
}
public abstract class EventBase : IEvent
{
protected EventBase(string correllationId)
{
CorrelationId = correllationId;
OccurredDateTime = DateTime.UtcNow;
}
public string CorrelationId { get; set; }
public DateTime OccurredDateTime { get; set; }
}
public class Command1 : MessageBase<Command1, Event1> { }
public class Command2 : MessageBase<Command2, Event2> { }
public class Command3 : MessageBase<Command3, Event3> { }
public class Command4 : MessageBase<Command4, Event4> { }
public class Command5 : MessageBase<Command5, Event5> { }
public class Command6 : MessageBase<Command6, Event6> { }
public class Command7 : MessageBase<Command7, Event7> { }
public class Command8 : MessageBase<Command8, Event8> { }
public class Event1 : EventBase { public Event1(string c) : base(c) { } }
public class Event2 : EventBase { public Event2(string c) : base(c) { } }
public class Event3 : EventBase { public Event3(string c) : base(c) { } }
public class Event4 : EventBase { public Event4(string c) : base(c) { } }
public class Event5 : EventBase { public Event5(string c) : base(c) { } }
public class Event6 : EventBase { public Event6(string c) : base(c) { } }
public class Event7 : EventBase { public Event7(string c) : base(c) { } }
public class Event8 : EventBase { public Event8(string c) : base(c) { } }
public class TracingBus : Bus
{
public override void Handle(IMessage message)
{
var @event = message as IEvent;
if (@event != null)
{
LogEvent(@event);
}
bool wasProcessed;
var stopwatch = Stopwatch.StartNew();
var processingStartTime = DateTime.Now;
try
{
Handle(message, out wasProcessed);
var r = new Task<int>(() => 1);
}
catch (Exception ex)
{
LogException(ex);
throw;
}
if (@event == null)
{
var timeSpan = stopwatch.Elapsed;
LogOperationDuration(message.GetType(), processingStartTime, timeSpan, message.CorrelationId, wasProcessed);
}
else if (!wasProcessed)
{
throw new InvalidOperationException($"{@message.CorrelationId} of type {message.GetType().Name} was not processed.");
}
}
public List<string> Log = new List<string>();
private void LogOperationDuration(Type getType, DateTime processingStartTime, TimeSpan timeSpan, string messageCorrelationId, bool wasMessageProcessed)
{
lock (Log)
{
Log.Add($"{getType} {processingStartTime} {timeSpan} {messageCorrelationId} {wasMessageProcessed}");
}
}
private void LogException(Exception exception)
{
lock (Log)
{
Log.Add(exception.Message);
}
}
private void LogEvent(IEvent @event)
{
lock (Log)
{
Log.Add($"Event {@event.GetType().Name} occured {@event.CorrelationId}");
}
}
}
[Test, Explicit]
public void D()
{
var t = typeof(Event1);
var bus = new TracingBus();
var rng = new Random();
bus.AddHandler(new ActionConsumer<Command1>(m => { Thread.Sleep(rng.Next(0, 100)); bus.Send(new Event1(m.CorrelationId)); }));
bus.AddHandler(new ActionConsumer<Command2>(m => { Thread.Sleep(rng.Next(0, 100)); bus.Send(new Event2(m.CorrelationId)); }));
bus.AddHandler(new ActionConsumer<Command3>(m => { Thread.Sleep(rng.Next(0, 100)); bus.Send(new Event3(m.CorrelationId)); }));
bus.AddHandler(new ActionConsumer<Command4>(m => { Thread.Sleep(rng.Next(0, 100)); bus.Send(new Event4(m.CorrelationId)); }));
bus.AddHandler(new ActionConsumer<Command5>(m => { Thread.Sleep(rng.Next(0, 100)); bus.Send(new Event5(m.CorrelationId)); }));
bus.AddHandler(new ActionConsumer<Command6>(m => { Thread.Sleep(rng.Next(0, 100)); bus.Send(new Event6(m.CorrelationId)); }));
bus.AddHandler(new ActionConsumer<Command7>(m => { Thread.Sleep(rng.Next(0, 100)); bus.Send(new Event7(m.CorrelationId)); }));
bus.AddHandler(new ActionConsumer<Command8>(m => { Thread.Sleep(rng.Next(0, 100)); bus.Send(new Event8(m.CorrelationId)); }));
var commands = new List<Message>
#if false
{
new Command1(),
new Command2(),
new Command3(),
new Command4(),
new Command5(),
new Command6(),
new Command7(),
new Command8(),
new Command1(),
new Command2(),
new Command3(),
new Command4(),
new Command5(),
new Command6(),
new Command7(),
new Command8(),
};
#else
{
new Command1(),
new Command1(),
new Command2(),
new Command2(),
new Command3(),
new Command3(),
new Command4(),
new Command4(),
new Command5(),
new Command5(),
new Command6(),
new Command6(),
new Command7(),
new Command7(),
new Command8(),
new Command8(),
};
#endif
var stopwatch = Stopwatch.StartNew();
while (stopwatch.Elapsed.TotalMinutes < 2)
#pragma warning disable RECS0165 // Asynchronous methods should return a Task instead of void: TESTS
Parallel.ForEach(commands, new ParallelOptions {MaxDegreeOfParallelism = commands.Count}, async command =>
#pragma warning restore RECS0165 // Asynchronous methods should return a Task instead of void: TESTS
{
command.CorrelationId = Guid.NewGuid().ToString("D");
var result = await command.RequestAsync(bus);
});
foreach (var log in bus.Log) Trace.WriteLine(log);
Trace.WriteLine("done");
}
}
}
#pragma warning restore S1481 // Unused local variables should be removed
#pragma warning restore S1104 // Fields should not have public accessibility
| 31.793814 | 154 | 0.693174 | [
"MIT"
] | peteraritchie/Messaging.Patterns | Tests/BusTests.cs | 12,336 | C# |
using System;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Privatbank.Business.Converters
{
internal class StringDecimalConverter : JsonConverter<decimal>
{
public override decimal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return decimal.Parse(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, decimal value, JsonSerializerOptions options)
{
writer.WriteStringValue(
value.ToString(CultureInfo.InvariantCulture));
}
}
} | 30.571429 | 114 | 0.699377 | [
"MIT"
] | mindcollapse/Privatbank.Business | Privatbank.Business/Converters/StringDecimalConverter.cs | 642 | C# |
namespace Lexs4SearchRetrieveWebService
{
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("WscfGen", "1.0.0.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://niem.gov/niem/twpdes/2.0")]
public partial class DateAccuracyIndicatorCodeType
{
private string idField;
private string metadataField;
private string linkMetadataField;
private DateAccuracyIndicatorCodeSimpleType valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form=System.Xml.Schema.XmlSchemaForm.Qualified, Namespace="http://niem.gov/niem/structures/2.0", DataType="ID")]
public string id
{
get
{
return this.idField;
}
set
{
this.idField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form=System.Xml.Schema.XmlSchemaForm.Qualified, Namespace="http://niem.gov/niem/structures/2.0", DataType="IDREFS")]
public string metadata
{
get
{
return this.metadataField;
}
set
{
this.metadataField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form=System.Xml.Schema.XmlSchemaForm.Qualified, Namespace="http://niem.gov/niem/structures/2.0", DataType="IDREFS")]
public string linkMetadata
{
get
{
return this.linkMetadataField;
}
set
{
this.linkMetadataField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public DateAccuracyIndicatorCodeSimpleType Value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
}
| 29.974684 | 173 | 0.518159 | [
"Apache-2.0"
] | gtri-iead/LEXS-NET-Sample-Implementation-4.0 | LEXS Search Retrieve Service Implementation/LexsSearchRetrieveCommon/DateAccuracyIndicatorCodeType.cs | 2,368 | C# |
using System;
using System.IO;
using Ela.Parsing;
using ElaConsole.Options;
using Ela;
using System.Collections.Generic;
using Ela.Debug;
namespace ElaConsole
{
internal sealed class MessageHelper
{
#region Construction
private ElaOptions opt;
internal MessageHelper(ElaOptions opt)
{
this.opt = opt;
}
#endregion
#region Methods
internal bool ValidateOptions()
{
if (opt.ShowSymbols != SymTables.None)
opt.Debug = true;
if (opt.Silent && opt.ShowEil)
return IncompatibleOptions("-silent", "-eil");
else if (opt.Silent && opt.ShowHelp)
return IncompatibleOptions("-silent", "-help");
else if (opt.ShowTime != 0 && String.IsNullOrEmpty(opt.FileName))
return NotInteractiveOption("-time");
else if (opt.LunchInteractive && String.IsNullOrEmpty(opt.FileName))
return RequireFileOption("-inter");
else if (opt.Compile && String.IsNullOrEmpty(opt.FileName))
return RequireFileOption("-compile");
else if (opt.Compile && opt.LunchInteractive)
return IncompatibleOptions("-compile", "-inter");
else if (opt.WarningsAsErrors && opt.NoWarnings)
return IncompatibleOptions("-warnaserr", "-nowarn");
else if (opt.LinkerWarningsAsErrors && opt.LinkerNoWarnings)
return IncompatibleOptions("-linkWarnaserr", "-linkNowarn");
return true;
}
private bool IncompatibleOptions(params string[] names)
{
PrintErrorAlways("Unable to use the following options at the same time: {0}.", String.Join(",", names));
return false;
}
private bool RequireFileOption(string name)
{
PrintErrorAlways("Unable to use {0} option when a file name is not specified.", name);
return false;
}
private bool NotInteractiveOption(string name)
{
PrintErrorAlways("Unable to use {0} option in interactive mode.", name);
return false;
}
internal void PrintLogo()
{
if (!opt.NoLogo && !opt.Silent)
{
var vr = String.Empty;
var mono = Type.GetType("Mono.Runtime") != null;
var rt = mono ? "Mono" : "CLR";
if (mono)
{
var type = Type.GetType("Consts");
var fi = default(System.Reflection.FieldInfo);
if (type != null && (fi = type.GetField("MonoVersion")) != null)
vr = fi.GetValue(null).ToString();
else
vr = Environment.Version.ToString();
}
else
vr = Environment.Version.ToString();
var bit = IntPtr.Size == 4 ? "32" : "64";
Console.WriteLine("Ela version {0}", ElaVersionInfo.Version);
Console.WriteLine("Running {0} {1} {2}-bit ({3})", rt, vr, bit, Environment.OSVersion);
Console.WriteLine();
}
}
internal void PrintInteractiveModeLogo()
{
if (!opt.NoLogo && !opt.Silent)
{
Console.WriteLine("Interactive mode");
if (opt.Multiline)
{
Console.WriteLine("Enter expressions in several lines. Put a double semicolon ;; after");
Console.WriteLine("an expression to execute it.");
}
else
Console.WriteLine("Enter expressions and press <Return> to execute.");
Console.WriteLine();
}
}
internal void PrintPrompt()
{
if (!opt.Silent)
{
Console.WriteLine();
var prompt = String.IsNullOrEmpty(opt.Prompt) ? "ela" : opt.Prompt;
Console.Write(prompt + ">" + (opt.NewLinePrompt?Environment.NewLine:""));
}
}
internal void PrintSecondaryPrompt()
{
if (!opt.Silent)
{
var promptLength = String.IsNullOrEmpty(opt.Prompt) ? 3 : opt.Prompt.Length;
Console.Write(new String('-', promptLength) + ">" + (opt.NewLinePrompt ? Environment.NewLine : ""));
}
}
internal void PrintHelp()
{
using (var sr = new StreamReader(typeof(MessageHelper).Assembly.
GetManifestResourceStream("ElaConsole.Properties.Help.txt")))
Console.WriteLine(sr.ReadToEnd()
.Replace("%VERSION%", Const.Version)
.Replace("%ELA%", ElaVersionInfo.Version.ToString()));
}
internal void PrintExecuteFirstTime()
{
Console.WriteLine("Executing code first time...");
}
internal void PrintExecuteSecondTime()
{
Console.WriteLine("Execution finished. Executing second time, measuring time...");
}
internal void PrintSymTables(DebugReader gen)
{
var prev = false;
if ((opt.ShowSymbols & SymTables.Lines) == SymTables.Lines)
{
Console.WriteLine("Lines:\r\n");
Console.Write(gen.PrintSymTables(SymTables.Lines));
prev = true;
}
if ((opt.ShowSymbols & SymTables.Scopes) == SymTables.Scopes)
{
Console.WriteLine((prev ? "\r\n" : String.Empty) + "Scopes:\r\n");
Console.Write(gen.PrintSymTables(SymTables.Scopes));
}
if ((opt.ShowSymbols & SymTables.Vars) == SymTables.Vars)
{
Console.WriteLine((prev ? "\r\n" : String.Empty) + "Variables:\r\n");
Console.Write(gen.PrintSymTables(SymTables.Vars));
}
if ((opt.ShowSymbols & SymTables.Functions) == SymTables.Functions)
{
Console.WriteLine((prev ? "\r\n" : String.Empty) + "Functions:\r\n");
Console.Write(gen.PrintSymTables(SymTables.Functions));
}
}
internal void PrintUnableWriteFile(string file, Exception ex)
{
PrintError("Unable to write cast the file {0}. Error: {1}", file, ex.Message);
}
internal void PrintInvalidOption(ElaOptionException ex)
{
switch (ex.Error)
{
case ElaOptionError.InvalidFormat:
if (!String.IsNullOrEmpty(ex.Option))
PrintErrorAlways("Invalid format for the '{0}' option.", ex.Option);
else
PrintErrorAlways("Invalid command line format.");
break;
case ElaOptionError.UnknownOption:
PrintErrorAlways("Unknown command line option '{0}'.", ex.Option);
break;
}
}
internal void PrintErrors(IEnumerable<ElaMessage> errors)
{
if (!opt.Silent)
{
foreach (var e in errors)
WriteMessage(e.ToString(), e.Type);
}
}
internal void PrintInternalError(Exception ex)
{
PrintError("Internal error: {0}", ex.Message);
}
internal void PrintError(string message, params object[] args)
{
if (!opt.Silent)
{
if (args != null && args.Length > 0)
WriteMessage(String.Format(message, args), MessageType.Error);
else
WriteMessage(message, MessageType.Error);
}
}
internal void PrintErrorAlways(string message, params object[] args)
{
WriteMessage(String.Format("Ela Console error: " + message, args), MessageType.Error);
}
private void WriteMessage(string msg, MessageType type)
{
Console.WriteLine(msg);
}
#endregion
}
}
| 32.953668 | 117 | 0.500293 | [
"MIT"
] | vorov2/ela | Ela/ElaConsole/MessageHelper.cs | 8,537 | C# |
using System;
using System.Collections.Generic;
namespace EZOper.NetSiteUtilities.AopApi
{
/// <summary>
/// AOP API: alipay.trade.app.pay
/// </summary>
public class AlipayTradeAppPayRequest : IAopRequest<AlipayTradeAppPayResponse>
{
/// <summary>
/// app支付接口2.0
/// </summary>
public string BizContent { get; set; }
#region IAopRequest Members
private bool needEncrypt=false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AopObject bizModel;
public void SetNeedEncrypt(bool needEncrypt){
this.needEncrypt=needEncrypt;
}
public bool GetNeedEncrypt(){
return this.needEncrypt;
}
public void SetNotifyUrl(string notifyUrl){
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl(){
return this.notifyUrl;
}
public void SetReturnUrl(string returnUrl){
this.returnUrl = returnUrl;
}
public string GetReturnUrl(){
return this.returnUrl;
}
public void SetTerminalType(String terminalType){
this.terminalType=terminalType;
}
public string GetTerminalType(){
return this.terminalType;
}
public void SetTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
public string GetTerminalInfo(){
return this.terminalInfo;
}
public void SetProdCode(String prodCode){
this.prodCode=prodCode;
}
public string GetProdCode(){
return this.prodCode;
}
public string GetApiName()
{
return "alipay.trade.app.pay";
}
public void SetApiVersion(string apiVersion){
this.apiVersion=apiVersion;
}
public string GetApiVersion(){
return this.apiVersion;
}
public IDictionary<string, string> GetParameters()
{
AopDictionary parameters = new AopDictionary();
parameters.Add("biz_content", this.BizContent);
return parameters;
}
public AopObject GetBizModel()
{
return this.bizModel;
}
public void SetBizModel(AopObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 22.854545 | 82 | 0.596659 | [
"MIT"
] | erikzhouxin/CSharpSolution | NetSiteUtilities/AopApi/Request/AlipayTradeAppPayRequest.cs | 2,522 | C# |
//----------------------
// <auto-generated>
// This file was automatically generated. Any changes to it will be lost if and when the file is regenerated.
// </auto-generated>
//----------------------
#pragma warning disable
using System;
using SQEX.Luminous.Core.Object;
using System.Collections.Generic;
using CodeDom = System.CodeDom;
namespace SQEX.Ebony.AIGraph.Data.ConstantValue
{
[Serializable, CodeDom.Compiler.GeneratedCode("Luminaire", "0.1")]
public partial class ConstantValueFloat : SQEX.Ebony.AIGraph.Data.ConstantValue.ConstantValueBase
{
new public static ObjectType ObjectType { get; private set; }
private static PropertyContainer fieldProperties;
public float value_;
new public static void SetupObjectType()
{
if (ObjectType != null)
{
return;
}
var dummy = new ConstantValueFloat();
var properties = dummy.GetFieldProperties();
ObjectType = new ObjectType("SQEX.Ebony.AIGraph.Data.ConstantValue.ConstantValueFloat", 0, SQEX.Ebony.AIGraph.Data.ConstantValue.ConstantValueFloat.ObjectType, Construct, properties, 0, 16);
}
public override ObjectType GetObjectType()
{
return ObjectType;
}
protected override PropertyContainer GetFieldProperties()
{
if (fieldProperties != null)
{
return fieldProperties;
}
fieldProperties = new PropertyContainer("SQEX.Ebony.AIGraph.Data.ConstantValue.ConstantValueFloat", base.GetFieldProperties(), 1826674779, 804675479);
fieldProperties.AddProperty(new Property("value_", 273093519, "float", 8, 4, 1, Property.PrimitiveType.Float, 0, (char)0));
return fieldProperties;
}
private static BaseObject Construct()
{
return new ConstantValueFloat();
}
}
} | 29.954545 | 202 | 0.626201 | [
"MIT"
] | Gurrimo/Luminaire | Assets/Editor/Generated/SQEX/Ebony/AIGraph/Data/ConstantValue/ConstantValueFloat.generated.cs | 1,977 | C# |
#region License
//--------------------------------------------------
// <License>
// <Copyright> 2018 © Top Nguyen </Copyright>
// <Url> http://topnguyen.com/ </Url>
// <Author> Top </Author>
// <Project> Elect </Project>
// <File>
// <Name> HideInApiDocAttribute.cs </Name>
// <Created> 24/03/2018 11:47:03 PM </Created>
// <Key> 3121f335-b605-4024-89a3-ed0704181cb1 </Key>
// </File>
// <Summary>
// HideInApiDocAttribute.cs is a part of Elect
// </Summary>
// <License>
//--------------------------------------------------
#endregion License
using System;
namespace Elect.Web.Swagger.Attributes
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class HideInApiDocAttribute : Attribute
{
}
} | 28.642857 | 70 | 0.537406 | [
"MIT"
] | anglesen1120/Elect | src/Web/Elect.Web.Swagger/Attributes/HideInApiDocAttribute.cs | 805 | C# |
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt.
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Windows.Forms.VisualStyles;
using System.Collections.Generic;
namespace Sce.Atf.Controls.PropertyEditing
{
/// <summary>
/// Universal property editing control that can be embedded in complex property
/// editing controls. It uses TypeConverters and UITypeEditors to provide a GUI
/// for every kind of .NET property.</summary>
public class PropertyEditingControl : Control,
IWindowsFormsEditorService,
ITypeDescriptorContext,
IServiceProvider,
ICacheablePropertyControl,
IFormsOwner
{
/// <summary>
/// Constructor</summary>
public PropertyEditingControl()
{
m_editButton = new EditButton();
m_textBox = new TextBox();
// force creation of the window handles on the GUI thread
// see http://forums.msdn.microsoft.com/en-US/clr/thread/fa033425-0149-4b9a-9c8b-bcd2196d5471/
#pragma warning disable 219
IntPtr handle;
#pragma warning restore 219
handle = m_editButton.Handle;
handle = m_textBox.Handle;
base.SuspendLayout();
m_editButton.Left = base.Right - 18;
m_editButton.Size = new Size(18, 18);
m_editButton.Anchor = AnchorStyles.Right | AnchorStyles.Top;
m_editButton.Visible = false;
m_editButton.Click += editButton_Click;
m_editButton.MouseDown += editButton_MouseDown;
m_textBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom;
m_textBox.BorderStyle = BorderStyle.None;
m_textBox.LostFocus += textBox_LostFocus;
// forward textbox events as if they originated with this control
m_textBox.DragOver += textBox_DragOver;
m_textBox.DragDrop += textBox_DragDrop;
m_textBox.MouseHover += textBox_MouseHover;
m_textBox.MouseLeave += textBox_MouseLeave;
m_textBox.Visible = false;
Controls.Add(m_editButton);
Controls.Add(m_textBox);
base.ResumeLayout();
m_textBox.SizeChanged += (sender, e) => Height = m_textBox.Height + 1;
m_dropDownForm = new DropDownForm(this);
}
/// <summary>
/// Gets and sets the size of the edit button.
/// Note: The edit button is rendered differently depending on
/// what this control is being used for, e.g., a drop down button
/// or a "..." button.</summary>
public Size EditButtonSize
{
get { return m_editButton.Size; }
set
{
m_editButton.Size = value;
m_editButton.Left = base.Right - value.Width;
}
}
/// <summary>
/// Binds the control to a property and owner</summary>
/// <param name="context">Context for property editing control</param>
public void Bind(PropertyEditorControlContext context)
{
if (m_textBox.Focused)
Flush();
m_context = context;
m_descriptor = m_context.Descriptor;
bool visible = m_context != null;
base.Visible = visible;
if (visible)
{
SetTextBoxFromProperty();
bool editButtonVisible = false;
if (!m_context.IsReadOnly)
{
UITypeEditor editor = WinFormsPropertyUtils.GetUITypeEditor(m_descriptor, this);
if (editor != null)
{
editButtonVisible = true;
m_editButton.Modal = (editor.GetEditStyle(this) == UITypeEditorEditStyle.Modal);
}
}
m_editButton.Visible = editButtonVisible;
// a standard set of values that can be picked from a list, like enum (but only if we're not readonly)
if (!m_context.IsReadOnly && (m_descriptor.Converter != null))
{
TypeDescriptorContext tdcontext = new TypeDescriptorContext(m_context.LastSelectedObject, m_descriptor, null);
if (m_descriptor.Converter.GetStandardValuesExclusive(tdcontext))
{
// this will redraw the control before we get to the invalidate below
m_textBox.AutoCompleteMode = AutoCompleteMode.None;
m_textBox.AutoCompleteCustomSource.Clear();
AutoCompleteStringCollection standardVals = new AutoCompleteStringCollection();
ICollection values = m_descriptor.Converter.GetStandardValues(tdcontext);
foreach (object item in values)
standardVals.Add(item.ToString());
m_textBox.AutoCompleteCustomSource = standardVals;
// this will redraw the control before we get to the invalidate below
m_textBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
m_textBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
}
else
{
// this will redraw the control before we get to the invalidate below
m_textBox.AutoCompleteMode = AutoCompleteMode.None;
m_textBox.AutoCompleteSource = AutoCompleteSource.None;
m_textBox.AutoCompleteCustomSource.Clear();
}
}
else
{
// this will redraw the control before we get to the invalidate below
m_textBox.AutoCompleteMode = AutoCompleteMode.None;
m_textBox.AutoCompleteSource = AutoCompleteSource.None;
m_textBox.AutoCompleteCustomSource.Clear();
}
PerformLayout();
Invalidate();
}
}
/// <summary>
/// Cancels the current edit</summary>
public void CancelEdit()
{
SetTextBoxFromProperty();
DisableTextBox();
}
/// <summary>
/// Forces the current edit to finish</summary>
public void Flush()
{
SetPropertyFromTextBox();
}
#region IFormsOwner
/// <summary>
/// If this control uses a top level form as the drop down box, gets that form so
/// users of this control can consider if as part of the control for focus situations</summary>
public IEnumerable<Form> Forms
{
get { yield return this.m_dropDownForm; }
}
#endregion
#region ICacheablePropertyControl
/// <summary>
/// Gets true iff this control can be used indefinitely, regardless of whether the associated
/// PropertyEditorControlContext's SelectedObjects property changes, i.e., the selection changes.
/// This property must be constant for the life of this control.</summary>
public virtual bool Cacheable
{
get { return true; }
}
#endregion
/// <summary>
/// Custom string formatting flags, in addition to the regular StringFormat flags</summary>
public enum CustomStringFormatFlags
{
/// <summary>
/// No formatting</summary>
None = 0,
/// <summary>
/// If the string doesn't fit, ellipses are used on the left side</summary>
TrimLeftWithEllipses = 1
}
/// <summary>
/// Formatting to use for displaying the property value</summary>
public class ExtendedStringFormat
{
/// <summary>
/// StringFormat used by System.Drawing.System.Drawing to format string</summary>
public System.Drawing.StringFormat Format;
/// <summary>
/// CustomStringFormatFlags used to format string</summary>
public CustomStringFormatFlags CustomFlags;
}
/// <summary>
/// Gets or sets the text formatting that is used to display a property as text. Modify this property
/// to change text rendering in all PropertyEditingControls. Is a subset of ExtendedTextFormat.
/// Setting this also affects the ExtendedTextFormat property.</summary>
public static StringFormat TextFormat
{
get { return s_textFormat.Format; }
set { s_textFormat.Format = value; }
}
/// <summary>
/// Gets or sets additional text formatting information. Setting this also affects the TextFormat property.</summary>
public static ExtendedStringFormat ExtendedTextFormat
{
get { return s_textFormat; }
set { s_textFormat = value; }
}
/// <summary>
/// Gets whether the control is currently drawing the property as an editable value</summary>
public static bool DrawingEditableValue
{
get { return s_drawingEditableValue; }
}
/// <summary>
/// Draws the property editing representation, in the same way that the control
/// presents the property in the GUI. Use this method to draw inactive properties
/// when multitasking a single PropertyEditingControl.</summary>
/// <param name="descriptor">Property descriptor</param>
/// <param name="context">Type descriptor context</param>
/// <param name="bounds">Bounds containing graphics</param>
/// <param name="font">Font to use for rendering property text</param>
/// <param name="brush">Brush for rendering property text</param>
/// <param name="g">Graphics object</param>
public static void DrawProperty(
PropertyDescriptor descriptor,
ITypeDescriptorContext context,
Rectangle bounds,
Font font,
Brush brush,
Graphics g)
{
object owner = context.Instance;
if (owner == null)
return;
UITypeEditor editor = WinFormsPropertyUtils.GetUITypeEditor(descriptor, context);
if (editor != null)
{
if (editor.GetPaintValueSupported(context))
{
object value = descriptor.GetValue(owner);
Rectangle paintRect = new Rectangle(
bounds.Left + 1,
bounds.Top + 1,
PaintRectWidth,
PaintRectHeight);
editor.PaintValue(new PaintValueEventArgs(context, value, g, paintRect));
bounds.X += PaintRectTextOffset;
bounds.Width -= PaintRectTextOffset;
g.DrawRectangle(SystemPens.ControlDark, paintRect);
}
}
string valueString = PropertyUtils.GetPropertyText(owner, descriptor);
bounds.Height = font.Height;
if (s_textFormat.CustomFlags == CustomStringFormatFlags.TrimLeftWithEllipses)
valueString = TrimStringLeftWithEllipses(valueString, bounds, font, g);
g.DrawString(valueString, font, brush, bounds, s_textFormat.Format);
}
private const int PaintRectWidth = 19;
private const int PaintRectHeight = 15;
private const int PaintRectTextOffset = PaintRectWidth + 4;
private const int TrimmingEllipsesWidth = 16;
private static string TrimStringLeftWithEllipses(string text, Rectangle bounds, Font font, Graphics graphics)
{
if (text.Length == 0)
return text;
if (bounds.Width == 0)
return "";
SizeF size = graphics.MeasureString(text, font);
if ((int)size.Width <= bounds.Width)
return text;
int targetWidth = bounds.Width - TrimmingEllipsesWidth;
if (targetWidth <= 0)
return "";
// Shorten our string until it more or less fits.
int iteration = 0;
do
{
float visibleRatio = (float)targetWidth / size.Width; // < 1
int guessedTextLength = (int)(text.Length * visibleRatio);
if (guessedTextLength == text.Length)
--guessedTextLength;
// Short text to guessedTextLength chars by removing chars at the front
text = text.Remove(0, text.Length - guessedTextLength);
size = graphics.MeasureString(text, font);
}
while (size.Width > targetWidth && ++iteration < 5 && text.Length > 0);
return "... " + text;
}
/// <summary>
/// Event that is raised when a property is edited</summary>
public event EventHandler<PropertyEditedEventArgs> PropertyEdited;
/// <summary>
/// Performs actions related to a property edit. Calls PropertyEdited event.</summary>
/// <param name="e">Event args</param>
protected virtual void OnPropertyEdited(PropertyEditedEventArgs e)
{
if (PropertyEdited != null)
{
PropertyEdited(this, e);
}
}
#region IServiceProvider Members
/// <summary>
/// Gets the service object of the specified type</summary>
/// <param name="serviceType">An object that specifies the type of service object to get</param>
/// <returns>A service object of type serviceType, or null if there is no service object of the given type</returns>
public new object GetService(Type serviceType)
{
if (typeof(IWindowsFormsEditorService).IsAssignableFrom(serviceType) ||
typeof(ITypeDescriptorContext).IsAssignableFrom(serviceType))
return this;
return base.GetService(serviceType);
}
#endregion
#region IWindowsFormsEditorService Members
/// <summary>
/// Drops down editor control</summary>
/// <param name="control">The control to drop down</param>
public void DropDownControl(Control control)
{
m_dropDownForm.SetControl(control);
Point rightBottom = new Point(base.Right, base.Bottom);
rightBottom = base.Parent.PointToScreen(rightBottom);
Rectangle bounds = new Rectangle(
rightBottom.X - control.Width, rightBottom.Y, control.Width, control.Height);
//Rectangle workingArea = Screen.FromControl(this).WorkingArea;
Applications.SkinService.ApplyActiveSkin(control);
m_dropDownForm.Bounds = bounds;
m_dropDownForm.Visible = true;
control.Focus();
while (m_dropDownForm.Visible)
{
Application.DoEvents();
MsgWaitForMultipleObjects(0, 0, true, 250, 255);
}
}
/// <summary>
/// Closes the dropped down editor</summary>
public void CloseDropDown()
{
if (m_closingDropDown)
return;
// set the focus back to the text box right here so this control never loses focus
EnableTextBox();
try
{
m_closingDropDown = true;
if (m_dropDownForm.Visible)
{
m_dropDownForm.SetControl(null);
m_dropDownForm.Visible = false;
}
}
finally
{
m_closingDropDown = false;
}
}
/// <summary>
/// Opens a dialog editor</summary>
/// <param name="dialog">The dialog to open</param>
/// <returns>Result of user interaction with dialog</returns>
public DialogResult ShowDialog(Form dialog)
{
dialog.ShowDialog(this);
return dialog.DialogResult;
}
[DllImport("user32.dll")]
private static extern int MsgWaitForMultipleObjects(
int nCount, // number of handles in array
int pHandles, // object-handle array
bool bWaitAll, // wait option
int dwMilliseconds, // time-out interval
int dwWakeMask // input-event type
);
/// <summary>
/// Hides the drop-down editor</summary>
protected void HideForm()
{
CloseDropDown();
}
#endregion
#region ITypeDescriptorContext Members
/// <summary>
/// Gets the object that is connected with this type descriptor request</summary>
/// <returns>The object that invokes the method on the <see cref="T:System.ComponentModel.TypeDescriptor"></see>;
/// otherwise, null if there is no object responsible for the call</returns>
public object Instance
{
get { return m_context.LastSelectedObject; }
}
/// <summary>
/// Raises the <see cref="E:System.ComponentModel.Design.IComponentChangeService.ComponentChanged"></see> event</summary>
public void OnComponentChanged()
{
}
/// <summary>
/// Raises the <see cref="E:System.ComponentModel.Design.IComponentChangeService.ComponentChanging"></see> event</summary>
/// <returns>True iff this object can be changed</returns>
public bool OnComponentChanging()
{
return true;
}
/// <summary>
/// Gets the <see cref="T:System.ComponentModel.PropertyDescriptor"></see> that is associated with the given context item</summary>
/// <returns>The <see cref="T:System.ComponentModel.PropertyDescriptor"></see> that describes the given context item;
/// otherwise, null if there is no <see cref="T:System.ComponentModel.PropertyDescriptor"></see> responsible for the call</returns>
public PropertyDescriptor PropertyDescriptor
{
get { return m_descriptor; }
}
#endregion
#region Overrides
/// <summary>
/// Sets whether the control can drag and drop</summary>
public override bool AllowDrop
{
set
{
base.AllowDrop = value;
m_textBox.AllowDrop = value;
}
}
/// <summary>
/// Process a command shortcut key. If the Control key needs to be held down,
/// then this is the place to check for it.</summary>
/// <param name="msg">System.Windows.Forms.Message representing the window message to process</param>
/// <param name="keyData">System.Windows.Forms.Keys value for key to process</param>
/// <returns>True iff character was processed by control</returns>
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if ((keyData == (Keys.Down | Keys.Alt) || keyData == (Keys.Down | Keys.Control))
&& m_editButton.Visible)
{
OpenDropDownEditor();
}
return base.ProcessCmdKey(ref msg, keyData);
}
/// <summary>
/// Processes a dialog key</summary>
/// <param name="keyData">One of the System.Windows.Forms.Keys values that represents the key to process</param>
/// <returns>True iff the key was processed by the control</returns>
protected override bool ProcessDialogKey(Keys keyData)
{
if (keyData == Keys.Enter)
{
// process the Enter keys on the base control as well. The default Control Enter key
// handler must do something significant. This is the only way I have found for users of the
// ProperyEditingControl, in this case the GridView to get its call to ProcessDialogKey
// This needs to be called before we close this text box, otherwise the ProcessDialogKey will not be
// consumed and will be fired AGAIN (in this case in the GridView).
base.ProcessDialogKey(keyData);
Flush();
DisableTextBox();
// hide the editing control to give visual feedback of committed change
Visible = false;
return true;
}
else if (keyData == Keys.Escape)
{
// process the Escape keys on the base control as well. The default Control Esc key
// handler must do something significant. This is the only way I have found for users of the
// ProperyEditingControl, in this case the GridView to get its call to ProcessDialogKey
// This needs to be called before we close this text box, otherwise the ProcessDialogKey will not be
// consumed and will be fired AGAIN (in this case in the GridView).
base.ProcessDialogKey(keyData);
CancelEdit();
return true;
}
else if (keyData == Keys.Tab || keyData == (Keys.Tab | Keys.Shift))
{
Flush();
}
return base.ProcessDialogKey(keyData);
}
/// <summary>
/// Performs custom actions and raises the <see cref="E:System.Windows.Forms.Control.Layout"></see> event</summary>
/// <param name="levent">A <see cref="T:System.Windows.Forms.LayoutEventArgs"></see> that contains the event data</param>
protected override void OnLayout(LayoutEventArgs levent)
{
if (m_context != null)
{
int x = 1;
int width = base.Width;
UITypeEditor editor = WinFormsPropertyUtils.GetUITypeEditor(m_descriptor, this);
if (editor != null)
{
if (editor.GetPaintValueSupported(this))
x += PaintRectTextOffset;
m_textBox.Left = x;
m_textBox.Width = width - x - m_editButton.Width;
}
else
{
// no editor, use text box and type converters
m_textBox.Left = x;
m_textBox.Width = width - x;
}
}
base.OnLayout(levent);
}
/// <summary>
/// Performs custom actions and raises the <see cref="E:System.Windows.Forms.Control.BackColorChanged"></see> event</summary>
/// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data</param>
protected override void OnBackColorChanged(EventArgs e)
{
m_textBox.BackColor = BackColor;
base.OnBackColorChanged(e);
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Control.Paint"></see> event and performs custom actions</summary>
/// <param name="e">A <see cref="T:System.Windows.Forms.PaintEventArgs"></see> that contains the event data</param>
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// This code below is required for display property values while editing a row in the spreadsheet-style GridView.
// http://tracker.ship.scea.com/jira/browse/WWSATF-1485
if (m_context != null)
{
Rectangle bounds = base.ClientRectangle;
bounds.Width -= m_editButton.Width;
Brush brush = m_descriptor.IsReadOnly ? SystemBrushes.GrayText : SystemBrushes.ControlText;
try
{
s_drawingEditableValue = true;
PropertyEditingControl.DrawProperty(
m_descriptor, this, bounds, Font, brush, e.Graphics);
}
finally
{
s_drawingEditableValue = false;
}
}
}
/// <summary>
/// Makes the TextBox in this property editor visible</summary>
protected void EnableTextBox()
{
// pass focus on to our TextBox control
m_textBox.Show();
SetTextBoxFromProperty();
m_textBox.SelectAll();
m_textBox.Focus();
}
/// <summary>
/// Makes the TextBox in this property editor invisible</summary>
protected void DisableTextBox()
{
m_textBox.Hide();
}
/// <summary>
/// Performs custom actions and raises the <see cref="E:System.Windows.Forms.Control.MouseClick"></see> event</summary>
/// <param name="e">A MouseEventArgs that contains the event data</param>
protected override void OnMouseClick(MouseEventArgs e)
{
EnableTextBox();
base.OnMouseClick(e);
}
/// <summary>
/// Performs custom actions and raises the <see cref="E:System.Windows.Forms.Control.GotFocus"></see> event</summary>
/// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data</param>
protected override void OnGotFocus(EventArgs e)
{
EnableTextBox();
base.OnGotFocus(e);
}
/// <summary>
/// Forces the control to invalidate its client area and immediately redraw itself and any child controls.</summary>
/// <PermissionSet><IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/><IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet>
public override void Refresh()
{
if (m_textBox.Visible)
SetTextBoxFromProperty();
base.Refresh();
}
#endregion
#region Event Handlers
private void editButton_MouseDown(object sender, MouseEventArgs e)
{
m_absorbEditButtonClick = m_isEditing;
}
private void editButton_Click(object sender, EventArgs e)
{
if (m_absorbEditButtonClick)
{
m_absorbEditButtonClick = false;
m_dropDownForm.Visible = false; //http://tracker.ship.scea.com/jira/browse/WWSATF-1486
return;
}
OpenDropDownEditor();
}
private void textBox_LostFocus(object sender, EventArgs e)
{
SetPropertyFromTextBox();
// if we are editing via the drop down, do not disable the text box
// we want to keep focus on the text box here. other wise focus will just to what ever
// control is next in line, then will be set right back to this control a moment later.
if (!m_isEditing)
DisableTextBox();
}
private void textBox_DragOver(object sender, DragEventArgs e)
{
// raise event on this control
OnDragOver(e);
}
private void textBox_DragDrop(object sender, DragEventArgs e)
{
// raise event on this control
OnDragDrop(e);
}
private void textBox_MouseHover(object sender, EventArgs e)
{
// raise event on this control
OnMouseHover(e);
}
private void textBox_MouseLeave(object sender, EventArgs e)
{
// raise event on this control
OnMouseLeave(e);
}
#endregion
private void OpenDropDownEditor()
{
if (m_isEditing) return;
try
{
m_isEditing = true;
object oldValue, value;
var oldContext = m_context;
// Alan Beckus: save references to all the required objects to perform the transaction.
// Because EditValue(...) enters modal loop using Application.DonEvent()
// consequently selectedObjects, transaction and event m_context itself can change
// before returning from EditValue(...).
// note: previous attempt to solve this issue was to cache selected objects inside
// m_context but it failed to solve the issue because the cache was cleared
// by PropertyView before it can be used.
List<object> selection = new List<object>(m_context.SelectedObjects);
var transactionContext = m_context.TransactionContext;
var descriptor = m_context.Descriptor;
oldValue = m_context.GetValue();
UITypeEditor editor = WinFormsPropertyUtils.GetUITypeEditor(m_descriptor, this);
// Bring up the editor which can cause Bind() to be called, so make sure that we use the
// correct context and selection after this EditValue call.
value = editor.EditValue(this, this, oldValue);
transactionContext.DoTransaction(delegate
{
foreach (object selectedObject in selection)
PropertyUtils.SetProperty(selectedObject, descriptor, value);
},string.Format("Edit: {0}".Localize(), descriptor.DisplayName));
// notify that we just changed a value
NotifyPropertyEdit(oldValue, value);
// Refresh text box, paint rect
if (oldContext == m_context)
{
SetTextBoxFromProperty();
EnableTextBox();
}
Invalidate();
}
finally
{
m_isEditing = false;
}
}
private void SetPropertyFromTextBox()
{
if (m_settingValue)
return;
try
{
m_settingValue = true;
string newText = m_textBox.Text;
// for enum list, ensure case correctness
if (m_textBox.AutoCompleteEnabled)
{
bool validText = false;
foreach (string item in m_textBox.AutoCompleteCustomSource)
{
if (string.Compare(item, newText, StringComparison.CurrentCultureIgnoreCase) == 0)
{
newText = item;
validText = true;
break;
}
}
if (!validText && m_context != null)
{
newText = m_initialText;
}
}
bool userHasEdited = newText != m_initialText;
if (m_context != null &&
userHasEdited)
{
object oldValue = m_context.GetValue();
// get prospective new value, normalized for the property descriptor
object value;
if (TryConvertString(newText, out value))
{
m_context.SetValue(value);
NotifyPropertyEdit(oldValue, value);
m_initialText = newText;
}
}
}
finally
{
m_settingValue = false;
}
}
private bool TryConvertString(string newText, out object value)
{
bool succeeded = false;
value = newText;
try
{
TypeConverter converter = m_descriptor.Converter;
if (converter != null &&
value != null &&
converter.CanConvertFrom(value.GetType()))
{
// makes sure a reference to this is available within the ConvertFrom() method in
// the CoreRefTypeConverter. We use this to trigger the DropDown when someone pastes a FileName
// into the Control
value = converter.ConvertFrom(this, CultureInfo.CurrentCulture, value);
}
succeeded = true;
}
catch (Exception ex)
{
// NotSupportedException, FormatException, and Exception can be thrown. For example,
// for a string "14'" being converted to an Int32. So, I made this a catch (Exception). --Ron
CancelEdit();
MessageBox.Show(ex.Message, "Error".Localize());
}
return succeeded;
}
private void SetTextBoxFromProperty()
{
if (m_context != null && m_context.LastSelectedObject != null)
{
string propertyText = PropertyUtils.GetPropertyText(m_context.LastSelectedObject, m_descriptor);
m_initialText = propertyText;
m_textBox.Text = propertyText;
m_textBox.Font = Font;
m_textBox.ReadOnly = m_descriptor.IsReadOnly;
m_textBox.ForeColor = (m_descriptor.IsReadOnly) ? SystemColors.GrayText : ForeColor;
}
}
private void NotifyPropertyEdit(object oldValue, object newValue)
{
OnPropertyEdited(
new PropertyEditedEventArgs(m_context.LastSelectedObject, m_descriptor, oldValue, newValue));
}
private PropertyEditorControlContext m_context;
private PropertyDescriptor m_descriptor;
private string m_initialText = string.Empty;
private bool m_settingValue;
private bool m_isEditing;
private bool m_absorbEditButtonClick;
private readonly EditButton m_editButton;
private readonly TextBox m_textBox;
private readonly DropDownForm m_dropDownForm;
private bool m_closingDropDown;
/// <summary>
/// Static constructor</summary>
static PropertyEditingControl()
{
s_textFormat = new ExtendedStringFormat();
s_textFormat.Format = new System.Drawing.StringFormat();
s_textFormat.Format.Alignment = StringAlignment.Near;
s_textFormat.Format.Trimming = StringTrimming.EllipsisPath;// StringTrimming.EllipsisCharacter;
s_textFormat.Format.FormatFlags = StringFormatFlags.NoWrap;
s_textFormat.CustomFlags = CustomStringFormatFlags.None;
}
private static ExtendedStringFormat s_textFormat;
private static bool s_drawingEditableValue;
private class EditButton : Button
{
public EditButton()
{
base.SetStyle(ControlStyles.Selectable, true);
base.BackColor = SystemColors.Control;
base.ForeColor = SystemColors.ControlText;
base.TabStop = false;
base.IsDefault = false;
}
/// <summary>
/// Gets or sets whether the button is for a modal dialog or a drop down control</summary>
public bool Modal
{
get { return m_modal; }
set
{
m_modal = value;
Invalidate();
}
}
protected override void OnMouseDown(MouseEventArgs arg)
{
base.OnMouseDown(arg);
if (arg.Button == MouseButtons.Left)
{
m_pushed = true;
Invalidate();
}
}
protected override void OnMouseUp(MouseEventArgs arg)
{
base.OnMouseUp(arg);
if (arg.Button == MouseButtons.Left)
{
m_pushed = false;
Invalidate();
}
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
Rectangle r = ClientRectangle;
if (m_modal)
{
base.OnPaint(e);
// draws "..."
int x = r.X + r.Width / 2 - 5;
int y = r.Bottom - 5;
using (Brush brush = new SolidBrush(Enabled ? SystemColors.ControlText : SystemColors.GrayText))
{
g.FillRectangle(brush, x, y, 2, 2);
g.FillRectangle(brush, x + 4, y, 2, 2);
g.FillRectangle(brush, x + 8, y, 2, 2);
}
}
else
{
if (Application.RenderWithVisualStyles)
{
ComboBoxRenderer.DrawDropDownButton(
g,
ClientRectangle,
!Enabled ? ComboBoxState.Disabled : (m_pushed ? ComboBoxState.Pressed : ComboBoxState.Normal));
}
else
{
ControlPaint.DrawButton(
g,
ClientRectangle,
!Enabled ? ButtonState.Inactive : (m_pushed ? ButtonState.Pushed : ButtonState.Normal));
}
}
}
private bool m_modal;
private bool m_pushed;
}
private class DropDownForm : Form
{
public DropDownForm(PropertyEditingControl parent)
{
m_parent = parent;
base.StartPosition = FormStartPosition.Manual;
base.ShowInTaskbar = false;
base.ControlBox = false;
base.MinimizeBox = false;
base.MaximizeBox = false;
base.FormBorderStyle = FormBorderStyle.None;
base.Visible = false;
}
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
m_parent.CloseDropDown();
base.OnMouseDown(e);
}
protected override void OnClosed(EventArgs e)
{
if (Visible)
m_parent.CloseDropDown();
base.OnClosed(e);
}
protected override void OnDeactivate(EventArgs e)
{
if (Visible)
m_parent.CloseDropDown();
base.OnDeactivate(e);
}
public void SetControl(Control control)
{
if (m_control != null)
{
Controls.Remove(m_control);
m_control = null;
}
if (control != null)
{
control.Width = Math.Max(m_parent.Width, control.Width);
Size = control.Size;
m_control = control;
Controls.Add(m_control);
m_control.Location = new Point(0, 0);
m_control.Visible = true;
}
Enabled = m_control != null;
}
private Control m_control;
private readonly PropertyEditingControl m_parent;
}
private class TextBox : System.Windows.Forms.TextBox
{
public TextBox()
{
AutoSize = false;
}
protected override void OnFontChanged(EventArgs e)
{
base.OnFontChanged(e); //updates FontHeight property
Height = FontHeight;
}
// Up and Down keys need to be seen by our containing Control (PropertyView or one of the
// derived classes, PropertyGridView or GridView) in order to allow for navigation to
// other properties.
protected override bool IsInputKey(Keys keyData)
{
if (keyData == Keys.Up ||
keyData == Keys.Down)
{
return false;
}
// For the spreadsheet-style property editor, we want to let it change the focused
// property using the left and right arrow keys, but only if the caret is at either
// end of the text.
if (keyData == Keys.Left &&
SelectionStart == 0 &&
SelectionLength == 0)
{
return false;
}
if (keyData == Keys.Right &&
SelectionStart == Text.Length)
{
return false;
}
// If text is already selected, and the user presses the left arrow key (without holding
// a modifier key), the caret should go to the front. The default behavior is to put the
// caret at the end.
if (keyData == Keys.Left &&
SelectionLength > 0)
{
SelectionLength = 0;
}
return base.IsInputKey(keyData);
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (AutoCompleteEnabled)
{
if (char.IsLetterOrDigit(e.KeyChar))
{
int length = SelectionStart < base.Text.Length ? SelectionStart : base.Text.Length;
StringBuilder sb = new StringBuilder();
sb.Append(base.Text.Substring(0, length));
sb.Append(e.KeyChar);
string text = sb.ToString();
if (!ValidateInput(text))
e.Handled = true;
}
}
base.OnKeyPress(e);
}
public bool AutoCompleteEnabled
{
get
{
return AutoCompleteMode == AutoCompleteMode.SuggestAppend && AutoCompleteCustomSource.Count > 0;
}
}
private bool ValidateInput(string text)
{
foreach (string item in AutoCompleteCustomSource)
{
if (string.Compare(text, 0, item, 0, text.Length, true, CultureInfo.CurrentCulture) == 0)
return true;
}
return false;
}
}
}
}
| 38.806009 | 787 | 0.528125 | [
"Apache-2.0"
] | HaKDMoDz/ATF | Framework/Atf.Gui.WinForms/Controls/PropertyEditing/PropertyEditingControl.cs | 44,048 | C# |
using System.ComponentModel;
namespace AdventOfCode
{
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyChange(string propertyName)
{
if (PropertyChanged != null)
{
var e = new PropertyChangedEventArgs(propertyName);
PropertyChanged(this, e);
}
}
}
}
| 23.631579 | 67 | 0.605791 | [
"MIT"
] | tpryde/AoC2020 | AdventOfCode2020/src/UI/BaseViewModel.cs | 451 | C# |
using SFML.System;
using SFML.Graphics;
namespace polygon_collision_detection {
public abstract class body {
public enum enumBodyType {
point,
line,
circle,
rectangle,
polygon
}
#region "Properties"
internal enumBodyType bodytype;
public enumBodyType BodyType => bodytype;
internal Vector2f position;
public Vector2f Position => position;
internal Vector2f velocity;
public Vector2f Velocity {
get { return velocity; }
set { velocity = value; }
}
internal float angle;
public float Angle {
get { return angle; }
set { angle = value; }
}
internal float angularVelocity;
public float AngularVelocity {
get { return angularVelocity; }
set { angularVelocity = value; }
}
internal float scale = 1.0f;
public float Scale {
get { return scale; }
set { scale = value; }
}
internal float mass = 100f;
public float Mass {
get { return mass; }
set { mass = value; }
}
#endregion
#region "Methods"
public void update(float delta) {
SetPosition(Position + Velocity * delta);
Angle += AngularVelocity * delta;
}
public virtual void draw(RenderWindow window) { }
public void SetPosition(Vector2f pos) {
position = pos;
}
public void SetXPosition(float x) {
position.X = x;
}
public void SetYPosition(float y) {
position.Y = y;
}
public void SetColour(Color c) {
switch (bodytype) {
case body.enumBodyType.point:
((point)this).Colour = c;
break;
case body.enumBodyType.line:
((line)this).Colour = c;
break;
case body.enumBodyType.circle:
((circle)this).FillColour = c;
break;
case body.enumBodyType.rectangle:
((rectangle)this).FillColour = c;
break;
case body.enumBodyType.polygon:
((polygon)this).OutlineColour = c;
break;
}
}
#endregion
}
} | 26.695652 | 57 | 0.492671 | [
"MIT"
] | JohnGinnane/polygon-collision-detection | classes/entities/body.cs | 2,456 | C# |
using UnityEngine;
using UnityEngine.UI;
namespace OmiyaGames.Menus
{
///-----------------------------------------------------------------------
/// <copyright file="OptionsListMenu.cs" company="Omiya Games">
/// The MIT License (MIT)
///
/// Copyright (c) 2014-2018 Omiya Games
///
/// 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.
/// </copyright>
/// <author>Taro Omiya</author>
/// <date>6/11/2018</date>
///-----------------------------------------------------------------------
/// <summary>
/// Menu that provides a list of option categories.
/// You can retrieve this menu from the singleton script,
/// <code>MenuManager</code>.
/// </summary>
/// <seealso cref="MenuManager"/>
[RequireComponent(typeof(Animator))]
[DisallowMultipleComponent]
public class OptionsListMenu : IOptionsMenu
{
private const BackgroundMenu.BackgroundType DefaultBackground = BackgroundMenu.BackgroundType.GradientRightToLeft;
[Header("Options List")]
[SerializeField]
private Button backButton;
[SerializeField]
private PlatformSpecificButton audioButton;
[SerializeField]
private PlatformSpecificButton controlsButton;
[SerializeField]
private PlatformSpecificButton graphicsButton;
[SerializeField]
private PlatformSpecificButton accessibilityButton;
[SerializeField]
private PlatformSpecificButton languageButton;
[SerializeField]
private PlatformSpecificButton resetDataButton;
[SerializeField]
private string resetDataMessage = "Options Reset Message";
private Selectable cachedDefaultButton = null;
private PlatformSpecificButton[] cachedAllButtons = null;
private BackgroundSettings background = new BackgroundSettings();
#region Overridden Properties
public override Type MenuType
{
get
{
return Type.ManagedMenu;
}
}
public override Selectable DefaultUi
{
get
{
if(CurrentDefaultUi != null)
{
return CurrentDefaultUi;
}
else if(cachedDefaultButton == null)
{
foreach(PlatformSpecificButton button in AllButtons)
{
if(button.EnabledFor.IsSupported() == true)
{
cachedDefaultButton = button.Component;
break;
}
}
}
return cachedDefaultButton;
}
}
public override BackgroundMenu.BackgroundType Background
{
get
{
return background.BackgroundState;
}
}
public override string TitleTranslationKey
{
get
{
return background.TitleTranslationKey;
}
}
public override object[] TitleTranslationArgs
{
get
{
return background.TitleTranslationArgs;
}
}
#endregion
Selectable CurrentDefaultUi
{
get;
set;
} = null;
PlatformSpecificButton[] AllButtons
{
get
{
if(cachedAllButtons == null)
{
cachedAllButtons = new PlatformSpecificButton[]
{
audioButton,
controlsButton,
graphicsButton,
accessibilityButton,
languageButton,
resetDataButton
};
}
return cachedAllButtons;
}
}
protected override void OnSetup()
{
// Call base method
base.OnSetup();
// Setup every button
foreach (PlatformSpecificButton button in AllButtons)
{
button.Setup();
}
CurrentDefaultUi = null;
}
/// <summary>
/// Sets up the dialog background based off of another menu.
/// </summary>
public void UpdateDialog(IMenu copyBackgroundSettings)
{
// Check the parameter
if (copyBackgroundSettings != null)
{
background.CopySettings(copyBackgroundSettings);
CurrentDefaultUi = null;
}
}
/// <summary>
/// Sets up the dialog with the proper message and time on when to select the default dialog selection
/// </summary>
/// <param name="messageTranslatedKey"></param>
/// <param name="automaticallySelectDefaultAfterSeconds"></param>
public void UpdateDialog(BackgroundMenu.BackgroundType backgroundType = DefaultBackground, string titleTranslationKey = null, params object[] titleTranslationArgs)
{
// Update background
background.Update(backgroundType, titleTranslationKey, titleTranslationArgs);
}
#region UI Events
public void OnAudioClicked()
{
// Make sure the button isn't locked yet
if (IsListeningToEvents == true)
{
// Show the audio options
Manager.Show<OptionsAudioMenu>();
// Indicate this button was clicked
CurrentDefaultUi = audioButton.Component;
}
}
public void OnControlsClicked()
{
// Make sure the button isn't locked yet
if (IsListeningToEvents == true)
{
// Show the controls options
Manager.Show<OptionsControlsMenu>();
// Indicate this button was clicked
CurrentDefaultUi = controlsButton.Component;
}
}
public void OnGraphicsClicked()
{
// Make sure the button isn't locked yet
if (IsListeningToEvents == true)
{
// Show the graphics options
Manager.Show<OptionsGraphicsMenu>();
// Indicate this button was clicked
CurrentDefaultUi = graphicsButton.Component;
}
}
public void OnAccessibilityClicked()
{
// Make sure the button isn't locked yet
if (IsListeningToEvents == true)
{
// Show the accessibility options
Manager.Show<OptionsAccessibilityMenu>();
// Indicate this button was clicked
CurrentDefaultUi = accessibilityButton.Component;
}
}
public void OnLanguageClicked()
{
// Make sure the button isn't locked yet
if (IsListeningToEvents == true)
{
// Show the language options
Manager.Show<OptionsLanguageMenu>();
// Indicate this button was clicked
CurrentDefaultUi = languageButton.Component;
}
}
public void OnResetDataClicked()
{
// Make sure the button isn't locked yet
if (IsListeningToEvents == true)
{
ConfirmationMenu menu = Manager.GetMenu<ConfirmationMenu>();
if (menu != null)
{
// Display confirmation dialog
menu.DefaultToYes = false;
menu.UpdateDialog(this, resetDataMessage);
menu.Show(CheckResetSavedDataConfirmation);
}
// Indicate this button was clicked
CurrentDefaultUi = resetDataButton.Component;
}
}
#endregion
#region Helper Methods
void CheckResetSavedDataConfirmation(IMenu source, VisibilityState from, VisibilityState to)
{
if ((source is ConfirmationMenu) && (to == VisibilityState.Hidden) && (((ConfirmationMenu)source).IsYesSelected == true))
{
// Clear settings
Settings.ClearSettings();
// Update the start menu, if one is available
StartMenu start = Manager.GetMenu<StartMenu>();
if (start != null)
{
start.SetupStartButton();
}
// Update the level select menu, if one is available
LevelSelectMenu levelSelect = Manager.GetMenu<LevelSelectMenu>();
if (levelSelect != null)
{
levelSelect.SetButtonsEnabled(true);
}
}
}
#endregion
}
}
| 33.812709 | 171 | 0.53452 | [
"MIT"
] | OmiyaGames/what-goes-around | Assets/Omiya Games/Scripts/Menus/Options/OptionsListMenu.cs | 10,112 | 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("Lab4")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Lab4")]
[assembly: AssemblyCopyright("Copyright © Microsoft 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("3ea0edb3-79ef-4eaa-8c20-32da10e99837")]
// 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.810811 | 84 | 0.745533 | [
"Artistic-2.0"
] | WildElf/BeginningCSharp | Lab4/Lab4/Properties/AssemblyInfo.cs | 1,402 | C# |
using System;
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Sys.Workflow.Engine.Impl.Bpmn.Listeners
{
using Sys.Workflow.Engine.Delegate;
/// <summary>
///
/// </summary>
[Serializable]
public class ExpressionTaskListener : ITaskListener
{
/// <summary>
///
/// </summary>
protected internal IExpression expression;
/// <summary>
///
/// </summary>
/// <param name="expression"></param>
public ExpressionTaskListener(IExpression expression)
{
this.expression = expression;
}
/// <summary>
///
/// </summary>
/// <param name="delegateTask"></param>
public virtual void Notify(IDelegateTask delegateTask)
{
expression.GetValue(delegateTask);
}
/// <summary>
/// returns the expression text for this task listener. Comes in handy if you want to check which listeners you already have.
/// </summary>
public virtual string ExpressionText
{
get
{
return expression.ExpressionText;
}
}
}
} | 28.666667 | 133 | 0.6 | [
"Apache-2.0"
] | zhangzihan/nactivity | NActiviti/Sys.Bpm.Engine/Engine/impl/bpmn/listener/ExpressionTaskListener.cs | 1,722 | C# |
using Unity.Entities;
namespace Match3Game
{
public static class StateMachineHelper
{
public interface IStateTransition<TState>
{
TState State { get; }
}
public static TState TryFindTransition<TTransition, TState>(
EntityQueryBuilder entities, TState from, TState[] to
)
where TTransition : struct, IComponentData, IStateTransition<TState>
where TState : System.Enum
{
TState target = from;
var c = System.Collections.Generic.EqualityComparer<TState>.Default;
#if UNITY_EDITOR
int numTransitions = 0;
entities.ForEach((ref TTransition transition) =>
{
bool match = false;
for (int i = 0; i < to.Length; i++) {
if (c.Equals(transition.State, to[i])) {
target = to[i];
match = true;
break;
}
}
if (!match)
{
UnityEngine.Debug.LogError($"Invalid transition from {from} to {transition.State}, expected {to}.");
}
numTransitions += 1;
});
if (numTransitions > 1)
{
UnityEngine.Debug.LogError($"Multiple transitions from {from}.");
}
#else
entities.ForEach((ref TTransition transition) =>
{
for (int i = 0; i < to.Length; i++) {
if (c.Equals(transition.State, to[i])) {
target = to[i];
break;
}
}
}
#endif
return target;
}
public static TState TryFindTransition<TTransition, TState>(
EntityQueryBuilder entities, TState from, TState to
)
where TTransition : struct, IComponentData, IStateTransition<TState>
where TState : System.Enum
{
TState target = from;
var c = System.Collections.Generic.EqualityComparer<TState>.Default;
#if UNITY_EDITOR
int numTransitions = 0;
entities.ForEach((ref TTransition transition) =>
{
if (c.Equals(transition.State, to))
{
target = to;
}
else
{
UnityEngine.Debug.LogError($"Invalid transition from {from} to {transition.State}, expected {to}.");
}
numTransitions += 1;
});
if (numTransitions > 1)
{
UnityEngine.Debug.LogError($"Multiple transitions from {from}.");
}
#else
entities.ForEach((ref TTransition transition) =>
{
if (c.Equals(transition.State, to))
{
target = to;
}
}
#endif
return target;
}
}
}
| 31.919192 | 121 | 0.449051 | [
"MIT"
] | sschoener/dots3 | Assets/Scripts/StateMachineHelper.cs | 3,160 | C# |
using Ryujinx.Common;
using Ryujinx.Common.Logging;
using Ryujinx.Cpu;
using Ryujinx.HLE.HOS.Services.Account.Acc.AccountService;
using System.Collections.Generic;
namespace Ryujinx.HLE.HOS.Services.Account.Acc
{
class ApplicationServiceServer
{
readonly AccountServiceFlag _serviceFlag;
public ApplicationServiceServer(AccountServiceFlag serviceFlag)
{
_serviceFlag = serviceFlag;
}
public ResultCode GetUserCountImpl(ServiceCtx context)
{
context.ResponseData.Write(context.Device.System.State.Account.GetUserCount());
return ResultCode.Success;
}
public ResultCode GetUserExistenceImpl(ServiceCtx context)
{
ResultCode resultCode = CheckUserId(context, out UserId userId);
if (resultCode != ResultCode.Success)
{
return resultCode;
}
context.ResponseData.Write(context.Device.System.State.Account.TryGetUser(userId, out _));
return ResultCode.Success;
}
public ResultCode ListAllUsers(ServiceCtx context)
{
return WriteUserList(context, context.Device.System.State.Account.GetAllUsers());
}
public ResultCode ListOpenUsers(ServiceCtx context)
{
return WriteUserList(context, context.Device.System.State.Account.GetOpenedUsers());
}
private ResultCode WriteUserList(ServiceCtx context, IEnumerable<UserProfile> profiles)
{
if (context.Request.RecvListBuff.Count == 0)
{
return ResultCode.InvalidInputBuffer;
}
long outputPosition = context.Request.RecvListBuff[0].Position;
long outputSize = context.Request.RecvListBuff[0].Size;
MemoryHelper.FillWithZeros(context.Memory, outputPosition, (int)outputSize);
ulong offset = 0;
foreach (UserProfile userProfile in profiles)
{
if (offset + 0x10 > (ulong)outputSize)
{
break;
}
context.Memory.Write((ulong)outputPosition + offset, userProfile.UserId.High);
context.Memory.Write((ulong)outputPosition + offset + 8, userProfile.UserId.Low);
offset += 0x10;
}
return ResultCode.Success;
}
public ResultCode GetLastOpenedUser(ServiceCtx context)
{
context.Device.System.State.Account.LastOpenedUser.UserId.Write(context.ResponseData);
return ResultCode.Success;
}
public ResultCode GetProfile(ServiceCtx context, out IProfile profile)
{
profile = default;
ResultCode resultCode = CheckUserId(context, out UserId userId);
if (resultCode != ResultCode.Success)
{
return resultCode;
}
if (!context.Device.System.State.Account.TryGetUser(userId, out UserProfile userProfile))
{
Logger.Warning?.Print(LogClass.ServiceAcc, $"User 0x{userId} not found!");
return ResultCode.UserNotFound;
}
profile = new IProfile(userProfile);
// Doesn't occur in our case.
// return ResultCode.NullObject;
return ResultCode.Success;
}
public ResultCode IsUserRegistrationRequestPermitted(ServiceCtx context)
{
context.ResponseData.Write(_serviceFlag != AccountServiceFlag.Application);
return ResultCode.Success;
}
public ResultCode TrySelectUserWithoutInteraction(ServiceCtx context)
{
if (context.Device.System.State.Account.GetUserCount() != 1)
{
// Invalid UserId.
UserId.Null.Write(context.ResponseData);
return ResultCode.UserNotFound;
}
bool isNetworkServiceAccountRequired = context.RequestData.ReadBoolean();
if (isNetworkServiceAccountRequired)
{
// NOTE: This checks something related to baas (online), and then return an invalid UserId if the check in baas returns an error code.
// In our case, we can just log it for now.
Logger.Stub?.PrintStub(LogClass.ServiceAcc, new { isNetworkServiceAccountRequired });
}
// NOTE: As we returned an invalid UserId if there is more than one user earlier, now we can return only the first one.
context.Device.System.State.Account.GetFirst().UserId.Write(context.ResponseData);
return ResultCode.Success;
}
public ResultCode StoreSaveDataThumbnail(ServiceCtx context)
{
ResultCode resultCode = CheckUserId(context, out UserId userId);
if (resultCode != ResultCode.Success)
{
return resultCode;
}
if (context.Request.SendBuff.Count == 0)
{
return ResultCode.InvalidInputBuffer;
}
long inputPosition = context.Request.SendBuff[0].Position;
long inputSize = context.Request.SendBuff[0].Size;
if (inputSize != 0x24000)
{
return ResultCode.InvalidInputBufferSize;
}
byte[] thumbnailBuffer = new byte[inputSize];
context.Memory.Read((ulong)inputPosition, thumbnailBuffer);
// NOTE: Account service call nn::fs::WriteSaveDataThumbnailFile().
// TODO: Store thumbnailBuffer somewhere, in save data 0x8000000000000010 ?
Logger.Stub?.PrintStub(LogClass.ServiceAcc);
return ResultCode.Success;
}
public ResultCode ClearSaveDataThumbnail(ServiceCtx context)
{
ResultCode resultCode = CheckUserId(context, out UserId userId);
if (resultCode != ResultCode.Success)
{
return resultCode;
}
/*
// NOTE: Doesn't occur in our case.
if (userId == null)
{
return ResultCode.InvalidArgument;
}
*/
// NOTE: Account service call nn::fs::WriteSaveDataThumbnailFileHeader();
// TODO: Clear the Thumbnail somewhere, in save data 0x8000000000000010 ?
Logger.Stub?.PrintStub(LogClass.ServiceAcc);
return ResultCode.Success;
}
public ResultCode ListQualifiedUsers(ServiceCtx context)
{
// TODO: Determine how users are "qualified". We assume all users are "qualified" for now.
return WriteUserList(context, context.Device.System.State.Account.GetAllUsers());
}
public ResultCode CheckUserId(ServiceCtx context, out UserId userId)
{
userId = context.RequestData.ReadStruct<UserId>();
if (userId.IsNull)
{
return ResultCode.NullArgument;
}
return ResultCode.Success;
}
}
} | 32.170404 | 150 | 0.59409 | [
"MIT"
] | 312811719/Ryujinx | Ryujinx.HLE/HOS/Services/Account/Acc/ApplicationServiceServer.cs | 7,176 | C# |
namespace MTProto.NET.Schema.TL
{
public abstract class TLAbsMessagesFilter : MTObject
{
}
}
| 15 | 56 | 0.695238 | [
"MIT"
] | Gostareh-Negar/TeleNet | MTProto.NET/Schema/TL/_generated/TLAbsMessagesFilter.cs | 105 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Cci;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.Extensions.Logging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Rebuild
{
public class CompilationOptionsReader
{
// GUIDs specified in https://github.com/dotnet/runtime/blob/main/docs/design/specs/PortablePdb-Metadata.md#document-table-0x30
public static readonly Guid HashAlgorithmSha1 = unchecked(new Guid((int)0xff1816ec, (short)0xaa5e, 0x4d10, 0x87, 0xf7, 0x6f, 0x49, 0x63, 0x83, 0x34, 0x60));
public static readonly Guid HashAlgorithmSha256 = unchecked(new Guid((int)0x8829d00f, 0x11b8, 0x4213, 0x87, 0x8b, 0x77, 0x0e, 0x85, 0x97, 0xac, 0x16));
// https://github.com/dotnet/runtime/blob/main/docs/design/specs/PortablePdb-Metadata.md#compilation-metadata-references-c-and-vb-compilers
public static readonly Guid MetadataReferenceInfoGuid = new Guid("7E4D4708-096E-4C5C-AEDA-CB10BA6A740D");
// https://github.com/dotnet/runtime/blob/main/docs/design/specs/PortablePdb-Metadata.md#compilation-options-c-and-vb-compilers
public static readonly Guid CompilationOptionsGuid = new Guid("B5FEEC05-8CD0-4A83-96DA-466284BB4BD8");
// https://github.com/dotnet/runtime/blob/main/docs/design/specs/PortablePdb-Metadata.md#embedded-source-c-and-vb-compilers
public static readonly Guid EmbeddedSourceGuid = new Guid("0E8A571B-6926-466E-B4AD-8AB04611F5FE");
// https://github.com/dotnet/runtime/blob/main/docs/design/specs/PortablePdb-Metadata.md#source-link-c-and-vb-compilers
public static readonly Guid SourceLinkGuid = new Guid("CC110556-A091-4D38-9FEC-25AB9A351A6A");
public MetadataReader PdbReader { get; }
public PEReader PeReader { get; }
private readonly ILogger _logger;
public bool HasMetadataCompilationOptions => TryGetMetadataCompilationOptions(out _);
private MetadataCompilationOptions? _metadataCompilationOptions;
private byte[]? _sourceLinkUTF8;
public CompilationOptionsReader(ILogger logger, MetadataReader pdbReader, PEReader peReader)
{
_logger = logger;
PdbReader = pdbReader;
PeReader = peReader;
}
public bool TryGetMetadataCompilationOptionsBlobReader(out BlobReader reader)
{
return TryGetCustomDebugInformationBlobReader(CompilationOptionsGuid, out reader);
}
public BlobReader GetMetadataCompilationOptionsBlobReader()
{
if (!TryGetMetadataCompilationOptionsBlobReader(out var reader))
{
throw new InvalidOperationException(RebuildResources.Does_not_contain_metadata_compilation_options);
}
return reader;
}
internal bool TryGetMetadataCompilationOptions([NotNullWhen(true)] out MetadataCompilationOptions? options)
{
if (_metadataCompilationOptions is null && TryGetMetadataCompilationOptionsBlobReader(out var optionsBlob))
{
_metadataCompilationOptions = new MetadataCompilationOptions(ParseCompilationOptions(optionsBlob));
}
options = _metadataCompilationOptions;
return options != null;
}
internal MetadataCompilationOptions GetMetadataCompilationOptions()
{
if (_metadataCompilationOptions is null)
{
var optionsBlob = GetMetadataCompilationOptionsBlobReader();
_metadataCompilationOptions = new MetadataCompilationOptions(ParseCompilationOptions(optionsBlob));
}
return _metadataCompilationOptions;
}
/// <summary>
/// Get the specified <see cref="LanguageNames"/> for this compilation.
/// </summary>
public string GetLanguageName()
{
var pdbCompilationOptions = GetMetadataCompilationOptions();
if (!pdbCompilationOptions.TryGetUniqueOption(CompilationOptionNames.Language, out var language))
{
throw new Exception(RebuildResources.Invalid_language_name);
}
return language;
}
public Encoding GetEncoding()
{
using var scope = _logger.BeginScope("Encoding");
var optionsReader = GetMetadataCompilationOptions();
optionsReader.TryGetUniqueOption(_logger, CompilationOptionNames.DefaultEncoding, out var defaultEncoding);
optionsReader.TryGetUniqueOption(_logger, CompilationOptionNames.FallbackEncoding, out var fallbackEncoding);
var encodingString = defaultEncoding ?? fallbackEncoding;
var encoding = encodingString is null
? Encoding.UTF8
: Encoding.GetEncoding(encodingString);
return encoding;
}
public byte[]? GetSourceLinkUTF8()
{
if (_sourceLinkUTF8 is null && TryGetCustomDebugInformationBlobReader(SourceLinkGuid, out var optionsBlob))
{
_sourceLinkUTF8 = optionsBlob.ReadBytes(optionsBlob.Length);
}
return _sourceLinkUTF8;
}
public string? GetMainTypeName() => GetMainMethodInfo()?.MainTypeName;
public (string MainTypeName, string MainMethodName)? GetMainMethodInfo()
{
if (!(PdbReader.DebugMetadataHeader is { } header) ||
header.EntryPoint.IsNil)
{
return null;
}
var mdReader = PeReader.GetMetadataReader();
var methodDefinition = mdReader.GetMethodDefinition(header.EntryPoint);
var methodName = mdReader.GetString(methodDefinition.Name);
// Here we only want to give the caller the main method name and containing type name if the method is named "Main" per convention.
// If the main method has another name, we have to assume that specifying a main type name won't work.
// For example, if the compilation uses top-level statements.
if (methodName != WellKnownMemberNames.EntryPointMethodName)
{
return null;
}
var typeHandle = methodDefinition.GetDeclaringType();
var typeDefinition = mdReader.GetTypeDefinition(typeHandle);
var typeName = mdReader.GetString(typeDefinition.Name);
if (!typeDefinition.Namespace.IsNil)
{
var namespaceName = mdReader.GetString(typeDefinition.Namespace);
typeName = namespaceName + "." + typeName;
}
return (typeName, methodName);
}
public int GetSourceFileCount()
=> int.Parse(GetMetadataCompilationOptions().GetUniqueOption(CompilationOptionNames.SourceFileCount));
public IEnumerable<EmbeddedSourceTextInfo> GetEmbeddedSourceTextInfo()
=> GetSourceTextInfoCore()
.Select(x => ResolveEmbeddedSource(x.DocumentHandle, x.SourceTextInfo))
.WhereNotNull();
private IEnumerable<(DocumentHandle DocumentHandle, SourceTextInfo SourceTextInfo)> GetSourceTextInfoCore()
{
var encoding = GetEncoding();
var sourceFileCount = GetSourceFileCount();
foreach (var documentHandle in PdbReader.Documents.Take(sourceFileCount))
{
var document = PdbReader.GetDocument(documentHandle);
var name = PdbReader.GetString(document.Name);
var hashAlgorithmGuid = PdbReader.GetGuid(document.HashAlgorithm);
var hashAlgorithm =
hashAlgorithmGuid == HashAlgorithmSha1 ? SourceHashAlgorithm.Sha1
: hashAlgorithmGuid == HashAlgorithmSha256 ? SourceHashAlgorithm.Sha256
: SourceHashAlgorithm.None;
var hash = PdbReader.GetBlobBytes(document.Hash);
var sourceTextInfo = new SourceTextInfo(name, hashAlgorithm, hash.ToImmutableArray(), encoding);
yield return (documentHandle, sourceTextInfo);
}
}
private EmbeddedSourceTextInfo? ResolveEmbeddedSource(DocumentHandle document, SourceTextInfo sourceTextInfo)
{
byte[] bytes = (from handle in PdbReader.GetCustomDebugInformation(document)
let cdi = PdbReader.GetCustomDebugInformation(handle)
where PdbReader.GetGuid(cdi.Kind) == EmbeddedSourceGuid
select PdbReader.GetBlobBytes(cdi.Value)).SingleOrDefault();
if (bytes is null)
{
return null;
}
int uncompressedSize = BitConverter.ToInt32(bytes, 0);
var stream = new MemoryStream(bytes, sizeof(int), bytes.Length - sizeof(int));
byte[]? compressedHash = null;
if (uncompressedSize != 0)
{
using var algorithm = CryptographicHashProvider.TryGetAlgorithm(sourceTextInfo.HashAlgorithm) ?? throw new InvalidOperationException();
compressedHash = algorithm.ComputeHash(bytes);
var decompressed = new MemoryStream(uncompressedSize);
using (var deflater = new DeflateStream(stream, CompressionMode.Decompress))
{
deflater.CopyTo(decompressed);
}
if (decompressed.Length != uncompressedSize)
{
throw new InvalidDataException();
}
stream = decompressed;
}
using (stream)
{
// todo: IVT and EncodedStringText.Create?
var embeddedText = SourceText.From(stream, encoding: sourceTextInfo.SourceTextEncoding, checksumAlgorithm: sourceTextInfo.HashAlgorithm, canBeEmbedded: true);
return new EmbeddedSourceTextInfo(sourceTextInfo, embeddedText, compressedHash?.ToImmutableArray() ?? ImmutableArray<byte>.Empty);
}
}
public byte[]? GetPublicKey()
{
var metadataReader = PeReader.GetMetadataReader();
if (!metadataReader.IsAssembly)
{
return null;
}
var blob = metadataReader.GetAssemblyDefinition().PublicKey;
if (blob.IsNil)
{
return null;
}
var reader = metadataReader.GetBlobReader(blob);
return reader.ReadBytes(reader.Length);
}
public unsafe ResourceDescription[]? GetManifestResources()
{
var metadataReader = PeReader.GetMetadataReader();
if (PeReader.PEHeaders.CorHeader is not { } corHeader
|| !PeReader.PEHeaders.TryGetDirectoryOffset(corHeader.ResourcesDirectory, out var resourcesOffset))
{
return null;
}
var result = metadataReader.ManifestResources.Select(handle =>
{
var resource = metadataReader.GetManifestResource(handle);
var name = metadataReader.GetString(resource.Name);
var resourceStart = PeReader.GetEntireImage().Pointer + resourcesOffset + resource.Offset;
var length = *(int*)resourceStart;
var contentPtr = resourceStart + sizeof(int);
var content = new byte[length];
Marshal.Copy(new IntPtr(contentPtr), content, 0, length);
var isPublic = (resource.Attributes & ManifestResourceAttributes.Public) != 0;
var description = new ResourceDescription(name, dataProvider: () => new MemoryStream(content), isPublic);
return description;
}).ToArray();
return result;
}
public (ImmutableArray<SyntaxTree> SyntaxTrees, ImmutableArray<MetadataReference> MetadataReferences) ResolveArtifacts(
IRebuildArtifactResolver resolver,
Func<string, SourceText, SyntaxTree> createSyntaxTreeFunc)
{
var syntaxTrees = ResolveSyntaxTrees();
var metadataReferences = ResolveMetadataReferences();
return (syntaxTrees, metadataReferences);
ImmutableArray<SyntaxTree> ResolveSyntaxTrees()
{
var sourceFileCount = GetSourceFileCount();
var builder = ImmutableArray.CreateBuilder<SyntaxTree>(sourceFileCount);
foreach (var (documentHandle, sourceTextInfo) in GetSourceTextInfoCore())
{
SourceText sourceText;
if (ResolveEmbeddedSource(documentHandle, sourceTextInfo) is { } embeddedSourceTextInfo)
{
sourceText = embeddedSourceTextInfo.SourceText;
}
else
{
sourceText = resolver.ResolveSourceText(sourceTextInfo);
if (!sourceText.GetChecksum().SequenceEqual(sourceTextInfo.Hash))
{
throw new InvalidOperationException();
}
}
var syntaxTree = createSyntaxTreeFunc(sourceTextInfo.OriginalSourceFilePath, sourceText);
builder.Add(syntaxTree);
}
return builder.MoveToImmutable();
}
ImmutableArray<MetadataReference> ResolveMetadataReferences()
{
var builder = ImmutableArray.CreateBuilder<MetadataReference>();
foreach (var metadataReferenceInfo in GetMetadataReferenceInfo())
{
var metadataReference = resolver.ResolveMetadataReference(metadataReferenceInfo);
if (metadataReference.Properties.EmbedInteropTypes != metadataReferenceInfo.EmbedInteropTypes)
{
throw new InvalidOperationException();
}
if (!(
(metadataReferenceInfo.ExternAlias is null && metadataReference.Properties.Aliases.IsEmpty) ||
(metadataReferenceInfo.ExternAlias == metadataReference.Properties.Aliases.SingleOrDefault())
))
{
throw new InvalidOperationException();
}
builder.Add(metadataReference);
}
return builder.ToImmutable();
}
}
public IEnumerable<MetadataReferenceInfo> GetMetadataReferenceInfo()
{
if (!TryGetCustomDebugInformationBlobReader(MetadataReferenceInfoGuid, out var blobReader))
{
throw new InvalidOperationException();
}
var builder = ImmutableArray.CreateBuilder<MetadataReference>();
while (blobReader.RemainingBytes > 0)
{
// Order of information
// File name (null terminated string): A.exe
// Extern Alias (null terminated string): a1,a2,a3
// EmbedInteropTypes/MetadataImageKind (byte)
// COFF header Timestamp field (4 byte int)
// COFF header SizeOfImage field (4 byte int)
// MVID (Guid, 24 bytes)
var terminatorIndex = blobReader.IndexOf(0);
var name = blobReader.ReadUTF8(terminatorIndex);
blobReader.SkipNullTerminator();
terminatorIndex = blobReader.IndexOf(0);
var externAliases = blobReader.ReadUTF8(terminatorIndex);
blobReader.SkipNullTerminator();
var embedInteropTypesAndKind = blobReader.ReadByte();
// Only the last two bits are used, verify nothing else in the
// byte has data.
if ((embedInteropTypesAndKind & 0b11111100) != 0)
{
throw new InvalidDataException(string.Format(RebuildResources.Unexpected_value_for_EmbedInteropTypes_MetadataImageKind_0, embedInteropTypesAndKind));
}
var embedInteropTypes = (embedInteropTypesAndKind & 0b10) == 0b10;
var kind = (embedInteropTypesAndKind & 0b1) == 0b1
? MetadataImageKind.Assembly
: MetadataImageKind.Module;
var timestamp = blobReader.ReadInt32();
var imageSize = blobReader.ReadInt32();
var mvid = blobReader.ReadGuid();
if (string.IsNullOrEmpty(externAliases))
{
yield return new MetadataReferenceInfo(
name,
mvid,
ExternAlias: null,
kind,
embedInteropTypes,
timestamp,
imageSize);
}
else
{
foreach (var alias in externAliases.Split(','))
{
// The "global" alias is an invention of the tooling on top of the compiler.
// The compiler itself just sees "global" as a reference without any aliases
// and we need to mimic that here.
yield return new MetadataReferenceInfo(
name,
mvid,
ExternAlias: alias == "global" ? null : alias,
kind,
embedInteropTypes,
timestamp,
imageSize);
}
}
}
}
private bool TryGetCustomDebugInformationBlobReader(Guid infoGuid, out BlobReader blobReader)
{
var blobs = from cdiHandle in PdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition)
let cdi = PdbReader.GetCustomDebugInformation(cdiHandle)
where PdbReader.GetGuid(cdi.Kind) == infoGuid
select PdbReader.GetBlobReader(cdi.Value);
if (blobs.Any())
{
blobReader = blobs.Single();
return true;
}
blobReader = default;
return false;
}
public bool HasEmbeddedPdb => PeReader.ReadDebugDirectory().Any(entry => entry.Type == DebugDirectoryEntryType.EmbeddedPortablePdb);
private static ImmutableArray<(string, string)> ParseCompilationOptions(BlobReader blobReader)
{
// Compiler flag bytes are UTF-8 null-terminated key-value pairs
string? key = null;
List<(string, string)> options = new List<(string, string)>();
for (; ; )
{
var nullIndex = blobReader.IndexOf(0);
if (nullIndex == -1)
{
break;
}
var value = blobReader.ReadUTF8(nullIndex);
blobReader.SkipNullTerminator();
if (key is null)
{
if (value is null or { Length: 0 })
{
throw new InvalidDataException(RebuildResources.Encountered_null_or_empty_key_for_compilation_options_pairs);
}
key = value;
}
else
{
options.Add((key, value));
key = null;
}
}
return options.ToImmutableArray();
}
}
}
| 42.115702 | 174 | 0.592327 | [
"MIT"
] | 333fred/roslyn | src/Compilers/Core/Rebuild/CompilationOptionsReader.cs | 20,386 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DbUtilsDemo.Models
{
[DisplayColumn("FirstName")]
public class Employee
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Column("EmployeeID")]
public int Id { get; set; }
[Required]
[Display(Name = "Last name")]
public string LastName { get; set; }
[Required]
[Display(Name = "First name")]
public string FirstName { get; set; }
[NotMapped]
public string FullName {
get {
string res = this.FirstName;
if (!string.IsNullOrEmpty(res))
res += " ";
if (!string.IsNullOrEmpty(this.LastName))
res += this.LastName;
return res;
}
}
[MaxLength(30)]
public string Title { get; set; }
public string TitleOfCourtesy { get; set; }
[Display(Name = "Birth date")]
public DateTime? BirthDate { get; set; }
public DateTime? HireDate { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
[MaxLength(24)]
public string HomePhone { get; set; }
[MaxLength(4)]
public string Extension { get; set; }
[ScaffoldColumn(false)]
public byte[] Photo { get; set; }
public string PhotoPath { get; set; }
public string Notes { get; set; }
[ScaffoldColumn(false)]
public int? ReportsTo { get; set; }
[ForeignKey("ReportsTo")]
public virtual Employee Manager { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
} | 23.853659 | 62 | 0.555215 | [
"MIT"
] | KorzhCom/Korzh.DbUtils | samples/DbUtilsDemo.AspNetCore/Data/Models/Employee.cs | 1,958 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.